Completed
Branch FET-9856-direct-instantiation (d3e084)
by
unknown
57:58 queued 46:07
created
core/EE_Request_Handler.core.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
     /**
348 348
      * remove param
349 349
      *
350
-     * @param $key
350
+     * @param string $key
351 351
      * @return    void
352 352
      */
353 353
     public function un_set($key)
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
 
384 384
 
385 385
     /**
386
-     * @param $string
386
+     * @param string $string
387 387
      * @return void
388 388
      */
389 389
     public function add_output($string)
Please login to merge, or discard this patch.
Indentation   +443 added lines, -443 removed lines patch added patch discarded remove patch
@@ -13,478 +13,478 @@
 block discarded – undo
13 13
 final class EE_Request_Handler implements InterminableInterface
14 14
 {
15 15
 
16
-    /**
17
-     * $_REQUEST parameters
18
-     *
19
-     * @var array $_params
20
-     */
21
-    private $_params;
22
-
23
-    /**
24
-     * @var array $_notice
25
-     */
26
-    private $_notice = array();
27
-
28
-    /**
29
-     * rendered output to be returned to WP
30
-     *
31
-     * @var string $_output
32
-     */
33
-    private $_output = '';
34
-
35
-    /**
36
-     * whether current request is via AJAX
37
-     *
38
-     * @var boolean $ajax
39
-     */
40
-    public $ajax = false;
41
-
42
-    /**
43
-     * whether current request is via AJAX from the frontend of the site
44
-     *
45
-     * @var boolean $front_ajax
46
-     */
47
-    public $front_ajax = false;
48
-
49
-
50
-
51
-    /**
52
-     * @param  EE_Request $request
53
-     */
54
-    public function __construct(EE_Request $request)
55
-    {
56
-        // grab request vars
57
-        $this->_params = $request->params();
58
-        // AJAX ???
59
-        $this->ajax = defined('DOING_AJAX') && DOING_AJAX;
60
-        $this->front_ajax = defined('EE_FRONT_AJAX') && EE_FRONT_AJAX;
61
-        do_action('AHEE__EE_Request_Handler__construct__complete');
62
-    }
63
-
64
-
65
-
66
-    /**
67
-     * @param WP $wp
68
-     * @return void
69
-     * @throws EE_Error
70
-     * @throws ReflectionException
71
-     */
72
-    public function parse_request($wp = null)
73
-    {
74
-        //if somebody forgot to provide us with WP, that's ok because its global
75
-        if (! $wp instanceof WP) {
76
-            global $wp;
77
-        }
78
-        $this->set_request_vars($wp);
79
-    }
80
-
81
-
82
-
83
-    /**
84
-     * @param WP $wp
85
-     * @return void
86
-     * @throws EE_Error
87
-     * @throws ReflectionException
88
-     */
89
-    public function set_request_vars($wp = null)
90
-    {
91
-        if (! is_admin()) {
92
-            // set request post_id
93
-            $this->set('post_id', $this->get_post_id_from_request($wp));
94
-            // set request post name
95
-            $this->set('post_name', $this->get_post_name_from_request($wp));
96
-            // set request post_type
97
-            $this->set('post_type', $this->get_post_type_from_request($wp));
98
-            // true or false ? is this page being used by EE ?
99
-            $this->set_espresso_page();
100
-        }
101
-    }
102
-
103
-
104
-
105
-    /**
106
-     * @param WP $wp
107
-     * @return int
108
-     */
109
-    public function get_post_id_from_request($wp = null)
110
-    {
111
-        if (! $wp instanceof WP) {
112
-            global $wp;
113
-        }
114
-        $post_id = null;
115
-        if (isset($wp->query_vars['p'])) {
116
-            $post_id = $wp->query_vars['p'];
117
-        }
118
-        if (! $post_id && isset($wp->query_vars['page_id'])) {
119
-            $post_id = $wp->query_vars['page_id'];
120
-        }
121
-        if (! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
122
-            $post_id = basename($wp->request);
123
-        }
124
-        return $post_id;
125
-    }
126
-
127
-
128
-
129
-    /**
130
-     * @param WP $wp
131
-     * @return string
132
-     */
133
-    public function get_post_name_from_request($wp = null)
134
-    {
135
-        if (! $wp instanceof WP) {
136
-            global $wp;
137
-        }
138
-        $post_name = null;
139
-        if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
140
-            $post_name = $wp->query_vars['name'];
141
-        }
142
-        if (! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
143
-            $post_name = $wp->query_vars['pagename'];
144
-        }
145
-        if (! $post_name && $wp->request !== null && ! empty($wp->request)) {
146
-            $possible_post_name = basename($wp->request);
147
-            if (! is_numeric($possible_post_name)) {
148
-                /** @type WPDB $wpdb */
149
-                global $wpdb;
150
-                $SQL =
151
-                    "SELECT ID from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND post_name=%s";
152
-                $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
153
-                if ($possible_post_name) {
154
-                    $post_name = $possible_post_name;
155
-                }
156
-            }
157
-        }
158
-        if (! $post_name && $this->get('post_id')) {
159
-            /** @type WPDB $wpdb */
160
-            global $wpdb;
161
-            $SQL =
162
-                "SELECT post_name from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND ID=%d";
163
-            $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->get('post_id')));
164
-            if ($possible_post_name) {
165
-                $post_name = $possible_post_name;
166
-            }
167
-        }
168
-        return $post_name;
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * @param WP $wp
175
-     * @return mixed
176
-     */
177
-    public function get_post_type_from_request($wp = null)
178
-    {
179
-        if (! $wp instanceof WP) {
180
-            global $wp;
181
-        }
182
-        return isset($wp->query_vars['post_type'])
183
-            ? $wp->query_vars['post_type']
184
-            : null;
185
-    }
186
-
187
-
188
-
189
-    /**
190
-     * Just a helper method for getting the url for the displayed page.
191
-     *
192
-     * @param  WP $wp
193
-     * @return string
194
-     */
195
-    public function get_current_page_permalink($wp = null)
196
-    {
197
-        $post_id = $this->get_post_id_from_request($wp);
198
-        if ($post_id) {
199
-            $current_page_permalink = get_permalink($post_id);
200
-        } else {
201
-            if (! $wp instanceof WP) {
202
-                global $wp;
203
-            }
204
-            if ($wp->request) {
205
-                $current_page_permalink = site_url($wp->request);
206
-            } else {
207
-                $current_page_permalink = esc_url(site_url($_SERVER['REQUEST_URI']));
208
-            }
209
-        }
210
-        return $current_page_permalink;
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * @return bool
217
-     * @throws EE_Error
218
-     * @throws ReflectionException
219
-     */
220
-    public function test_for_espresso_page()
221
-    {
222
-        global $wp;
223
-        /** @type EE_CPT_Strategy $EE_CPT_Strategy */
224
-        $EE_CPT_Strategy = EE_Registry::instance()->load_core('CPT_Strategy');
225
-        $espresso_CPT_taxonomies = $EE_CPT_Strategy->get_CPT_taxonomies();
226
-        if (is_array($espresso_CPT_taxonomies)) {
227
-            foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
228
-                if (isset($wp->query_vars, $wp->query_vars[$espresso_CPT_taxonomy])) {
229
-                    return true;
230
-                }
231
-            }
232
-        }
233
-        // load espresso CPT endpoints
234
-        $espresso_CPT_endpoints = $EE_CPT_Strategy->get_CPT_endpoints();
235
-        $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
236
-        $post_types = (array)$this->get('post_type');
237
-        foreach ($post_types as $post_type) {
238
-            // was a post name passed ?
239
-            if (isset($post_type_CPT_endpoints[$post_type])) {
240
-                // kk we know this is an espresso page, but is it a specific post ?
241
-                if (! $this->get('post_name')) {
242
-                    // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
243
-                    $post_name = isset($post_type_CPT_endpoints[$this->get('post_type')])
244
-                        ? $post_type_CPT_endpoints[$this->get('post_type')]
245
-                        : '';
246
-                    // if the post type matches on of our then set the endpoint
247
-                    if ($post_name) {
248
-                        $this->set('post_name', $post_name);
249
-                    }
250
-                }
251
-                return true;
252
-            }
253
-        }
254
-        return false;
255
-    }
256
-
257
-
258
-
259
-    /**
260
-     * @param null|bool $value
261
-     * @return void
262
-     * @throws EE_Error
263
-     * @throws ReflectionException
264
-     */
265
-    public function set_espresso_page($value = null)
266
-    {
267
-        $this->_params['is_espresso_page'] = ! empty($value)
268
-            ? $value
269
-            : $this->test_for_espresso_page();
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * @return    mixed
276
-     */
277
-    public function is_espresso_page()
278
-    {
279
-        return isset($this->_params['is_espresso_page'])
280
-            ? $this->_params['is_espresso_page']
281
-            : false;
282
-    }
283
-
284
-
285
-
286
-    /**
287
-     * returns contents of $_REQUEST
288
-     *
289
-     * @return array
290
-     */
291
-    public function params()
292
-    {
293
-        return $this->_params;
294
-    }
295
-
296
-
297
-
298
-    /**
299
-     * @param      $key
300
-     * @param      $value
301
-     * @param bool $override_ee
302
-     * @return    void
303
-     */
304
-    public function set($key, $value, $override_ee = false)
305
-    {
306
-        // don't allow "ee" to be overwritten unless explicitly instructed to do so
307
-        if (
308
-            $key !== 'ee'
309
-            || ($key === 'ee' && empty($this->_params['ee']))
310
-            || ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
311
-        ) {
312
-            $this->_params[$key] = $value;
313
-        }
314
-    }
315
-
316
-
317
-
318
-    /**
319
-     * @param      $key
320
-     * @param null $default
321
-     * @return    mixed
322
-     */
323
-    public function get($key, $default = null)
324
-    {
325
-        return isset($this->_params[$key])
326
-            ? $this->_params[$key]
327
-            : $default;
328
-    }
329
-
330
-
331
-
332
-    /**
333
-     * check if param exists
334
-     *
335
-     * @param $key
336
-     * @return    boolean
337
-     */
338
-    public function is_set($key)
339
-    {
340
-        return isset($this->_params[$key])
341
-            ? true
342
-            : false;
343
-    }
344
-
345
-
346
-
347
-    /**
348
-     * remove param
349
-     *
350
-     * @param $key
351
-     * @return    void
352
-     */
353
-    public function un_set($key)
354
-    {
355
-        unset($this->_params[$key]);
356
-    }
357
-
358
-
359
-
360
-    /**
361
-     * @param $key
362
-     * @param $value
363
-     * @return    void
364
-     */
365
-    public function set_notice($key, $value)
366
-    {
367
-        $this->_notice[$key] = $value;
368
-    }
369
-
370
-
16
+	/**
17
+	 * $_REQUEST parameters
18
+	 *
19
+	 * @var array $_params
20
+	 */
21
+	private $_params;
22
+
23
+	/**
24
+	 * @var array $_notice
25
+	 */
26
+	private $_notice = array();
27
+
28
+	/**
29
+	 * rendered output to be returned to WP
30
+	 *
31
+	 * @var string $_output
32
+	 */
33
+	private $_output = '';
34
+
35
+	/**
36
+	 * whether current request is via AJAX
37
+	 *
38
+	 * @var boolean $ajax
39
+	 */
40
+	public $ajax = false;
41
+
42
+	/**
43
+	 * whether current request is via AJAX from the frontend of the site
44
+	 *
45
+	 * @var boolean $front_ajax
46
+	 */
47
+	public $front_ajax = false;
48
+
49
+
50
+
51
+	/**
52
+	 * @param  EE_Request $request
53
+	 */
54
+	public function __construct(EE_Request $request)
55
+	{
56
+		// grab request vars
57
+		$this->_params = $request->params();
58
+		// AJAX ???
59
+		$this->ajax = defined('DOING_AJAX') && DOING_AJAX;
60
+		$this->front_ajax = defined('EE_FRONT_AJAX') && EE_FRONT_AJAX;
61
+		do_action('AHEE__EE_Request_Handler__construct__complete');
62
+	}
63
+
64
+
65
+
66
+	/**
67
+	 * @param WP $wp
68
+	 * @return void
69
+	 * @throws EE_Error
70
+	 * @throws ReflectionException
71
+	 */
72
+	public function parse_request($wp = null)
73
+	{
74
+		//if somebody forgot to provide us with WP, that's ok because its global
75
+		if (! $wp instanceof WP) {
76
+			global $wp;
77
+		}
78
+		$this->set_request_vars($wp);
79
+	}
80
+
81
+
82
+
83
+	/**
84
+	 * @param WP $wp
85
+	 * @return void
86
+	 * @throws EE_Error
87
+	 * @throws ReflectionException
88
+	 */
89
+	public function set_request_vars($wp = null)
90
+	{
91
+		if (! is_admin()) {
92
+			// set request post_id
93
+			$this->set('post_id', $this->get_post_id_from_request($wp));
94
+			// set request post name
95
+			$this->set('post_name', $this->get_post_name_from_request($wp));
96
+			// set request post_type
97
+			$this->set('post_type', $this->get_post_type_from_request($wp));
98
+			// true or false ? is this page being used by EE ?
99
+			$this->set_espresso_page();
100
+		}
101
+	}
102
+
103
+
104
+
105
+	/**
106
+	 * @param WP $wp
107
+	 * @return int
108
+	 */
109
+	public function get_post_id_from_request($wp = null)
110
+	{
111
+		if (! $wp instanceof WP) {
112
+			global $wp;
113
+		}
114
+		$post_id = null;
115
+		if (isset($wp->query_vars['p'])) {
116
+			$post_id = $wp->query_vars['p'];
117
+		}
118
+		if (! $post_id && isset($wp->query_vars['page_id'])) {
119
+			$post_id = $wp->query_vars['page_id'];
120
+		}
121
+		if (! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
122
+			$post_id = basename($wp->request);
123
+		}
124
+		return $post_id;
125
+	}
126
+
127
+
128
+
129
+	/**
130
+	 * @param WP $wp
131
+	 * @return string
132
+	 */
133
+	public function get_post_name_from_request($wp = null)
134
+	{
135
+		if (! $wp instanceof WP) {
136
+			global $wp;
137
+		}
138
+		$post_name = null;
139
+		if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
140
+			$post_name = $wp->query_vars['name'];
141
+		}
142
+		if (! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
143
+			$post_name = $wp->query_vars['pagename'];
144
+		}
145
+		if (! $post_name && $wp->request !== null && ! empty($wp->request)) {
146
+			$possible_post_name = basename($wp->request);
147
+			if (! is_numeric($possible_post_name)) {
148
+				/** @type WPDB $wpdb */
149
+				global $wpdb;
150
+				$SQL =
151
+					"SELECT ID from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND post_name=%s";
152
+				$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
153
+				if ($possible_post_name) {
154
+					$post_name = $possible_post_name;
155
+				}
156
+			}
157
+		}
158
+		if (! $post_name && $this->get('post_id')) {
159
+			/** @type WPDB $wpdb */
160
+			global $wpdb;
161
+			$SQL =
162
+				"SELECT post_name from {$wpdb->posts} WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND ID=%d";
163
+			$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->get('post_id')));
164
+			if ($possible_post_name) {
165
+				$post_name = $possible_post_name;
166
+			}
167
+		}
168
+		return $post_name;
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * @param WP $wp
175
+	 * @return mixed
176
+	 */
177
+	public function get_post_type_from_request($wp = null)
178
+	{
179
+		if (! $wp instanceof WP) {
180
+			global $wp;
181
+		}
182
+		return isset($wp->query_vars['post_type'])
183
+			? $wp->query_vars['post_type']
184
+			: null;
185
+	}
186
+
187
+
188
+
189
+	/**
190
+	 * Just a helper method for getting the url for the displayed page.
191
+	 *
192
+	 * @param  WP $wp
193
+	 * @return string
194
+	 */
195
+	public function get_current_page_permalink($wp = null)
196
+	{
197
+		$post_id = $this->get_post_id_from_request($wp);
198
+		if ($post_id) {
199
+			$current_page_permalink = get_permalink($post_id);
200
+		} else {
201
+			if (! $wp instanceof WP) {
202
+				global $wp;
203
+			}
204
+			if ($wp->request) {
205
+				$current_page_permalink = site_url($wp->request);
206
+			} else {
207
+				$current_page_permalink = esc_url(site_url($_SERVER['REQUEST_URI']));
208
+			}
209
+		}
210
+		return $current_page_permalink;
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * @return bool
217
+	 * @throws EE_Error
218
+	 * @throws ReflectionException
219
+	 */
220
+	public function test_for_espresso_page()
221
+	{
222
+		global $wp;
223
+		/** @type EE_CPT_Strategy $EE_CPT_Strategy */
224
+		$EE_CPT_Strategy = EE_Registry::instance()->load_core('CPT_Strategy');
225
+		$espresso_CPT_taxonomies = $EE_CPT_Strategy->get_CPT_taxonomies();
226
+		if (is_array($espresso_CPT_taxonomies)) {
227
+			foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
228
+				if (isset($wp->query_vars, $wp->query_vars[$espresso_CPT_taxonomy])) {
229
+					return true;
230
+				}
231
+			}
232
+		}
233
+		// load espresso CPT endpoints
234
+		$espresso_CPT_endpoints = $EE_CPT_Strategy->get_CPT_endpoints();
235
+		$post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
236
+		$post_types = (array)$this->get('post_type');
237
+		foreach ($post_types as $post_type) {
238
+			// was a post name passed ?
239
+			if (isset($post_type_CPT_endpoints[$post_type])) {
240
+				// kk we know this is an espresso page, but is it a specific post ?
241
+				if (! $this->get('post_name')) {
242
+					// there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
243
+					$post_name = isset($post_type_CPT_endpoints[$this->get('post_type')])
244
+						? $post_type_CPT_endpoints[$this->get('post_type')]
245
+						: '';
246
+					// if the post type matches on of our then set the endpoint
247
+					if ($post_name) {
248
+						$this->set('post_name', $post_name);
249
+					}
250
+				}
251
+				return true;
252
+			}
253
+		}
254
+		return false;
255
+	}
256
+
257
+
258
+
259
+	/**
260
+	 * @param null|bool $value
261
+	 * @return void
262
+	 * @throws EE_Error
263
+	 * @throws ReflectionException
264
+	 */
265
+	public function set_espresso_page($value = null)
266
+	{
267
+		$this->_params['is_espresso_page'] = ! empty($value)
268
+			? $value
269
+			: $this->test_for_espresso_page();
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * @return    mixed
276
+	 */
277
+	public function is_espresso_page()
278
+	{
279
+		return isset($this->_params['is_espresso_page'])
280
+			? $this->_params['is_espresso_page']
281
+			: false;
282
+	}
283
+
284
+
285
+
286
+	/**
287
+	 * returns contents of $_REQUEST
288
+	 *
289
+	 * @return array
290
+	 */
291
+	public function params()
292
+	{
293
+		return $this->_params;
294
+	}
295
+
296
+
297
+
298
+	/**
299
+	 * @param      $key
300
+	 * @param      $value
301
+	 * @param bool $override_ee
302
+	 * @return    void
303
+	 */
304
+	public function set($key, $value, $override_ee = false)
305
+	{
306
+		// don't allow "ee" to be overwritten unless explicitly instructed to do so
307
+		if (
308
+			$key !== 'ee'
309
+			|| ($key === 'ee' && empty($this->_params['ee']))
310
+			|| ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
311
+		) {
312
+			$this->_params[$key] = $value;
313
+		}
314
+	}
315
+
316
+
317
+
318
+	/**
319
+	 * @param      $key
320
+	 * @param null $default
321
+	 * @return    mixed
322
+	 */
323
+	public function get($key, $default = null)
324
+	{
325
+		return isset($this->_params[$key])
326
+			? $this->_params[$key]
327
+			: $default;
328
+	}
329
+
330
+
331
+
332
+	/**
333
+	 * check if param exists
334
+	 *
335
+	 * @param $key
336
+	 * @return    boolean
337
+	 */
338
+	public function is_set($key)
339
+	{
340
+		return isset($this->_params[$key])
341
+			? true
342
+			: false;
343
+	}
344
+
345
+
346
+
347
+	/**
348
+	 * remove param
349
+	 *
350
+	 * @param $key
351
+	 * @return    void
352
+	 */
353
+	public function un_set($key)
354
+	{
355
+		unset($this->_params[$key]);
356
+	}
357
+
358
+
359
+
360
+	/**
361
+	 * @param $key
362
+	 * @param $value
363
+	 * @return    void
364
+	 */
365
+	public function set_notice($key, $value)
366
+	{
367
+		$this->_notice[$key] = $value;
368
+	}
369
+
370
+
371 371
 
372
-    /**
373
-     * @param $key
374
-     * @return    mixed
375
-     */
376
-    public function get_notice($key)
377
-    {
378
-        return isset($this->_notice[$key])
379
-            ? $this->_notice[$key]
380
-            : null;
381
-    }
372
+	/**
373
+	 * @param $key
374
+	 * @return    mixed
375
+	 */
376
+	public function get_notice($key)
377
+	{
378
+		return isset($this->_notice[$key])
379
+			? $this->_notice[$key]
380
+			: null;
381
+	}
382 382
 
383 383
 
384 384
 
385
-    /**
386
-     * @param $string
387
-     * @return void
388
-     */
389
-    public function add_output($string)
390
-    {
391
-        $this->_output .= $string;
392
-    }
385
+	/**
386
+	 * @param $string
387
+	 * @return void
388
+	 */
389
+	public function add_output($string)
390
+	{
391
+		$this->_output .= $string;
392
+	}
393 393
 
394 394
 
395 395
 
396
-    /**
397
-     * @return string
398
-     */
399
-    public function get_output()
400
-    {
401
-        return $this->_output;
402
-    }
403
-
404
-
396
+	/**
397
+	 * @return string
398
+	 */
399
+	public function get_output()
400
+	{
401
+		return $this->_output;
402
+	}
403
+
404
+
405 405
 
406
-    /**
407
-     * @param $item
408
-     * @param $key
409
-     */
410
-    public function sanitize_text_field_for_array_walk(&$item, &$key)
411
-    {
412
-        $item = strpos($item, 'email') !== false
413
-            ? sanitize_email($item)
414
-            : sanitize_text_field($item);
415
-    }
406
+	/**
407
+	 * @param $item
408
+	 * @param $key
409
+	 */
410
+	public function sanitize_text_field_for_array_walk(&$item, &$key)
411
+	{
412
+		$item = strpos($item, 'email') !== false
413
+			? sanitize_email($item)
414
+			: sanitize_text_field($item);
415
+	}
416 416
 
417 417
 
418 418
 
419
-    /**
420
-     * @param $a
421
-     * @param $b
422
-     * @return bool
423
-     */
424
-    public function __set($a, $b)
425
-    {
426
-        return false;
427
-    }
419
+	/**
420
+	 * @param $a
421
+	 * @param $b
422
+	 * @return bool
423
+	 */
424
+	public function __set($a, $b)
425
+	{
426
+		return false;
427
+	}
428 428
 
429 429
 
430 430
 
431
-    /**
432
-     * @param $a
433
-     * @return bool
434
-     */
435
-    public function __get($a)
436
-    {
437
-        return false;
438
-    }
431
+	/**
432
+	 * @param $a
433
+	 * @return bool
434
+	 */
435
+	public function __get($a)
436
+	{
437
+		return false;
438
+	}
439 439
 
440 440
 
441 441
 
442
-    /**
443
-     * @param $a
444
-     * @return bool
445
-     */
446
-    public function __isset($a)
447
-    {
448
-        return false;
449
-    }
442
+	/**
443
+	 * @param $a
444
+	 * @return bool
445
+	 */
446
+	public function __isset($a)
447
+	{
448
+		return false;
449
+	}
450 450
 
451 451
 
452 452
 
453
-    /**
454
-     * @param $a
455
-     * @return bool
456
-     */
457
-    public function __unset($a)
458
-    {
459
-        return false;
460
-    }
453
+	/**
454
+	 * @param $a
455
+	 * @return bool
456
+	 */
457
+	public function __unset($a)
458
+	{
459
+		return false;
460
+	}
461 461
 
462 462
 
463 463
 
464
-    /**
465
-     * @return void
466
-     */
467
-    public function __clone()
468
-    {
469
-    }
464
+	/**
465
+	 * @return void
466
+	 */
467
+	public function __clone()
468
+	{
469
+	}
470 470
 
471 471
 
472 472
 
473
-    /**
474
-     * @return void
475
-     */
476
-    public function __wakeup()
477
-    {
478
-    }
473
+	/**
474
+	 * @return void
475
+	 */
476
+	public function __wakeup()
477
+	{
478
+	}
479 479
 
480 480
 
481 481
 
482
-    /**
483
-     *
484
-     */
485
-    public function __destruct()
486
-    {
487
-    }
482
+	/**
483
+	 *
484
+	 */
485
+	public function __destruct()
486
+	{
487
+	}
488 488
 
489 489
 
490 490
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
     public function parse_request($wp = null)
73 73
     {
74 74
         //if somebody forgot to provide us with WP, that's ok because its global
75
-        if (! $wp instanceof WP) {
75
+        if ( ! $wp instanceof WP) {
76 76
             global $wp;
77 77
         }
78 78
         $this->set_request_vars($wp);
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
      */
89 89
     public function set_request_vars($wp = null)
90 90
     {
91
-        if (! is_admin()) {
91
+        if ( ! is_admin()) {
92 92
             // set request post_id
93 93
             $this->set('post_id', $this->get_post_id_from_request($wp));
94 94
             // set request post name
@@ -108,17 +108,17 @@  discard block
 block discarded – undo
108 108
      */
109 109
     public function get_post_id_from_request($wp = null)
110 110
     {
111
-        if (! $wp instanceof WP) {
111
+        if ( ! $wp instanceof WP) {
112 112
             global $wp;
113 113
         }
114 114
         $post_id = null;
115 115
         if (isset($wp->query_vars['p'])) {
116 116
             $post_id = $wp->query_vars['p'];
117 117
         }
118
-        if (! $post_id && isset($wp->query_vars['page_id'])) {
118
+        if ( ! $post_id && isset($wp->query_vars['page_id'])) {
119 119
             $post_id = $wp->query_vars['page_id'];
120 120
         }
121
-        if (! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
121
+        if ( ! $post_id && $wp->request !== null && is_numeric(basename($wp->request))) {
122 122
             $post_id = basename($wp->request);
123 123
         }
124 124
         return $post_id;
@@ -132,19 +132,19 @@  discard block
 block discarded – undo
132 132
      */
133 133
     public function get_post_name_from_request($wp = null)
134 134
     {
135
-        if (! $wp instanceof WP) {
135
+        if ( ! $wp instanceof WP) {
136 136
             global $wp;
137 137
         }
138 138
         $post_name = null;
139 139
         if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
140 140
             $post_name = $wp->query_vars['name'];
141 141
         }
142
-        if (! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
142
+        if ( ! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
143 143
             $post_name = $wp->query_vars['pagename'];
144 144
         }
145
-        if (! $post_name && $wp->request !== null && ! empty($wp->request)) {
145
+        if ( ! $post_name && $wp->request !== null && ! empty($wp->request)) {
146 146
             $possible_post_name = basename($wp->request);
147
-            if (! is_numeric($possible_post_name)) {
147
+            if ( ! is_numeric($possible_post_name)) {
148 148
                 /** @type WPDB $wpdb */
149 149
                 global $wpdb;
150 150
                 $SQL =
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
                 }
156 156
             }
157 157
         }
158
-        if (! $post_name && $this->get('post_id')) {
158
+        if ( ! $post_name && $this->get('post_id')) {
159 159
             /** @type WPDB $wpdb */
160 160
             global $wpdb;
161 161
             $SQL =
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
      */
177 177
     public function get_post_type_from_request($wp = null)
178 178
     {
179
-        if (! $wp instanceof WP) {
179
+        if ( ! $wp instanceof WP) {
180 180
             global $wp;
181 181
         }
182 182
         return isset($wp->query_vars['post_type'])
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
         if ($post_id) {
199 199
             $current_page_permalink = get_permalink($post_id);
200 200
         } else {
201
-            if (! $wp instanceof WP) {
201
+            if ( ! $wp instanceof WP) {
202 202
                 global $wp;
203 203
             }
204 204
             if ($wp->request) {
@@ -233,12 +233,12 @@  discard block
 block discarded – undo
233 233
         // load espresso CPT endpoints
234 234
         $espresso_CPT_endpoints = $EE_CPT_Strategy->get_CPT_endpoints();
235 235
         $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
236
-        $post_types = (array)$this->get('post_type');
236
+        $post_types = (array) $this->get('post_type');
237 237
         foreach ($post_types as $post_type) {
238 238
             // was a post name passed ?
239 239
             if (isset($post_type_CPT_endpoints[$post_type])) {
240 240
                 // kk we know this is an espresso page, but is it a specific post ?
241
-                if (! $this->get('post_name')) {
241
+                if ( ! $this->get('post_name')) {
242 242
                     // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
243 243
                     $post_name = isset($post_type_CPT_endpoints[$this->get('post_type')])
244 244
                         ? $post_type_CPT_endpoints[$this->get('post_type')]
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,243 +40,243 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.025');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.025');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.
admin_pages/messages/Messages_Admin_Page.core.php 1 patch
Indentation   +3632 added lines, -3632 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('NO direct script access allowed');
2
+	exit('NO direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -17,2222 +17,2222 @@  discard block
 block discarded – undo
17 17
 class Messages_Admin_Page extends EE_Admin_Page
18 18
 {
19 19
     
20
-    /**
21
-     * @type EE_Message_Resource_Manager $_message_resource_manager
22
-     */
23
-    protected $_message_resource_manager;
24
-    
25
-    /**
26
-     * @type string $_active_message_type_name
27
-     */
28
-    protected $_active_message_type_name = '';
29
-    
30
-    /**
31
-     * @type EE_messenger $_active_messenger
32
-     */
33
-    protected $_active_messenger;
34
-    protected $_activate_state;
35
-    protected $_activate_meta_box_type;
36
-    protected $_current_message_meta_box;
37
-    protected $_current_message_meta_box_object;
38
-    protected $_context_switcher;
39
-    protected $_shortcodes = array();
40
-    protected $_active_messengers = array();
41
-    protected $_active_message_types = array();
42
-    
43
-    /**
44
-     * @var EE_Message_Template_Group $_message_template_group
45
-     */
46
-    protected $_message_template_group;
47
-    protected $_m_mt_settings = array();
48
-    
49
-    
50
-    /**
51
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
52
-     * IF there is no group then it gets automatically set to the Default template pack.
53
-     *
54
-     * @since 4.5.0
55
-     *
56
-     * @var EE_Messages_Template_Pack
57
-     */
58
-    protected $_template_pack;
59
-    
60
-    
61
-    /**
62
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
63
-     * group is.  If there is no group then it automatically gets set to default.
64
-     *
65
-     * @since 4.5.0
66
-     *
67
-     * @var string
68
-     */
69
-    protected $_variation;
70
-    
71
-    
72
-    /**
73
-     * @param bool $routing
74
-     */
75
-    public function __construct($routing = true)
76
-    {
77
-        //make sure messages autoloader is running
78
-        EED_Messages::set_autoloaders();
79
-        parent::__construct($routing);
80
-    }
81
-    
82
-    
83
-    protected function _init_page_props()
84
-    {
85
-        $this->page_slug        = EE_MSG_PG_SLUG;
86
-        $this->page_label       = __('Messages Settings', 'event_espresso');
87
-        $this->_admin_base_url  = EE_MSG_ADMIN_URL;
88
-        $this->_admin_base_path = EE_MSG_ADMIN;
89
-        
90
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
91
-        
92
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93
-        $this->_load_message_resource_manager();
94
-    }
95
-    
96
-    
97
-    /**
98
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
99
-     *
100
-     *
101
-     * @throws EE_Error
102
-     */
103
-    protected function _load_message_resource_manager()
104
-    {
105
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
106
-    }
107
-    
108
-    
109
-    /**
110
-     * @deprecated 4.9.9.rc.014
111
-     * @return array
112
-     */
113
-    public function get_messengers_for_list_table()
114
-    {
115
-        EE_Error::doing_it_wrong(
116
-            __METHOD__,
117
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
20
+	/**
21
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
22
+	 */
23
+	protected $_message_resource_manager;
24
+    
25
+	/**
26
+	 * @type string $_active_message_type_name
27
+	 */
28
+	protected $_active_message_type_name = '';
29
+    
30
+	/**
31
+	 * @type EE_messenger $_active_messenger
32
+	 */
33
+	protected $_active_messenger;
34
+	protected $_activate_state;
35
+	protected $_activate_meta_box_type;
36
+	protected $_current_message_meta_box;
37
+	protected $_current_message_meta_box_object;
38
+	protected $_context_switcher;
39
+	protected $_shortcodes = array();
40
+	protected $_active_messengers = array();
41
+	protected $_active_message_types = array();
42
+    
43
+	/**
44
+	 * @var EE_Message_Template_Group $_message_template_group
45
+	 */
46
+	protected $_message_template_group;
47
+	protected $_m_mt_settings = array();
48
+    
49
+    
50
+	/**
51
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
52
+	 * IF there is no group then it gets automatically set to the Default template pack.
53
+	 *
54
+	 * @since 4.5.0
55
+	 *
56
+	 * @var EE_Messages_Template_Pack
57
+	 */
58
+	protected $_template_pack;
59
+    
60
+    
61
+	/**
62
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
63
+	 * group is.  If there is no group then it automatically gets set to default.
64
+	 *
65
+	 * @since 4.5.0
66
+	 *
67
+	 * @var string
68
+	 */
69
+	protected $_variation;
70
+    
71
+    
72
+	/**
73
+	 * @param bool $routing
74
+	 */
75
+	public function __construct($routing = true)
76
+	{
77
+		//make sure messages autoloader is running
78
+		EED_Messages::set_autoloaders();
79
+		parent::__construct($routing);
80
+	}
81
+    
82
+    
83
+	protected function _init_page_props()
84
+	{
85
+		$this->page_slug        = EE_MSG_PG_SLUG;
86
+		$this->page_label       = __('Messages Settings', 'event_espresso');
87
+		$this->_admin_base_url  = EE_MSG_ADMIN_URL;
88
+		$this->_admin_base_path = EE_MSG_ADMIN;
89
+        
90
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
91
+        
92
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93
+		$this->_load_message_resource_manager();
94
+	}
95
+    
96
+    
97
+	/**
98
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
99
+	 *
100
+	 *
101
+	 * @throws EE_Error
102
+	 */
103
+	protected function _load_message_resource_manager()
104
+	{
105
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
106
+	}
107
+    
108
+    
109
+	/**
110
+	 * @deprecated 4.9.9.rc.014
111
+	 * @return array
112
+	 */
113
+	public function get_messengers_for_list_table()
114
+	{
115
+		EE_Error::doing_it_wrong(
116
+			__METHOD__,
117
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
118 118
 			values for use in creating a messenger filter dropdown which is now generated differently via
119 119
 			 Messages_Admin_Page::get_messengers_select_input', 'event_espresso'),
120
-            '4.9.9.rc.014'
121
-        );
122
-        
123
-        $m_values          = array();
124
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
125
-        //setup messengers for selects
126
-        $i = 1;
127
-        foreach ($active_messengers as $active_messenger) {
128
-            if ($active_messenger instanceof EE_Message) {
129
-                $m_values[$i]['id']   = $active_messenger->messenger();
130
-                $m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
131
-                $i++;
132
-            }
133
-        }
134
-        
135
-        return $m_values;
136
-    }
137
-    
138
-    
139
-    /**
140
-     * @deprecated 4.9.9.rc.014
141
-     * @return array
142
-     */
143
-    public function get_message_types_for_list_table()
144
-    {
145
-        EE_Error::doing_it_wrong(
146
-            __METHOD__,
147
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
120
+			'4.9.9.rc.014'
121
+		);
122
+        
123
+		$m_values          = array();
124
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
125
+		//setup messengers for selects
126
+		$i = 1;
127
+		foreach ($active_messengers as $active_messenger) {
128
+			if ($active_messenger instanceof EE_Message) {
129
+				$m_values[$i]['id']   = $active_messenger->messenger();
130
+				$m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
131
+				$i++;
132
+			}
133
+		}
134
+        
135
+		return $m_values;
136
+	}
137
+    
138
+    
139
+	/**
140
+	 * @deprecated 4.9.9.rc.014
141
+	 * @return array
142
+	 */
143
+	public function get_message_types_for_list_table()
144
+	{
145
+		EE_Error::doing_it_wrong(
146
+			__METHOD__,
147
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
148 148
 			values for use in creating a message type filter dropdown which is now generated differently via
149 149
 			 Messages_Admin_Page::get_message_types_select_input', 'event_espresso'),
150
-            '4.9.9.rc.014'
151
-        );
152
-        
153
-        $mt_values       = array();
154
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
155
-        $i               = 1;
156
-        foreach ($active_messages as $active_message) {
157
-            if ($active_message instanceof EE_Message) {
158
-                $mt_values[$i]['id']   = $active_message->message_type();
159
-                $mt_values[$i]['text'] = ucwords($active_message->message_type_label());
160
-                $i++;
161
-            }
162
-        }
163
-        
164
-        return $mt_values;
165
-    }
166
-    
167
-    
168
-    /**
169
-     * @deprecated 4.9.9.rc.014
170
-     * @return array
171
-     */
172
-    public function get_contexts_for_message_types_for_list_table()
173
-    {
174
-        EE_Error::doing_it_wrong(
175
-            __METHOD__,
176
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
150
+			'4.9.9.rc.014'
151
+		);
152
+        
153
+		$mt_values       = array();
154
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
155
+		$i               = 1;
156
+		foreach ($active_messages as $active_message) {
157
+			if ($active_message instanceof EE_Message) {
158
+				$mt_values[$i]['id']   = $active_message->message_type();
159
+				$mt_values[$i]['text'] = ucwords($active_message->message_type_label());
160
+				$i++;
161
+			}
162
+		}
163
+        
164
+		return $mt_values;
165
+	}
166
+    
167
+    
168
+	/**
169
+	 * @deprecated 4.9.9.rc.014
170
+	 * @return array
171
+	 */
172
+	public function get_contexts_for_message_types_for_list_table()
173
+	{
174
+		EE_Error::doing_it_wrong(
175
+			__METHOD__,
176
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
177 177
 			values for use in creating a message type context filter dropdown which is now generated differently via
178 178
 			 Messages_Admin_Page::get_contexts_for_message_types_select_input', 'event_espresso'),
179
-            '4.9.9.rc.014'
180
-        );
181
-        
182
-        $contexts                = array();
183
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
184
-        foreach ($active_message_contexts as $active_message) {
185
-            if ($active_message instanceof EE_Message) {
186
-                $message_type = $active_message->message_type_object();
187
-                if ($message_type instanceof EE_message_type) {
188
-                    $message_type_contexts = $message_type->get_contexts();
189
-                    foreach ($message_type_contexts as $context => $context_details) {
190
-                        $contexts[$context] = $context_details['label'];
191
-                    }
192
-                }
193
-            }
194
-        }
195
-        
196
-        return $contexts;
197
-    }
198
-    
199
-    
200
-    /**
201
-     * Generate select input with provided messenger options array.
202
-     *
203
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
204
-     *                                 labels.
205
-     *
206
-     * @return string
207
-     */
208
-    public function get_messengers_select_input($messenger_options)
209
-    {
210
-        //if empty or just one value then just return an empty string
211
-        if (empty($messenger_options)
212
-            || ! is_array($messenger_options)
213
-            || count($messenger_options) === 1
214
-        ) {
215
-            return '';
216
-        }
217
-        //merge in default
218
-        $messenger_options = array_merge(
219
-            array('none_selected' => __('Show All Messengers', 'event_espresso')),
220
-            $messenger_options
221
-        );
222
-        $input             = new EE_Select_Input(
223
-            $messenger_options,
224
-            array(
225
-                'html_name'  => 'ee_messenger_filter_by',
226
-                'html_id'    => 'ee_messenger_filter_by',
227
-                'html_class' => 'wide',
228
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
229
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
230
-                    : 'none_selected'
231
-            )
232
-        );
233
-        
234
-        return $input->get_html_for_input();
235
-    }
236
-    
237
-    
238
-    /**
239
-     * Generate select input with provided message type options array.
240
-     *
241
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
242
-     *                                    message type labels
243
-     *
244
-     * @return string
245
-     */
246
-    public function get_message_types_select_input($message_type_options)
247
-    {
248
-        //if empty or count of options is 1 then just return an empty string
249
-        if (empty($message_type_options)
250
-            || ! is_array($message_type_options)
251
-            || count($message_type_options) === 1
252
-        ) {
253
-            return '';
254
-        }
255
-        //merge in default
256
-        $message_type_options = array_merge(
257
-            array('none_selected' => __('Show All Message Types', 'event_espresso')),
258
-            $message_type_options
259
-        );
260
-        $input                = new EE_Select_Input(
261
-            $message_type_options,
262
-            array(
263
-                'html_name'  => 'ee_message_type_filter_by',
264
-                'html_id'    => 'ee_message_type_filter_by',
265
-                'html_class' => 'wide',
266
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
267
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
268
-                    : 'none_selected',
269
-            )
270
-        );
271
-        
272
-        return $input->get_html_for_input();
273
-    }
274
-    
275
-    
276
-    /**
277
-     * Generate select input with provide message type contexts array.
278
-     *
279
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
280
-     *                               context label.
281
-     *
282
-     * @return string
283
-     */
284
-    public function get_contexts_for_message_types_select_input($context_options)
285
-    {
286
-        //if empty or count of options is one then just return empty string
287
-        if (empty($context_options)
288
-            || ! is_array($context_options)
289
-            || count($context_options) === 1
290
-        ) {
291
-            return '';
292
-        }
293
-        //merge in default
294
-        $context_options = array_merge(
295
-            array('none_selected' => __('Show all Contexts', 'event_espresso')),
296
-            $context_options
297
-        );
298
-        $input           = new EE_Select_Input(
299
-            $context_options,
300
-            array(
301
-                'html_name'  => 'ee_context_filter_by',
302
-                'html_id'    => 'ee_context_filter_by',
303
-                'html_class' => 'wide',
304
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
305
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
306
-                    : 'none_selected',
307
-            )
308
-        );
309
-        
310
-        return $input->get_html_for_input();
311
-    }
312
-    
313
-    
314
-    protected function _ajax_hooks()
315
-    {
316
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
317
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
318
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
319
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
320
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
321
-    }
322
-    
323
-    
324
-    protected function _define_page_props()
325
-    {
326
-        $this->_admin_page_title = $this->page_label;
327
-        $this->_labels           = array(
328
-            'buttons'    => array(
329
-                'add'    => __('Add New Message Template', 'event_espresso'),
330
-                'edit'   => __('Edit Message Template', 'event_espresso'),
331
-                'delete' => __('Delete Message Template', 'event_espresso')
332
-            ),
333
-            'publishbox' => __('Update Actions', 'event_espresso')
334
-        );
335
-    }
336
-    
337
-    
338
-    /**
339
-     *        an array for storing key => value pairs of request actions and their corresponding methods
340
-     * @access protected
341
-     * @return void
342
-     */
343
-    protected function _set_page_routes()
344
-    {
345
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
346
-            ? $this->_req_data['GRP_ID']
347
-            : 0;
348
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
349
-            ? $this->_req_data['id']
350
-            : $grp_id;
351
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
352
-            ? $this->_req_data['MSG_ID']
353
-            : 0;
354
-        
355
-        $this->_page_routes = array(
356
-            'default'                          => array(
357
-                'func'       => '_message_queue_list_table',
358
-                'capability' => 'ee_read_global_messages'
359
-            ),
360
-            'global_mtps'                      => array(
361
-                'func'       => '_ee_default_messages_overview_list_table',
362
-                'capability' => 'ee_read_global_messages'
363
-            ),
364
-            'custom_mtps'                      => array(
365
-                'func'       => '_custom_mtps_preview',
366
-                'capability' => 'ee_read_messages'
367
-            ),
368
-            'add_new_message_template'         => array(
369
-                'func'       => '_add_message_template',
370
-                'capability' => 'ee_edit_messages',
371
-                'noheader'   => true
372
-            ),
373
-            'edit_message_template'            => array(
374
-                'func'       => '_edit_message_template',
375
-                'capability' => 'ee_edit_message',
376
-                'obj_id'     => $grp_id
377
-            ),
378
-            'preview_message'                  => array(
379
-                'func'               => '_preview_message',
380
-                'capability'         => 'ee_read_message',
381
-                'obj_id'             => $grp_id,
382
-                'noheader'           => true,
383
-                'headers_sent_route' => 'display_preview_message'
384
-            ),
385
-            'display_preview_message'          => array(
386
-                'func'       => '_display_preview_message',
387
-                'capability' => 'ee_read_message',
388
-                'obj_id'     => $grp_id
389
-            ),
390
-            'insert_message_template'          => array(
391
-                'func'       => '_insert_or_update_message_template',
392
-                'capability' => 'ee_edit_messages',
393
-                'args'       => array('new_template' => true),
394
-                'noheader'   => true
395
-            ),
396
-            'update_message_template'          => array(
397
-                'func'       => '_insert_or_update_message_template',
398
-                'capability' => 'ee_edit_message',
399
-                'obj_id'     => $grp_id,
400
-                'args'       => array('new_template' => false),
401
-                'noheader'   => true
402
-            ),
403
-            'trash_message_template'           => array(
404
-                'func'       => '_trash_or_restore_message_template',
405
-                'capability' => 'ee_delete_message',
406
-                'obj_id'     => $grp_id,
407
-                'args'       => array('trash' => true, 'all' => true),
408
-                'noheader'   => true
409
-            ),
410
-            'trash_message_template_context'   => array(
411
-                'func'       => '_trash_or_restore_message_template',
412
-                'capability' => 'ee_delete_message',
413
-                'obj_id'     => $grp_id,
414
-                'args'       => array('trash' => true),
415
-                'noheader'   => true
416
-            ),
417
-            'restore_message_template'         => array(
418
-                'func'       => '_trash_or_restore_message_template',
419
-                'capability' => 'ee_delete_message',
420
-                'obj_id'     => $grp_id,
421
-                'args'       => array('trash' => false, 'all' => true),
422
-                'noheader'   => true
423
-            ),
424
-            'restore_message_template_context' => array(
425
-                'func'       => '_trash_or_restore_message_template',
426
-                'capability' => 'ee_delete_message',
427
-                'obj_id'     => $grp_id,
428
-                'args'       => array('trash' => false),
429
-                'noheader'   => true
430
-            ),
431
-            'delete_message_template'          => array(
432
-                'func'       => '_delete_message_template',
433
-                'capability' => 'ee_delete_message',
434
-                'obj_id'     => $grp_id,
435
-                'noheader'   => true
436
-            ),
437
-            'reset_to_default'                 => array(
438
-                'func'       => '_reset_to_default_template',
439
-                'capability' => 'ee_edit_message',
440
-                'obj_id'     => $grp_id,
441
-                'noheader'   => true
442
-            ),
443
-            'settings'                         => array(
444
-                'func'       => '_settings',
445
-                'capability' => 'manage_options'
446
-            ),
447
-            'update_global_settings'           => array(
448
-                'func'       => '_update_global_settings',
449
-                'capability' => 'manage_options',
450
-                'noheader'   => true
451
-            ),
452
-            'generate_now'                     => array(
453
-                'func'       => '_generate_now',
454
-                'capability' => 'ee_send_message',
455
-                'noheader'   => true
456
-            ),
457
-            'generate_and_send_now'            => array(
458
-                'func'       => '_generate_and_send_now',
459
-                'capability' => 'ee_send_message',
460
-                'noheader'   => true
461
-            ),
462
-            'queue_for_resending'              => array(
463
-                'func'       => '_queue_for_resending',
464
-                'capability' => 'ee_send_message',
465
-                'noheader'   => true
466
-            ),
467
-            'send_now'                         => array(
468
-                'func'       => '_send_now',
469
-                'capability' => 'ee_send_message',
470
-                'noheader'   => true
471
-            ),
472
-            'delete_ee_message'                => array(
473
-                'func'       => '_delete_ee_messages',
474
-                'capability' => 'ee_delete_messages',
475
-                'noheader'   => true
476
-            ),
477
-            'delete_ee_messages'               => array(
478
-                'func'       => '_delete_ee_messages',
479
-                'capability' => 'ee_delete_messages',
480
-                'noheader'   => true,
481
-                'obj_id'     => $msg_id
482
-            )
483
-        );
484
-    }
485
-    
486
-    
487
-    protected function _set_page_config()
488
-    {
489
-        $this->_page_config = array(
490
-            'default'                  => array(
491
-                'nav'           => array(
492
-                    'label' => __('Message Activity', 'event_espresso'),
493
-                    'order' => 10
494
-                ),
495
-                'list_table'    => 'EE_Message_List_Table',
496
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
497
-                'require_nonce' => false
498
-            ),
499
-            'global_mtps'              => array(
500
-                'nav'           => array(
501
-                    'label' => __('Default Message Templates', 'event_espresso'),
502
-                    'order' => 20
503
-                ),
504
-                'list_table'    => 'Messages_Template_List_Table',
505
-                'help_tabs'     => array(
506
-                    'messages_overview_help_tab'                                => array(
507
-                        'title'    => __('Messages Overview', 'event_espresso'),
508
-                        'filename' => 'messages_overview'
509
-                    ),
510
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
511
-                        'title'    => __('Messages Table Column Headings', 'event_espresso'),
512
-                        'filename' => 'messages_overview_table_column_headings'
513
-                    ),
514
-                    'messages_overview_messages_filters_help_tab'               => array(
515
-                        'title'    => __('Message Filters', 'event_espresso'),
516
-                        'filename' => 'messages_overview_filters'
517
-                    ),
518
-                    'messages_overview_messages_views_help_tab'                 => array(
519
-                        'title'    => __('Message Views', 'event_espresso'),
520
-                        'filename' => 'messages_overview_views'
521
-                    ),
522
-                    'message_overview_message_types_help_tab'                   => array(
523
-                        'title'    => __('Message Types', 'event_espresso'),
524
-                        'filename' => 'messages_overview_types'
525
-                    ),
526
-                    'messages_overview_messengers_help_tab'                     => array(
527
-                        'title'    => __('Messengers', 'event_espresso'),
528
-                        'filename' => 'messages_overview_messengers',
529
-                    ),
530
-                ),
531
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
532
-                'require_nonce' => false
533
-            ),
534
-            'custom_mtps'              => array(
535
-                'nav'           => array(
536
-                    'label' => __('Custom Message Templates', 'event_espresso'),
537
-                    'order' => 30
538
-                ),
539
-                'help_tabs'     => array(),
540
-                'help_tour'     => array(),
541
-                'require_nonce' => false
542
-            ),
543
-            'add_new_message_template' => array(
544
-                'nav'           => array(
545
-                    'label'      => __('Add New Message Templates', 'event_espresso'),
546
-                    'order'      => 5,
547
-                    'persistent' => false
548
-                ),
549
-                'require_nonce' => false
550
-            ),
551
-            'edit_message_template'    => array(
552
-                'labels'        => array(
553
-                    'buttons'    => array(
554
-                        'reset' => __('Reset Templates'),
555
-                    ),
556
-                    'publishbox' => __('Update Actions', 'event_espresso')
557
-                ),
558
-                'nav'           => array(
559
-                    'label'      => __('Edit Message Templates', 'event_espresso'),
560
-                    'order'      => 5,
561
-                    'persistent' => false,
562
-                    'url'        => ''
563
-                ),
564
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
565
-                'has_metaboxes' => true,
566
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
567
-                'help_tabs'     => array(
568
-                    'edit_message_template'       => array(
569
-                        'title'    => __('Message Template Editor', 'event_espresso'),
570
-                        'callback' => 'edit_message_template_help_tab'
571
-                    ),
572
-                    'message_templates_help_tab'  => array(
573
-                        'title'    => __('Message Templates', 'event_espresso'),
574
-                        'filename' => 'messages_templates'
575
-                    ),
576
-                    'message_template_shortcodes' => array(
577
-                        'title'    => __('Message Shortcodes', 'event_espresso'),
578
-                        'callback' => 'message_template_shortcodes_help_tab'
579
-                    ),
580
-                    'message_preview_help_tab'    => array(
581
-                        'title'    => __('Message Preview', 'event_espresso'),
582
-                        'filename' => 'messages_preview'
583
-                    ),
584
-                    'messages_overview_other_help_tab'                          => array(
585
-                        'title'    => __('Messages Other', 'event_espresso'),
586
-                        'filename' => 'messages_overview_other',
587
-                    ),
588
-                ),
589
-                'require_nonce' => false
590
-            ),
591
-            'display_preview_message'  => array(
592
-                'nav'           => array(
593
-                    'label'      => __('Message Preview', 'event_espresso'),
594
-                    'order'      => 5,
595
-                    'url'        => '',
596
-                    'persistent' => false
597
-                ),
598
-                'help_tabs'     => array(
599
-                    'preview_message' => array(
600
-                        'title'    => __('About Previews', 'event_espresso'),
601
-                        'callback' => 'preview_message_help_tab'
602
-                    )
603
-                ),
604
-                'require_nonce' => false
605
-            ),
606
-            'settings'                 => array(
607
-                'nav'           => array(
608
-                    'label' => __('Settings', 'event_espresso'),
609
-                    'order' => 40
610
-                ),
611
-                'metaboxes'     => array('_messages_settings_metaboxes'),
612
-                'help_tabs'     => array(
613
-                    'messages_settings_help_tab'               => array(
614
-                        'title'    => __('Messages Settings', 'event_espresso'),
615
-                        'filename' => 'messages_settings'
616
-                    ),
617
-                    'messages_settings_message_types_help_tab' => array(
618
-                        'title'    => __('Activating / Deactivating Message Types', 'event_espresso'),
619
-                        'filename' => 'messages_settings_message_types'
620
-                    ),
621
-                    'messages_settings_messengers_help_tab'    => array(
622
-                        'title'    => __('Activating / Deactivating Messengers', 'event_espresso'),
623
-                        'filename' => 'messages_settings_messengers'
624
-                    ),
625
-                ),
626
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
627
-                'require_nonce' => false
628
-            )
629
-        );
630
-    }
631
-    
632
-    
633
-    protected function _add_screen_options()
634
-    {
635
-        //todo
636
-    }
637
-    
638
-    
639
-    protected function _add_screen_options_global_mtps()
640
-    {
641
-        /**
642
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
643
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
644
-         */
645
-        $page_title              = $this->_admin_page_title;
646
-        $this->_admin_page_title = __('Global Message Templates', 'event_espresso');
647
-        $this->_per_page_screen_option();
648
-        $this->_admin_page_title = $page_title;
649
-    }
650
-    
651
-    
652
-    protected function _add_screen_options_default()
653
-    {
654
-        $this->_admin_page_title = __('Message Activity', 'event_espresso');
655
-        $this->_per_page_screen_option();
656
-    }
657
-    
658
-    
659
-    //none of the below group are currently used for Messages
660
-    protected function _add_feature_pointers()
661
-    {
662
-    }
663
-    
664
-    public function admin_init()
665
-    {
666
-    }
667
-    
668
-    public function admin_notices()
669
-    {
670
-    }
671
-    
672
-    public function admin_footer_scripts()
673
-    {
674
-    }
675
-    
676
-    
677
-    public function messages_help_tab()
678
-    {
679
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
680
-    }
681
-    
682
-    
683
-    public function messengers_help_tab()
684
-    {
685
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
686
-    }
687
-    
688
-    
689
-    public function message_types_help_tab()
690
-    {
691
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
692
-    }
693
-    
694
-    
695
-    public function messages_overview_help_tab()
696
-    {
697
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
698
-    }
699
-    
700
-    
701
-    public function message_templates_help_tab()
702
-    {
703
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
704
-    }
705
-    
706
-    
707
-    public function edit_message_template_help_tab()
708
-    {
709
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
-                'event_espresso') . '" />';
711
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
-                'event_espresso') . '" />';
713
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
-                'event_espresso') . '" />';
715
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
-                'event_espresso') . '" />';
717
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
-                'event_espresso') . '" />';
719
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
720
-            $args);
721
-    }
722
-    
723
-    
724
-    public function message_template_shortcodes_help_tab()
725
-    {
726
-        $this->_set_shortcodes();
727
-        $args['shortcodes'] = $this->_shortcodes;
728
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
729
-            $args);
730
-    }
179
+			'4.9.9.rc.014'
180
+		);
181
+        
182
+		$contexts                = array();
183
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
184
+		foreach ($active_message_contexts as $active_message) {
185
+			if ($active_message instanceof EE_Message) {
186
+				$message_type = $active_message->message_type_object();
187
+				if ($message_type instanceof EE_message_type) {
188
+					$message_type_contexts = $message_type->get_contexts();
189
+					foreach ($message_type_contexts as $context => $context_details) {
190
+						$contexts[$context] = $context_details['label'];
191
+					}
192
+				}
193
+			}
194
+		}
195
+        
196
+		return $contexts;
197
+	}
198
+    
199
+    
200
+	/**
201
+	 * Generate select input with provided messenger options array.
202
+	 *
203
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
204
+	 *                                 labels.
205
+	 *
206
+	 * @return string
207
+	 */
208
+	public function get_messengers_select_input($messenger_options)
209
+	{
210
+		//if empty or just one value then just return an empty string
211
+		if (empty($messenger_options)
212
+			|| ! is_array($messenger_options)
213
+			|| count($messenger_options) === 1
214
+		) {
215
+			return '';
216
+		}
217
+		//merge in default
218
+		$messenger_options = array_merge(
219
+			array('none_selected' => __('Show All Messengers', 'event_espresso')),
220
+			$messenger_options
221
+		);
222
+		$input             = new EE_Select_Input(
223
+			$messenger_options,
224
+			array(
225
+				'html_name'  => 'ee_messenger_filter_by',
226
+				'html_id'    => 'ee_messenger_filter_by',
227
+				'html_class' => 'wide',
228
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
229
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
230
+					: 'none_selected'
231
+			)
232
+		);
233
+        
234
+		return $input->get_html_for_input();
235
+	}
236
+    
237
+    
238
+	/**
239
+	 * Generate select input with provided message type options array.
240
+	 *
241
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
242
+	 *                                    message type labels
243
+	 *
244
+	 * @return string
245
+	 */
246
+	public function get_message_types_select_input($message_type_options)
247
+	{
248
+		//if empty or count of options is 1 then just return an empty string
249
+		if (empty($message_type_options)
250
+			|| ! is_array($message_type_options)
251
+			|| count($message_type_options) === 1
252
+		) {
253
+			return '';
254
+		}
255
+		//merge in default
256
+		$message_type_options = array_merge(
257
+			array('none_selected' => __('Show All Message Types', 'event_espresso')),
258
+			$message_type_options
259
+		);
260
+		$input                = new EE_Select_Input(
261
+			$message_type_options,
262
+			array(
263
+				'html_name'  => 'ee_message_type_filter_by',
264
+				'html_id'    => 'ee_message_type_filter_by',
265
+				'html_class' => 'wide',
266
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
267
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
268
+					: 'none_selected',
269
+			)
270
+		);
271
+        
272
+		return $input->get_html_for_input();
273
+	}
274
+    
275
+    
276
+	/**
277
+	 * Generate select input with provide message type contexts array.
278
+	 *
279
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
280
+	 *                               context label.
281
+	 *
282
+	 * @return string
283
+	 */
284
+	public function get_contexts_for_message_types_select_input($context_options)
285
+	{
286
+		//if empty or count of options is one then just return empty string
287
+		if (empty($context_options)
288
+			|| ! is_array($context_options)
289
+			|| count($context_options) === 1
290
+		) {
291
+			return '';
292
+		}
293
+		//merge in default
294
+		$context_options = array_merge(
295
+			array('none_selected' => __('Show all Contexts', 'event_espresso')),
296
+			$context_options
297
+		);
298
+		$input           = new EE_Select_Input(
299
+			$context_options,
300
+			array(
301
+				'html_name'  => 'ee_context_filter_by',
302
+				'html_id'    => 'ee_context_filter_by',
303
+				'html_class' => 'wide',
304
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
305
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
306
+					: 'none_selected',
307
+			)
308
+		);
309
+        
310
+		return $input->get_html_for_input();
311
+	}
312
+    
313
+    
314
+	protected function _ajax_hooks()
315
+	{
316
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
317
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
318
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
319
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
320
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
321
+	}
322
+    
323
+    
324
+	protected function _define_page_props()
325
+	{
326
+		$this->_admin_page_title = $this->page_label;
327
+		$this->_labels           = array(
328
+			'buttons'    => array(
329
+				'add'    => __('Add New Message Template', 'event_espresso'),
330
+				'edit'   => __('Edit Message Template', 'event_espresso'),
331
+				'delete' => __('Delete Message Template', 'event_espresso')
332
+			),
333
+			'publishbox' => __('Update Actions', 'event_espresso')
334
+		);
335
+	}
336
+    
337
+    
338
+	/**
339
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
340
+	 * @access protected
341
+	 * @return void
342
+	 */
343
+	protected function _set_page_routes()
344
+	{
345
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
346
+			? $this->_req_data['GRP_ID']
347
+			: 0;
348
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
349
+			? $this->_req_data['id']
350
+			: $grp_id;
351
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
352
+			? $this->_req_data['MSG_ID']
353
+			: 0;
354
+        
355
+		$this->_page_routes = array(
356
+			'default'                          => array(
357
+				'func'       => '_message_queue_list_table',
358
+				'capability' => 'ee_read_global_messages'
359
+			),
360
+			'global_mtps'                      => array(
361
+				'func'       => '_ee_default_messages_overview_list_table',
362
+				'capability' => 'ee_read_global_messages'
363
+			),
364
+			'custom_mtps'                      => array(
365
+				'func'       => '_custom_mtps_preview',
366
+				'capability' => 'ee_read_messages'
367
+			),
368
+			'add_new_message_template'         => array(
369
+				'func'       => '_add_message_template',
370
+				'capability' => 'ee_edit_messages',
371
+				'noheader'   => true
372
+			),
373
+			'edit_message_template'            => array(
374
+				'func'       => '_edit_message_template',
375
+				'capability' => 'ee_edit_message',
376
+				'obj_id'     => $grp_id
377
+			),
378
+			'preview_message'                  => array(
379
+				'func'               => '_preview_message',
380
+				'capability'         => 'ee_read_message',
381
+				'obj_id'             => $grp_id,
382
+				'noheader'           => true,
383
+				'headers_sent_route' => 'display_preview_message'
384
+			),
385
+			'display_preview_message'          => array(
386
+				'func'       => '_display_preview_message',
387
+				'capability' => 'ee_read_message',
388
+				'obj_id'     => $grp_id
389
+			),
390
+			'insert_message_template'          => array(
391
+				'func'       => '_insert_or_update_message_template',
392
+				'capability' => 'ee_edit_messages',
393
+				'args'       => array('new_template' => true),
394
+				'noheader'   => true
395
+			),
396
+			'update_message_template'          => array(
397
+				'func'       => '_insert_or_update_message_template',
398
+				'capability' => 'ee_edit_message',
399
+				'obj_id'     => $grp_id,
400
+				'args'       => array('new_template' => false),
401
+				'noheader'   => true
402
+			),
403
+			'trash_message_template'           => array(
404
+				'func'       => '_trash_or_restore_message_template',
405
+				'capability' => 'ee_delete_message',
406
+				'obj_id'     => $grp_id,
407
+				'args'       => array('trash' => true, 'all' => true),
408
+				'noheader'   => true
409
+			),
410
+			'trash_message_template_context'   => array(
411
+				'func'       => '_trash_or_restore_message_template',
412
+				'capability' => 'ee_delete_message',
413
+				'obj_id'     => $grp_id,
414
+				'args'       => array('trash' => true),
415
+				'noheader'   => true
416
+			),
417
+			'restore_message_template'         => array(
418
+				'func'       => '_trash_or_restore_message_template',
419
+				'capability' => 'ee_delete_message',
420
+				'obj_id'     => $grp_id,
421
+				'args'       => array('trash' => false, 'all' => true),
422
+				'noheader'   => true
423
+			),
424
+			'restore_message_template_context' => array(
425
+				'func'       => '_trash_or_restore_message_template',
426
+				'capability' => 'ee_delete_message',
427
+				'obj_id'     => $grp_id,
428
+				'args'       => array('trash' => false),
429
+				'noheader'   => true
430
+			),
431
+			'delete_message_template'          => array(
432
+				'func'       => '_delete_message_template',
433
+				'capability' => 'ee_delete_message',
434
+				'obj_id'     => $grp_id,
435
+				'noheader'   => true
436
+			),
437
+			'reset_to_default'                 => array(
438
+				'func'       => '_reset_to_default_template',
439
+				'capability' => 'ee_edit_message',
440
+				'obj_id'     => $grp_id,
441
+				'noheader'   => true
442
+			),
443
+			'settings'                         => array(
444
+				'func'       => '_settings',
445
+				'capability' => 'manage_options'
446
+			),
447
+			'update_global_settings'           => array(
448
+				'func'       => '_update_global_settings',
449
+				'capability' => 'manage_options',
450
+				'noheader'   => true
451
+			),
452
+			'generate_now'                     => array(
453
+				'func'       => '_generate_now',
454
+				'capability' => 'ee_send_message',
455
+				'noheader'   => true
456
+			),
457
+			'generate_and_send_now'            => array(
458
+				'func'       => '_generate_and_send_now',
459
+				'capability' => 'ee_send_message',
460
+				'noheader'   => true
461
+			),
462
+			'queue_for_resending'              => array(
463
+				'func'       => '_queue_for_resending',
464
+				'capability' => 'ee_send_message',
465
+				'noheader'   => true
466
+			),
467
+			'send_now'                         => array(
468
+				'func'       => '_send_now',
469
+				'capability' => 'ee_send_message',
470
+				'noheader'   => true
471
+			),
472
+			'delete_ee_message'                => array(
473
+				'func'       => '_delete_ee_messages',
474
+				'capability' => 'ee_delete_messages',
475
+				'noheader'   => true
476
+			),
477
+			'delete_ee_messages'               => array(
478
+				'func'       => '_delete_ee_messages',
479
+				'capability' => 'ee_delete_messages',
480
+				'noheader'   => true,
481
+				'obj_id'     => $msg_id
482
+			)
483
+		);
484
+	}
485
+    
486
+    
487
+	protected function _set_page_config()
488
+	{
489
+		$this->_page_config = array(
490
+			'default'                  => array(
491
+				'nav'           => array(
492
+					'label' => __('Message Activity', 'event_espresso'),
493
+					'order' => 10
494
+				),
495
+				'list_table'    => 'EE_Message_List_Table',
496
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
497
+				'require_nonce' => false
498
+			),
499
+			'global_mtps'              => array(
500
+				'nav'           => array(
501
+					'label' => __('Default Message Templates', 'event_espresso'),
502
+					'order' => 20
503
+				),
504
+				'list_table'    => 'Messages_Template_List_Table',
505
+				'help_tabs'     => array(
506
+					'messages_overview_help_tab'                                => array(
507
+						'title'    => __('Messages Overview', 'event_espresso'),
508
+						'filename' => 'messages_overview'
509
+					),
510
+					'messages_overview_messages_table_column_headings_help_tab' => array(
511
+						'title'    => __('Messages Table Column Headings', 'event_espresso'),
512
+						'filename' => 'messages_overview_table_column_headings'
513
+					),
514
+					'messages_overview_messages_filters_help_tab'               => array(
515
+						'title'    => __('Message Filters', 'event_espresso'),
516
+						'filename' => 'messages_overview_filters'
517
+					),
518
+					'messages_overview_messages_views_help_tab'                 => array(
519
+						'title'    => __('Message Views', 'event_espresso'),
520
+						'filename' => 'messages_overview_views'
521
+					),
522
+					'message_overview_message_types_help_tab'                   => array(
523
+						'title'    => __('Message Types', 'event_espresso'),
524
+						'filename' => 'messages_overview_types'
525
+					),
526
+					'messages_overview_messengers_help_tab'                     => array(
527
+						'title'    => __('Messengers', 'event_espresso'),
528
+						'filename' => 'messages_overview_messengers',
529
+					),
530
+				),
531
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
532
+				'require_nonce' => false
533
+			),
534
+			'custom_mtps'              => array(
535
+				'nav'           => array(
536
+					'label' => __('Custom Message Templates', 'event_espresso'),
537
+					'order' => 30
538
+				),
539
+				'help_tabs'     => array(),
540
+				'help_tour'     => array(),
541
+				'require_nonce' => false
542
+			),
543
+			'add_new_message_template' => array(
544
+				'nav'           => array(
545
+					'label'      => __('Add New Message Templates', 'event_espresso'),
546
+					'order'      => 5,
547
+					'persistent' => false
548
+				),
549
+				'require_nonce' => false
550
+			),
551
+			'edit_message_template'    => array(
552
+				'labels'        => array(
553
+					'buttons'    => array(
554
+						'reset' => __('Reset Templates'),
555
+					),
556
+					'publishbox' => __('Update Actions', 'event_espresso')
557
+				),
558
+				'nav'           => array(
559
+					'label'      => __('Edit Message Templates', 'event_espresso'),
560
+					'order'      => 5,
561
+					'persistent' => false,
562
+					'url'        => ''
563
+				),
564
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
565
+				'has_metaboxes' => true,
566
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
567
+				'help_tabs'     => array(
568
+					'edit_message_template'       => array(
569
+						'title'    => __('Message Template Editor', 'event_espresso'),
570
+						'callback' => 'edit_message_template_help_tab'
571
+					),
572
+					'message_templates_help_tab'  => array(
573
+						'title'    => __('Message Templates', 'event_espresso'),
574
+						'filename' => 'messages_templates'
575
+					),
576
+					'message_template_shortcodes' => array(
577
+						'title'    => __('Message Shortcodes', 'event_espresso'),
578
+						'callback' => 'message_template_shortcodes_help_tab'
579
+					),
580
+					'message_preview_help_tab'    => array(
581
+						'title'    => __('Message Preview', 'event_espresso'),
582
+						'filename' => 'messages_preview'
583
+					),
584
+					'messages_overview_other_help_tab'                          => array(
585
+						'title'    => __('Messages Other', 'event_espresso'),
586
+						'filename' => 'messages_overview_other',
587
+					),
588
+				),
589
+				'require_nonce' => false
590
+			),
591
+			'display_preview_message'  => array(
592
+				'nav'           => array(
593
+					'label'      => __('Message Preview', 'event_espresso'),
594
+					'order'      => 5,
595
+					'url'        => '',
596
+					'persistent' => false
597
+				),
598
+				'help_tabs'     => array(
599
+					'preview_message' => array(
600
+						'title'    => __('About Previews', 'event_espresso'),
601
+						'callback' => 'preview_message_help_tab'
602
+					)
603
+				),
604
+				'require_nonce' => false
605
+			),
606
+			'settings'                 => array(
607
+				'nav'           => array(
608
+					'label' => __('Settings', 'event_espresso'),
609
+					'order' => 40
610
+				),
611
+				'metaboxes'     => array('_messages_settings_metaboxes'),
612
+				'help_tabs'     => array(
613
+					'messages_settings_help_tab'               => array(
614
+						'title'    => __('Messages Settings', 'event_espresso'),
615
+						'filename' => 'messages_settings'
616
+					),
617
+					'messages_settings_message_types_help_tab' => array(
618
+						'title'    => __('Activating / Deactivating Message Types', 'event_espresso'),
619
+						'filename' => 'messages_settings_message_types'
620
+					),
621
+					'messages_settings_messengers_help_tab'    => array(
622
+						'title'    => __('Activating / Deactivating Messengers', 'event_espresso'),
623
+						'filename' => 'messages_settings_messengers'
624
+					),
625
+				),
626
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
627
+				'require_nonce' => false
628
+			)
629
+		);
630
+	}
631
+    
632
+    
633
+	protected function _add_screen_options()
634
+	{
635
+		//todo
636
+	}
637
+    
638
+    
639
+	protected function _add_screen_options_global_mtps()
640
+	{
641
+		/**
642
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
643
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
644
+		 */
645
+		$page_title              = $this->_admin_page_title;
646
+		$this->_admin_page_title = __('Global Message Templates', 'event_espresso');
647
+		$this->_per_page_screen_option();
648
+		$this->_admin_page_title = $page_title;
649
+	}
650
+    
651
+    
652
+	protected function _add_screen_options_default()
653
+	{
654
+		$this->_admin_page_title = __('Message Activity', 'event_espresso');
655
+		$this->_per_page_screen_option();
656
+	}
657
+    
658
+    
659
+	//none of the below group are currently used for Messages
660
+	protected function _add_feature_pointers()
661
+	{
662
+	}
663
+    
664
+	public function admin_init()
665
+	{
666
+	}
667
+    
668
+	public function admin_notices()
669
+	{
670
+	}
671
+    
672
+	public function admin_footer_scripts()
673
+	{
674
+	}
675
+    
676
+    
677
+	public function messages_help_tab()
678
+	{
679
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
680
+	}
681
+    
682
+    
683
+	public function messengers_help_tab()
684
+	{
685
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
686
+	}
687
+    
688
+    
689
+	public function message_types_help_tab()
690
+	{
691
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
692
+	}
693
+    
694
+    
695
+	public function messages_overview_help_tab()
696
+	{
697
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
698
+	}
699
+    
700
+    
701
+	public function message_templates_help_tab()
702
+	{
703
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
704
+	}
705
+    
706
+    
707
+	public function edit_message_template_help_tab()
708
+	{
709
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
+				'event_espresso') . '" />';
711
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
+				'event_espresso') . '" />';
713
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
+				'event_espresso') . '" />';
715
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
+				'event_espresso') . '" />';
717
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
+				'event_espresso') . '" />';
719
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
720
+			$args);
721
+	}
722
+    
723
+    
724
+	public function message_template_shortcodes_help_tab()
725
+	{
726
+		$this->_set_shortcodes();
727
+		$args['shortcodes'] = $this->_shortcodes;
728
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
729
+			$args);
730
+	}
731 731
     
732 732
     
733
-    public function preview_message_help_tab()
734
-    {
735
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
736
-    }
733
+	public function preview_message_help_tab()
734
+	{
735
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
736
+	}
737 737
     
738
-    
739
-    public function settings_help_tab()
740
-    {
741
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
-                'event_espresso') . '" />';
743
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
-                'event_espresso') . '" />';
745
-        $args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746
-        $args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
748
-    }
738
+    
739
+	public function settings_help_tab()
740
+	{
741
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
+				'event_espresso') . '" />';
743
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
+				'event_espresso') . '" />';
745
+		$args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746
+		$args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
748
+	}
749 749
     
750 750
     
751
-    public function load_scripts_styles()
752
-    {
753
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754
-        wp_enqueue_style('espresso_ee_msg');
751
+	public function load_scripts_styles()
752
+	{
753
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754
+		wp_enqueue_style('espresso_ee_msg');
755 755
         
756
-        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
757
-            array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
-        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
759
-            array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760
-    }
756
+		wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
757
+			array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
+		wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
759
+			array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760
+	}
761 761
     
762 762
     
763
-    public function load_scripts_styles_default()
764
-    {
765
-        wp_enqueue_script('ee-msg-list-table-js');
766
-    }
763
+	public function load_scripts_styles_default()
764
+	{
765
+		wp_enqueue_script('ee-msg-list-table-js');
766
+	}
767 767
     
768 768
     
769
-    public function wp_editor_css($mce_css)
770
-    {
771
-        //if we're on the edit_message_template route
772
-        if ($this->_req_action == 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
773
-            $message_type_name = $this->_active_message_type_name;
769
+	public function wp_editor_css($mce_css)
770
+	{
771
+		//if we're on the edit_message_template route
772
+		if ($this->_req_action == 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
773
+			$message_type_name = $this->_active_message_type_name;
774 774
             
775
-            //we're going to REPLACE the existing mce css
776
-            //we need to get the css file location from the active messenger
777
-            $mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
778
-                'wpeditor', $this->_variation);
779
-        }
775
+			//we're going to REPLACE the existing mce css
776
+			//we need to get the css file location from the active messenger
777
+			$mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
778
+				'wpeditor', $this->_variation);
779
+		}
780 780
         
781
-        return $mce_css;
782
-    }
781
+		return $mce_css;
782
+	}
783 783
     
784 784
     
785
-    public function load_scripts_styles_edit_message_template()
786
-    {
785
+	public function load_scripts_styles_edit_message_template()
786
+	{
787 787
         
788
-        $this->_set_shortcodes();
788
+		$this->_set_shortcodes();
789 789
         
790
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
791
-            __('Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
792
-                'event_espresso'),
793
-            $this->_message_template_group->messenger_obj()->label['singular'],
794
-            $this->_message_template_group->message_type_obj()->label['singular']
795
-        );
796
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
797
-            'event_espresso');
790
+		EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
791
+			__('Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
792
+				'event_espresso'),
793
+			$this->_message_template_group->messenger_obj()->label['singular'],
794
+			$this->_message_template_group->message_type_obj()->label['singular']
795
+		);
796
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
797
+			'event_espresso');
798 798
         
799
-        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
800
-            EVENT_ESPRESSO_VERSION);
799
+		wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
800
+			EVENT_ESPRESSO_VERSION);
801 801
         
802
-        wp_enqueue_script('ee_admin_js');
803
-        wp_enqueue_script('ee_msgs_edit_js');
802
+		wp_enqueue_script('ee_admin_js');
803
+		wp_enqueue_script('ee_msgs_edit_js');
804 804
         
805
-        //add in special css for tiny_mce
806
-        add_filter('mce_css', array($this, 'wp_editor_css'));
807
-    }
805
+		//add in special css for tiny_mce
806
+		add_filter('mce_css', array($this, 'wp_editor_css'));
807
+	}
808 808
     
809 809
     
810
-    public function load_scripts_styles_display_preview_message()
811
-    {
810
+	public function load_scripts_styles_display_preview_message()
811
+	{
812 812
         
813
-        $this->_set_message_template_group();
813
+		$this->_set_message_template_group();
814 814
         
815
-        if (isset($this->_req_data['messenger'])) {
816
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
817
-        }
815
+		if (isset($this->_req_data['messenger'])) {
816
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
817
+		}
818 818
         
819
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
819
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
820 820
         
821 821
         
822
-        wp_enqueue_style('espresso_preview_css',
823
-            $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true, 'preview',
824
-                $this->_variation));
825
-    }
822
+		wp_enqueue_style('espresso_preview_css',
823
+			$this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true, 'preview',
824
+				$this->_variation));
825
+	}
826 826
     
827 827
     
828
-    public function load_scripts_styles_settings()
829
-    {
830
-        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
831
-            EVENT_ESPRESSO_VERSION);
832
-        wp_enqueue_style('ee-text-links');
833
-        wp_enqueue_style('ee-message-settings');
828
+	public function load_scripts_styles_settings()
829
+	{
830
+		wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
831
+			EVENT_ESPRESSO_VERSION);
832
+		wp_enqueue_style('ee-text-links');
833
+		wp_enqueue_style('ee-message-settings');
834 834
         
835
-        wp_enqueue_script('ee-messages-settings');
836
-    }
835
+		wp_enqueue_script('ee-messages-settings');
836
+	}
837 837
     
838 838
     
839
-    /**
840
-     * set views array for List Table
841
-     */
842
-    public function _set_list_table_views_global_mtps()
843
-    {
844
-        $this->_views = array(
845
-            'in_use' => array(
846
-                'slug'        => 'in_use',
847
-                'label'       => __('In Use', 'event_espresso'),
848
-                'count'       => 0,
849
-            )
850
-        );
851
-    }
839
+	/**
840
+	 * set views array for List Table
841
+	 */
842
+	public function _set_list_table_views_global_mtps()
843
+	{
844
+		$this->_views = array(
845
+			'in_use' => array(
846
+				'slug'        => 'in_use',
847
+				'label'       => __('In Use', 'event_espresso'),
848
+				'count'       => 0,
849
+			)
850
+		);
851
+	}
852 852
 
853 853
 
854
-    /**
855
-     * Set views array for the Custom Template List Table
856
-     */
857
-    public function _set_list_table_views_custom_mtps()
858
-    {
859
-        $this->_set_list_table_views_global_mtps();
860
-        $this->_views['in_use']['bulk_action'] = array(
861
-                'trash_message_template' => esc_html__('Move to Trash', 'event_espresso')
862
-        );
863
-    }
864
-    
865
-    
866
-    /**
867
-     * set views array for message queue list table
868
-     */
869
-    public function _set_list_table_views_default()
870
-    {
871
-        EE_Registry::instance()->load_helper('Template');
872
-        
873
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can('ee_send_message',
874
-            'message_list_table_bulk_actions')
875
-            ? array(
876
-                'generate_now'          => __('Generate Now', 'event_espresso'),
877
-                'generate_and_send_now' => __('Generate and Send Now', 'event_espresso'),
878
-                'queue_for_resending'   => __('Queue for Resending', 'event_espresso'),
879
-                'send_now'              => __('Send Now', 'event_espresso')
880
-            )
881
-            : array();
882
-        
883
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can('ee_delete_messages',
884
-            'message_list_table_bulk_actions')
885
-            ? array('delete_ee_messages' => __('Delete Messages', 'event_espresso'))
886
-            : array();
887
-        
888
-        
889
-        $this->_views = array(
890
-            'all' => array(
891
-                'slug'        => 'all',
892
-                'label'       => __('All', 'event_espresso'),
893
-                'count'       => 0,
894
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
895
-            )
896
-        );
897
-        
898
-        
899
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
900
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
901
-                continue;
902
-            }
903
-            $status_bulk_actions = $common_bulk_actions;
904
-            //unset bulk actions not applying to status
905
-            if (! empty($status_bulk_actions)) {
906
-                switch ($status) {
907
-                    case EEM_Message::status_idle:
908
-                    case EEM_Message::status_resend:
909
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
910
-                        break;
854
+	/**
855
+	 * Set views array for the Custom Template List Table
856
+	 */
857
+	public function _set_list_table_views_custom_mtps()
858
+	{
859
+		$this->_set_list_table_views_global_mtps();
860
+		$this->_views['in_use']['bulk_action'] = array(
861
+				'trash_message_template' => esc_html__('Move to Trash', 'event_espresso')
862
+		);
863
+	}
864
+    
865
+    
866
+	/**
867
+	 * set views array for message queue list table
868
+	 */
869
+	public function _set_list_table_views_default()
870
+	{
871
+		EE_Registry::instance()->load_helper('Template');
872
+        
873
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can('ee_send_message',
874
+			'message_list_table_bulk_actions')
875
+			? array(
876
+				'generate_now'          => __('Generate Now', 'event_espresso'),
877
+				'generate_and_send_now' => __('Generate and Send Now', 'event_espresso'),
878
+				'queue_for_resending'   => __('Queue for Resending', 'event_espresso'),
879
+				'send_now'              => __('Send Now', 'event_espresso')
880
+			)
881
+			: array();
882
+        
883
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can('ee_delete_messages',
884
+			'message_list_table_bulk_actions')
885
+			? array('delete_ee_messages' => __('Delete Messages', 'event_espresso'))
886
+			: array();
887
+        
888
+        
889
+		$this->_views = array(
890
+			'all' => array(
891
+				'slug'        => 'all',
892
+				'label'       => __('All', 'event_espresso'),
893
+				'count'       => 0,
894
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
895
+			)
896
+		);
897
+        
898
+        
899
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
900
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
901
+				continue;
902
+			}
903
+			$status_bulk_actions = $common_bulk_actions;
904
+			//unset bulk actions not applying to status
905
+			if (! empty($status_bulk_actions)) {
906
+				switch ($status) {
907
+					case EEM_Message::status_idle:
908
+					case EEM_Message::status_resend:
909
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
910
+						break;
911 911
                     
912
-                    case EEM_Message::status_failed:
913
-                    case EEM_Message::status_debug_only:
914
-                    case EEM_Message::status_messenger_executing:
915
-                        $status_bulk_actions = array();
916
-                        break;
912
+					case EEM_Message::status_failed:
913
+					case EEM_Message::status_debug_only:
914
+					case EEM_Message::status_messenger_executing:
915
+						$status_bulk_actions = array();
916
+						break;
917 917
                     
918
-                    case EEM_Message::status_incomplete:
919
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
920
-                        break;
918
+					case EEM_Message::status_incomplete:
919
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
920
+						break;
921 921
                     
922
-                    case EEM_Message::status_retry:
923
-                    case EEM_Message::status_sent:
924
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
925
-                        break;
926
-                }
927
-            }
922
+					case EEM_Message::status_retry:
923
+					case EEM_Message::status_sent:
924
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
925
+						break;
926
+				}
927
+			}
928 928
 
929
-            //skip adding messenger executing status to views because it will be included with the Failed view.
930
-            if ( $status === EEM_Message::status_messenger_executing ) {
931
-                continue;
932
-            }
929
+			//skip adding messenger executing status to views because it will be included with the Failed view.
930
+			if ( $status === EEM_Message::status_messenger_executing ) {
931
+				continue;
932
+			}
933 933
             
934
-            $this->_views[strtolower($status)] = array(
935
-                'slug'        => strtolower($status),
936
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
937
-                'count'       => 0,
938
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
939
-            );
940
-        }
941
-    }
942
-    
943
-    
944
-    protected function _ee_default_messages_overview_list_table()
945
-    {
946
-        $this->_admin_page_title = __('Default Message Templates', 'event_espresso');
947
-        $this->display_admin_list_table_page_with_no_sidebar();
948
-    }
949
-    
950
-    
951
-    protected function _message_queue_list_table()
952
-    {
953
-        $this->_search_btn_label                   = __('Message Activity', 'event_espresso');
954
-        $this->_template_args['per_column']        = 6;
955
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
956
-        $this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
957
-        $this->display_admin_list_table_page_with_no_sidebar();
958
-    }
959
-    
960
-    
961
-    protected function _message_legend_items()
962
-    {
963
-        
964
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
965
-        $action_items       = array();
966
-        
967
-        foreach ($action_css_classes as $action_item => $action_details) {
968
-            if ($action_item === 'see_notifications_for') {
969
-                continue;
970
-            }
971
-            $action_items[$action_item] = array(
972
-                'class' => $action_details['css_class'],
973
-                'desc'  => $action_details['label']
974
-            );
975
-        }
976
-        
977
-        /** @type array $status_items status legend setup */
978
-        $status_items = array(
979
-            'sent_status'       => array(
980
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
981
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
982
-            ),
983
-            'idle_status'       => array(
984
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
985
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
986
-            ),
987
-            'failed_status'     => array(
988
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
989
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
990
-            ),
991
-            'messenger_executing_status' => array(
992
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
993
-                'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
994
-            ),
995
-            'resend_status'     => array(
996
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
997
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
998
-            ),
999
-            'incomplete_status' => array(
1000
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1001
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
1002
-            ),
1003
-            'retry_status'      => array(
1004
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1005
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
1006
-            )
1007
-        );
1008
-        if (EEM_Message::debug()) {
1009
-            $status_items['debug_only_status'] = array(
1010
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1011
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1012
-            );
1013
-        }
1014
-        
1015
-        return array_merge($action_items, $status_items);
1016
-    }
1017
-    
1018
-    
1019
-    protected function _custom_mtps_preview()
1020
-    {
1021
-        $this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1022
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1023
-                'event_espresso') . '" />';
1024
-        $this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1025
-                'event_espresso') . '</strong>';
1026
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1027
-    }
1028
-    
1029
-    
1030
-    /**
1031
-     * get_message_templates
1032
-     * This gets all the message templates for listing on the overview list.
1033
-     *
1034
-     * @access public
1035
-     *
1036
-     * @param int    $perpage the amount of templates groups to show per page
1037
-     * @param string $type    the current _view we're getting templates for
1038
-     * @param bool   $count   return count?
1039
-     * @param bool   $all     disregard any paging info (get all data);
1040
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1041
-     *
1042
-     * @return array
1043
-     */
1044
-    public function get_message_templates($perpage = 10, $type = 'in_use', $count = false, $all = false, $global = true)
1045
-    {
1046
-        
1047
-        $MTP = EEM_Message_Template_Group::instance();
1048
-        
1049
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1050
-        $orderby                    = $this->_req_data['orderby'];
1051
-        
1052
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
1053
-        
1054
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1055
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $perpage;
1056
-        
1057
-        $offset = ($current_page - 1) * $per_page;
1058
-        $limit  = $all ? null : array($offset, $per_page);
1059
-        
1060
-        
1061
-        //options will match what is in the _views array property
1062
-        switch ($type) {
934
+			$this->_views[strtolower($status)] = array(
935
+				'slug'        => strtolower($status),
936
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
937
+				'count'       => 0,
938
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
939
+			);
940
+		}
941
+	}
942
+    
943
+    
944
+	protected function _ee_default_messages_overview_list_table()
945
+	{
946
+		$this->_admin_page_title = __('Default Message Templates', 'event_espresso');
947
+		$this->display_admin_list_table_page_with_no_sidebar();
948
+	}
949
+    
950
+    
951
+	protected function _message_queue_list_table()
952
+	{
953
+		$this->_search_btn_label                   = __('Message Activity', 'event_espresso');
954
+		$this->_template_args['per_column']        = 6;
955
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
956
+		$this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
957
+		$this->display_admin_list_table_page_with_no_sidebar();
958
+	}
959
+    
960
+    
961
+	protected function _message_legend_items()
962
+	{
963
+        
964
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
965
+		$action_items       = array();
966
+        
967
+		foreach ($action_css_classes as $action_item => $action_details) {
968
+			if ($action_item === 'see_notifications_for') {
969
+				continue;
970
+			}
971
+			$action_items[$action_item] = array(
972
+				'class' => $action_details['css_class'],
973
+				'desc'  => $action_details['label']
974
+			);
975
+		}
976
+        
977
+		/** @type array $status_items status legend setup */
978
+		$status_items = array(
979
+			'sent_status'       => array(
980
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
981
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
982
+			),
983
+			'idle_status'       => array(
984
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
985
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
986
+			),
987
+			'failed_status'     => array(
988
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
989
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
990
+			),
991
+			'messenger_executing_status' => array(
992
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
993
+				'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
994
+			),
995
+			'resend_status'     => array(
996
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
997
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
998
+			),
999
+			'incomplete_status' => array(
1000
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1001
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
1002
+			),
1003
+			'retry_status'      => array(
1004
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1005
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
1006
+			)
1007
+		);
1008
+		if (EEM_Message::debug()) {
1009
+			$status_items['debug_only_status'] = array(
1010
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1011
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1012
+			);
1013
+		}
1014
+        
1015
+		return array_merge($action_items, $status_items);
1016
+	}
1017
+    
1018
+    
1019
+	protected function _custom_mtps_preview()
1020
+	{
1021
+		$this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1022
+		$this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1023
+				'event_espresso') . '" />';
1024
+		$this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1025
+				'event_espresso') . '</strong>';
1026
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1027
+	}
1028
+    
1029
+    
1030
+	/**
1031
+	 * get_message_templates
1032
+	 * This gets all the message templates for listing on the overview list.
1033
+	 *
1034
+	 * @access public
1035
+	 *
1036
+	 * @param int    $perpage the amount of templates groups to show per page
1037
+	 * @param string $type    the current _view we're getting templates for
1038
+	 * @param bool   $count   return count?
1039
+	 * @param bool   $all     disregard any paging info (get all data);
1040
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1041
+	 *
1042
+	 * @return array
1043
+	 */
1044
+	public function get_message_templates($perpage = 10, $type = 'in_use', $count = false, $all = false, $global = true)
1045
+	{
1046
+        
1047
+		$MTP = EEM_Message_Template_Group::instance();
1048
+        
1049
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1050
+		$orderby                    = $this->_req_data['orderby'];
1051
+        
1052
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
1053
+        
1054
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1055
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $perpage;
1056
+        
1057
+		$offset = ($current_page - 1) * $per_page;
1058
+		$limit  = $all ? null : array($offset, $per_page);
1059
+        
1060
+        
1061
+		//options will match what is in the _views array property
1062
+		switch ($type) {
1063 1063
             
1064
-            case 'in_use':
1065
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1066
-                break;
1064
+			case 'in_use':
1065
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1066
+				break;
1067 1067
             
1068
-            default:
1069
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1068
+			default:
1069
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1070 1070
             
1071
-        }
1072
-        
1073
-        return $templates;
1074
-    }
1075
-    
1076
-    
1077
-    /**
1078
-     * filters etc might need a list of installed message_types
1079
-     * @return array an array of message type objects
1080
-     */
1081
-    public function get_installed_message_types()
1082
-    {
1083
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1084
-        $installed               = array();
1085
-        
1086
-        foreach ($installed_message_types as $message_type) {
1087
-            $installed[$message_type->name] = $message_type;
1088
-        }
1089
-        
1090
-        return $installed;
1091
-    }
1092
-    
1093
-    
1094
-    /**
1095
-     * _add_message_template
1096
-     *
1097
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1098
-     *
1099
-     * @param string $message_type
1100
-     * @param string $messenger
1101
-     * @param string $GRP_ID
1102
-     *
1103
-     * @throws EE_error
1104
-     */
1105
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1106
-    {
1107
-        //set values override any request data
1108
-        $message_type = ! empty($message_type) ? $message_type : '';
1109
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type']) ? $this->_req_data['message_type'] : $message_type;
1110
-        
1111
-        $messenger = ! empty($messenger) ? $messenger : '';
1112
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger']) ? $this->_req_data['messenger'] : $messenger;
1113
-        
1114
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1115
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1116
-        
1117
-        //we need messenger and message type.  They should be coming from the event editor. If not here then return error
1118
-        if (empty($message_type) || empty($messenger)) {
1119
-            throw new EE_error(__('Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1120
-                'event_espresso'));
1121
-        }
1122
-        
1123
-        //we need the GRP_ID for the template being used as the base for the new template
1124
-        if (empty($GRP_ID)) {
1125
-            throw new EE_Error(__('In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1126
-                'event_espresso'));
1127
-        }
1128
-        
1129
-        //let's just make sure the template gets generated!
1130
-        
1131
-        //we need to reassign some variables for what the insert is expecting
1132
-        $this->_req_data['MTP_messenger']    = $messenger;
1133
-        $this->_req_data['MTP_message_type'] = $message_type;
1134
-        $this->_req_data['GRP_ID']           = $GRP_ID;
1135
-        $this->_insert_or_update_message_template(true);
1136
-    }
1137
-    
1138
-    
1139
-    /**
1140
-     * public wrapper for the _add_message_template method
1141
-     *
1142
-     * @param string $message_type     message type slug
1143
-     * @param string $messenger        messenger slug
1144
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1145
-     *                                 off of.
1146
-     */
1147
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1148
-    {
1149
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1150
-    }
1151
-    
1152
-    
1153
-    /**
1154
-     * _edit_message_template
1155
-     *
1156
-     * @access protected
1157
-     * @return void
1158
-     */
1159
-    protected function _edit_message_template()
1160
-    {
1161
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1162
-        $template_fields = '';
1163
-        $sidebar_fields  = '';
1164
-        //we filter the tinyMCE settings to remove the validation since message templates by their nature will not have valid html in the templates.
1165
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1166
-        
1167
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1168
-            ? absint($this->_req_data['id'])
1169
-            : false;
1170
-        
1171
-        $this->_set_shortcodes(); //this also sets the _message_template property.
1172
-        $message_template_group = $this->_message_template_group;
1173
-        $c_label                = $message_template_group->context_label();
1174
-        $c_config               = $message_template_group->contexts_config();
1175
-        
1176
-        reset($c_config);
1177
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1178
-            ? strtolower($this->_req_data['context'])
1179
-            : key($c_config);
1180
-        
1181
-        
1182
-        if (empty($GRP_ID)) {
1183
-            $action = 'insert_message_template';
1184
-            //$button_both = false;
1185
-            //$button_text = array( __( 'Save','event_espresso') );
1186
-            //$button_actions = array('something_different');
1187
-            //$referrer = false;
1188
-            $edit_message_template_form_url = add_query_arg(
1189
-                array('action' => $action, 'noheader' => true),
1190
-                EE_MSG_ADMIN_URL
1191
-            );
1192
-        } else {
1193
-            $action = 'update_message_template';
1194
-            //$button_both = true;
1195
-            //$button_text = array();
1196
-            //$button_actions = array();
1197
-            //$referrer = $this->_admin_base_url;
1198
-            $edit_message_template_form_url = add_query_arg(
1199
-                array('action' => $action, 'noheader' => true),
1200
-                EE_MSG_ADMIN_URL
1201
-            );
1202
-        }
1203
-        
1204
-        //set active messenger for this view
1205
-        $this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1206
-            $message_template_group->messenger()
1207
-        );
1208
-        $this->_active_message_type_name = $message_template_group->message_type();
1209
-        
1210
-        
1211
-        //Do we have any validation errors?
1212
-        $validators = $this->_get_transient();
1213
-        $v_fields   = ! empty($validators) ? array_keys($validators) : array();
1214
-        
1215
-        
1216
-        //we need to assemble the title from Various details
1217
-        $context_label = sprintf(
1218
-            __('(%s %s)', 'event_espresso'),
1219
-            $c_config[$context]['label'],
1220
-            ucwords($c_label['label'])
1221
-        );
1222
-        
1223
-        $title = sprintf(
1224
-            __(' %s %s Template %s', 'event_espresso'),
1225
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1226
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1227
-            $context_label
1228
-        );
1229
-        
1230
-        $this->_template_args['GRP_ID']           = $GRP_ID;
1231
-        $this->_template_args['message_template'] = $message_template_group;
1232
-        $this->_template_args['is_extra_fields']  = false;
1233
-        
1234
-        
1235
-        //let's get EEH_MSG_Template so we can get template form fields
1236
-        $template_field_structure = EEH_MSG_Template::get_fields(
1237
-            $message_template_group->messenger(),
1238
-            $message_template_group->message_type()
1239
-        );
1240
-        
1241
-        if ( ! $template_field_structure) {
1242
-            $template_field_structure = false;
1243
-            $template_fields          = __('There was an error in assembling the fields for this display (you should see an error message)',
1244
-                'event_espresso');
1245
-        }
1246
-        
1247
-        
1248
-        $message_templates = $message_template_group->context_templates();
1249
-        
1250
-        
1251
-        //if we have the extra key.. then we need to remove the content index from the template_field_structure as it will get handled in the "extra" array.
1252
-        if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1253
-            foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1254
-                unset($template_field_structure[$context][$reference_field]);
1255
-            }
1256
-        }
1257
-        
1258
-        //let's loop through the template_field_structure and actually assemble the input fields!
1259
-        if ( ! empty($template_field_structure)) {
1260
-            foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1261
-                //if this is an 'extra' template field then we need to remove any existing fields that are keyed up in the extra array and reset them.
1262
-                if ($template_field == 'extra') {
1263
-                    $this->_template_args['is_extra_fields'] = true;
1264
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1265
-                        $message_template = $message_templates[$context][$reference_field];
1266
-                        $content          = $message_template instanceof EE_Message_Template
1267
-                            ? $message_template->get('MTP_content')
1268
-                            : '';
1269
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1270
-                            //let's verify if we need this extra field via the shortcodes parameter.
1271
-                            $continue = false;
1272
-                            if (isset($extra_array['shortcodes_required'])) {
1273
-                                foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1274
-                                    if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1275
-                                        $continue = true;
1276
-                                    }
1277
-                                }
1278
-                                if ($continue) {
1279
-                                    continue;
1280
-                                }
1281
-                            }
1071
+		}
1072
+        
1073
+		return $templates;
1074
+	}
1075
+    
1076
+    
1077
+	/**
1078
+	 * filters etc might need a list of installed message_types
1079
+	 * @return array an array of message type objects
1080
+	 */
1081
+	public function get_installed_message_types()
1082
+	{
1083
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1084
+		$installed               = array();
1085
+        
1086
+		foreach ($installed_message_types as $message_type) {
1087
+			$installed[$message_type->name] = $message_type;
1088
+		}
1089
+        
1090
+		return $installed;
1091
+	}
1092
+    
1093
+    
1094
+	/**
1095
+	 * _add_message_template
1096
+	 *
1097
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1098
+	 *
1099
+	 * @param string $message_type
1100
+	 * @param string $messenger
1101
+	 * @param string $GRP_ID
1102
+	 *
1103
+	 * @throws EE_error
1104
+	 */
1105
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1106
+	{
1107
+		//set values override any request data
1108
+		$message_type = ! empty($message_type) ? $message_type : '';
1109
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type']) ? $this->_req_data['message_type'] : $message_type;
1110
+        
1111
+		$messenger = ! empty($messenger) ? $messenger : '';
1112
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger']) ? $this->_req_data['messenger'] : $messenger;
1113
+        
1114
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1115
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1116
+        
1117
+		//we need messenger and message type.  They should be coming from the event editor. If not here then return error
1118
+		if (empty($message_type) || empty($messenger)) {
1119
+			throw new EE_error(__('Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1120
+				'event_espresso'));
1121
+		}
1122
+        
1123
+		//we need the GRP_ID for the template being used as the base for the new template
1124
+		if (empty($GRP_ID)) {
1125
+			throw new EE_Error(__('In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1126
+				'event_espresso'));
1127
+		}
1128
+        
1129
+		//let's just make sure the template gets generated!
1130
+        
1131
+		//we need to reassign some variables for what the insert is expecting
1132
+		$this->_req_data['MTP_messenger']    = $messenger;
1133
+		$this->_req_data['MTP_message_type'] = $message_type;
1134
+		$this->_req_data['GRP_ID']           = $GRP_ID;
1135
+		$this->_insert_or_update_message_template(true);
1136
+	}
1137
+    
1138
+    
1139
+	/**
1140
+	 * public wrapper for the _add_message_template method
1141
+	 *
1142
+	 * @param string $message_type     message type slug
1143
+	 * @param string $messenger        messenger slug
1144
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1145
+	 *                                 off of.
1146
+	 */
1147
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1148
+	{
1149
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1150
+	}
1151
+    
1152
+    
1153
+	/**
1154
+	 * _edit_message_template
1155
+	 *
1156
+	 * @access protected
1157
+	 * @return void
1158
+	 */
1159
+	protected function _edit_message_template()
1160
+	{
1161
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1162
+		$template_fields = '';
1163
+		$sidebar_fields  = '';
1164
+		//we filter the tinyMCE settings to remove the validation since message templates by their nature will not have valid html in the templates.
1165
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1166
+        
1167
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1168
+			? absint($this->_req_data['id'])
1169
+			: false;
1170
+        
1171
+		$this->_set_shortcodes(); //this also sets the _message_template property.
1172
+		$message_template_group = $this->_message_template_group;
1173
+		$c_label                = $message_template_group->context_label();
1174
+		$c_config               = $message_template_group->contexts_config();
1175
+        
1176
+		reset($c_config);
1177
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1178
+			? strtolower($this->_req_data['context'])
1179
+			: key($c_config);
1180
+        
1181
+        
1182
+		if (empty($GRP_ID)) {
1183
+			$action = 'insert_message_template';
1184
+			//$button_both = false;
1185
+			//$button_text = array( __( 'Save','event_espresso') );
1186
+			//$button_actions = array('something_different');
1187
+			//$referrer = false;
1188
+			$edit_message_template_form_url = add_query_arg(
1189
+				array('action' => $action, 'noheader' => true),
1190
+				EE_MSG_ADMIN_URL
1191
+			);
1192
+		} else {
1193
+			$action = 'update_message_template';
1194
+			//$button_both = true;
1195
+			//$button_text = array();
1196
+			//$button_actions = array();
1197
+			//$referrer = $this->_admin_base_url;
1198
+			$edit_message_template_form_url = add_query_arg(
1199
+				array('action' => $action, 'noheader' => true),
1200
+				EE_MSG_ADMIN_URL
1201
+			);
1202
+		}
1203
+        
1204
+		//set active messenger for this view
1205
+		$this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1206
+			$message_template_group->messenger()
1207
+		);
1208
+		$this->_active_message_type_name = $message_template_group->message_type();
1209
+        
1210
+        
1211
+		//Do we have any validation errors?
1212
+		$validators = $this->_get_transient();
1213
+		$v_fields   = ! empty($validators) ? array_keys($validators) : array();
1214
+        
1215
+        
1216
+		//we need to assemble the title from Various details
1217
+		$context_label = sprintf(
1218
+			__('(%s %s)', 'event_espresso'),
1219
+			$c_config[$context]['label'],
1220
+			ucwords($c_label['label'])
1221
+		);
1222
+        
1223
+		$title = sprintf(
1224
+			__(' %s %s Template %s', 'event_espresso'),
1225
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1226
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1227
+			$context_label
1228
+		);
1229
+        
1230
+		$this->_template_args['GRP_ID']           = $GRP_ID;
1231
+		$this->_template_args['message_template'] = $message_template_group;
1232
+		$this->_template_args['is_extra_fields']  = false;
1233
+        
1234
+        
1235
+		//let's get EEH_MSG_Template so we can get template form fields
1236
+		$template_field_structure = EEH_MSG_Template::get_fields(
1237
+			$message_template_group->messenger(),
1238
+			$message_template_group->message_type()
1239
+		);
1240
+        
1241
+		if ( ! $template_field_structure) {
1242
+			$template_field_structure = false;
1243
+			$template_fields          = __('There was an error in assembling the fields for this display (you should see an error message)',
1244
+				'event_espresso');
1245
+		}
1246
+        
1247
+        
1248
+		$message_templates = $message_template_group->context_templates();
1249
+        
1250
+        
1251
+		//if we have the extra key.. then we need to remove the content index from the template_field_structure as it will get handled in the "extra" array.
1252
+		if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1253
+			foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1254
+				unset($template_field_structure[$context][$reference_field]);
1255
+			}
1256
+		}
1257
+        
1258
+		//let's loop through the template_field_structure and actually assemble the input fields!
1259
+		if ( ! empty($template_field_structure)) {
1260
+			foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1261
+				//if this is an 'extra' template field then we need to remove any existing fields that are keyed up in the extra array and reset them.
1262
+				if ($template_field == 'extra') {
1263
+					$this->_template_args['is_extra_fields'] = true;
1264
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1265
+						$message_template = $message_templates[$context][$reference_field];
1266
+						$content          = $message_template instanceof EE_Message_Template
1267
+							? $message_template->get('MTP_content')
1268
+							: '';
1269
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1270
+							//let's verify if we need this extra field via the shortcodes parameter.
1271
+							$continue = false;
1272
+							if (isset($extra_array['shortcodes_required'])) {
1273
+								foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1274
+									if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1275
+										$continue = true;
1276
+									}
1277
+								}
1278
+								if ($continue) {
1279
+									continue;
1280
+								}
1281
+							}
1282 1282
                             
1283
-                            $field_id                                = $reference_field . '-' . $extra_field . '-content';
1284
-                            $template_form_fields[$field_id]         = $extra_array;
1285
-                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1286
-                            $css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1283
+							$field_id                                = $reference_field . '-' . $extra_field . '-content';
1284
+							$template_form_fields[$field_id]         = $extra_array;
1285
+							$template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1286
+							$css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1287 1287
                             
1288
-                            $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1289
-                                                                            && in_array($extra_field, $v_fields)
1290
-                                                                            &&
1291
-                                                                            (
1292
-                                                                                is_array($validators[$extra_field])
1293
-                                                                                && isset($validators[$extra_field]['msg'])
1294
-                                                                            )
1295
-                                ? 'validate-error ' . $css_class
1296
-                                : $css_class;
1288
+							$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1289
+																			&& in_array($extra_field, $v_fields)
1290
+																			&&
1291
+																			(
1292
+																				is_array($validators[$extra_field])
1293
+																				&& isset($validators[$extra_field]['msg'])
1294
+																			)
1295
+								? 'validate-error ' . $css_class
1296
+								: $css_class;
1297 1297
                             
1298
-                            $template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
1299
-                                ? stripslashes(html_entity_decode($content[$extra_field], ENT_QUOTES, "UTF-8"))
1300
-                                : '';
1298
+							$template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
1299
+								? stripslashes(html_entity_decode($content[$extra_field], ENT_QUOTES, "UTF-8"))
1300
+								: '';
1301 1301
                             
1302
-                            //do we have a validation error?  if we do then let's use that value instead
1303
-                            $template_form_fields[$field_id]['value'] = isset($validators[$extra_field]) ? $validators[$extra_field]['value'] : $template_form_fields[$field_id]['value'];
1302
+							//do we have a validation error?  if we do then let's use that value instead
1303
+							$template_form_fields[$field_id]['value'] = isset($validators[$extra_field]) ? $validators[$extra_field]['value'] : $template_form_fields[$field_id]['value'];
1304 1304
                             
1305 1305
                             
1306
-                            $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1306
+							$template_form_fields[$field_id]['db-col'] = 'MTP_content';
1307 1307
                             
1308
-                            //shortcode selector
1309
-                            $field_name_to_use                                 = $extra_field == 'main' ? 'content' : $extra_field;
1310
-                            $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1311
-                                $field_name_to_use,
1312
-                                $field_id
1313
-                            );
1308
+							//shortcode selector
1309
+							$field_name_to_use                                 = $extra_field == 'main' ? 'content' : $extra_field;
1310
+							$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1311
+								$field_name_to_use,
1312
+								$field_id
1313
+							);
1314 1314
                             
1315
-                            if (isset($extra_array['input']) && $extra_array['input'] == 'wp_editor') {
1316
-                                //we want to decode the entities
1317
-                                $template_form_fields[$field_id]['value'] = stripslashes(
1318
-                                    html_entity_decode($template_form_fields[$field_id]['value'], ENT_QUOTES, "UTF-8")
1319
-                                );
1315
+							if (isset($extra_array['input']) && $extra_array['input'] == 'wp_editor') {
1316
+								//we want to decode the entities
1317
+								$template_form_fields[$field_id]['value'] = stripslashes(
1318
+									html_entity_decode($template_form_fields[$field_id]['value'], ENT_QUOTES, "UTF-8")
1319
+								);
1320 1320
                                 
1321
-                            }/**/
1322
-                        }
1323
-                        $templatefield_MTP_id          = $reference_field . '-MTP_ID';
1324
-                        $templatefield_templatename_id = $reference_field . '-name';
1321
+							}/**/
1322
+						}
1323
+						$templatefield_MTP_id          = $reference_field . '-MTP_ID';
1324
+						$templatefield_templatename_id = $reference_field . '-name';
1325 1325
                         
1326
-                        $template_form_fields[$templatefield_MTP_id] = array(
1327
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1328
-                            'label'      => null,
1329
-                            'input'      => 'hidden',
1330
-                            'type'       => 'int',
1331
-                            'required'   => false,
1332
-                            'validation' => false,
1333
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1334
-                            'css_class'  => '',
1335
-                            'format'     => '%d',
1336
-                            'db-col'     => 'MTP_ID'
1337
-                        );
1326
+						$template_form_fields[$templatefield_MTP_id] = array(
1327
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1328
+							'label'      => null,
1329
+							'input'      => 'hidden',
1330
+							'type'       => 'int',
1331
+							'required'   => false,
1332
+							'validation' => false,
1333
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1334
+							'css_class'  => '',
1335
+							'format'     => '%d',
1336
+							'db-col'     => 'MTP_ID'
1337
+						);
1338 1338
                         
1339
-                        $template_form_fields[$templatefield_templatename_id] = array(
1340
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1341
-                            'label'      => null,
1342
-                            'input'      => 'hidden',
1343
-                            'type'       => 'string',
1344
-                            'required'   => false,
1345
-                            'validation' => true,
1346
-                            'value'      => $reference_field,
1347
-                            'css_class'  => '',
1348
-                            'format'     => '%s',
1349
-                            'db-col'     => 'MTP_template_field'
1350
-                        );
1351
-                    }
1352
-                    continue; //skip the next stuff, we got the necessary fields here for this dataset.
1353
-                } else {
1354
-                    $field_id                                 = $template_field . '-content';
1355
-                    $template_form_fields[$field_id]          = $field_setup_array;
1356
-                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1357
-                    $message_template                         = isset($message_templates[$context][$template_field])
1358
-                        ? $message_templates[$context][$template_field]
1359
-                        : null;
1360
-                    $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1361
-                                                                && is_array($message_templates[$context])
1362
-                                                                && $message_template instanceof EE_Message_Template
1363
-                        ? $message_template->get('MTP_content')
1364
-                        : '';
1339
+						$template_form_fields[$templatefield_templatename_id] = array(
1340
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1341
+							'label'      => null,
1342
+							'input'      => 'hidden',
1343
+							'type'       => 'string',
1344
+							'required'   => false,
1345
+							'validation' => true,
1346
+							'value'      => $reference_field,
1347
+							'css_class'  => '',
1348
+							'format'     => '%s',
1349
+							'db-col'     => 'MTP_template_field'
1350
+						);
1351
+					}
1352
+					continue; //skip the next stuff, we got the necessary fields here for this dataset.
1353
+				} else {
1354
+					$field_id                                 = $template_field . '-content';
1355
+					$template_form_fields[$field_id]          = $field_setup_array;
1356
+					$template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1357
+					$message_template                         = isset($message_templates[$context][$template_field])
1358
+						? $message_templates[$context][$template_field]
1359
+						: null;
1360
+					$template_form_fields[$field_id]['value'] = ! empty($message_templates)
1361
+																&& is_array($message_templates[$context])
1362
+																&& $message_template instanceof EE_Message_Template
1363
+						? $message_template->get('MTP_content')
1364
+						: '';
1365 1365
                     
1366
-                    //do we have a validator error for this field?  if we do then we'll use that value instead
1367
-                    $template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1368
-                        ? $validators[$template_field]['value']
1369
-                        : $template_form_fields[$field_id]['value'];
1366
+					//do we have a validator error for this field?  if we do then we'll use that value instead
1367
+					$template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1368
+						? $validators[$template_field]['value']
1369
+						: $template_form_fields[$field_id]['value'];
1370 1370
                     
1371 1371
                     
1372
-                    $template_form_fields[$field_id]['db-col']    = 'MTP_content';
1373
-                    $css_class                                    = isset($field_setup_array['css_class']) ? $field_setup_array['css_class'] : '';
1374
-                    $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1375
-                                                                    && in_array($template_field, $v_fields)
1376
-                                                                    && isset($validators[$template_field]['msg'])
1377
-                        ? 'validate-error ' . $css_class
1378
-                        : $css_class;
1372
+					$template_form_fields[$field_id]['db-col']    = 'MTP_content';
1373
+					$css_class                                    = isset($field_setup_array['css_class']) ? $field_setup_array['css_class'] : '';
1374
+					$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1375
+																	&& in_array($template_field, $v_fields)
1376
+																	&& isset($validators[$template_field]['msg'])
1377
+						? 'validate-error ' . $css_class
1378
+						: $css_class;
1379 1379
                     
1380
-                    //shortcode selector
1381
-                    $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1382
-                        $template_field, $field_id
1383
-                    );
1384
-                }
1380
+					//shortcode selector
1381
+					$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1382
+						$template_field, $field_id
1383
+					);
1384
+				}
1385 1385
                 
1386
-                //k took care of content field(s) now let's take care of others.
1386
+				//k took care of content field(s) now let's take care of others.
1387 1387
                 
1388
-                $templatefield_MTP_id                = $template_field . '-MTP_ID';
1389
-                $templatefield_field_templatename_id = $template_field . '-name';
1388
+				$templatefield_MTP_id                = $template_field . '-MTP_ID';
1389
+				$templatefield_field_templatename_id = $template_field . '-name';
1390 1390
                 
1391
-                //foreach template field there are actually two form fields created
1392
-                $template_form_fields[$templatefield_MTP_id] = array(
1393
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1394
-                    'label'      => null,
1395
-                    'input'      => 'hidden',
1396
-                    'type'       => 'int',
1397
-                    'required'   => false,
1398
-                    'validation' => true,
1399
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1400
-                    'css_class'  => '',
1401
-                    'format'     => '%d',
1402
-                    'db-col'     => 'MTP_ID'
1403
-                );
1391
+				//foreach template field there are actually two form fields created
1392
+				$template_form_fields[$templatefield_MTP_id] = array(
1393
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1394
+					'label'      => null,
1395
+					'input'      => 'hidden',
1396
+					'type'       => 'int',
1397
+					'required'   => false,
1398
+					'validation' => true,
1399
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1400
+					'css_class'  => '',
1401
+					'format'     => '%d',
1402
+					'db-col'     => 'MTP_ID'
1403
+				);
1404 1404
                 
1405
-                $template_form_fields[$templatefield_field_templatename_id] = array(
1406
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1407
-                    'label'      => null,
1408
-                    'input'      => 'hidden',
1409
-                    'type'       => 'string',
1410
-                    'required'   => false,
1411
-                    'validation' => true,
1412
-                    'value'      => $template_field,
1413
-                    'css_class'  => '',
1414
-                    'format'     => '%s',
1415
-                    'db-col'     => 'MTP_template_field'
1416
-                );
1405
+				$template_form_fields[$templatefield_field_templatename_id] = array(
1406
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1407
+					'label'      => null,
1408
+					'input'      => 'hidden',
1409
+					'type'       => 'string',
1410
+					'required'   => false,
1411
+					'validation' => true,
1412
+					'value'      => $template_field,
1413
+					'css_class'  => '',
1414
+					'format'     => '%s',
1415
+					'db-col'     => 'MTP_template_field'
1416
+				);
1417 1417
                 
1418
-            }
1418
+			}
1419 1419
             
1420
-            //add other fields
1421
-            $template_form_fields['ee-msg-current-context'] = array(
1422
-                'name'       => 'MTP_context',
1423
-                'label'      => null,
1424
-                'input'      => 'hidden',
1425
-                'type'       => 'string',
1426
-                'required'   => false,
1427
-                'validation' => true,
1428
-                'value'      => $context,
1429
-                'css_class'  => '',
1430
-                'format'     => '%s',
1431
-                'db-col'     => 'MTP_context'
1432
-            );
1420
+			//add other fields
1421
+			$template_form_fields['ee-msg-current-context'] = array(
1422
+				'name'       => 'MTP_context',
1423
+				'label'      => null,
1424
+				'input'      => 'hidden',
1425
+				'type'       => 'string',
1426
+				'required'   => false,
1427
+				'validation' => true,
1428
+				'value'      => $context,
1429
+				'css_class'  => '',
1430
+				'format'     => '%s',
1431
+				'db-col'     => 'MTP_context'
1432
+			);
1433 1433
             
1434
-            $template_form_fields['ee-msg-grp-id'] = array(
1435
-                'name'       => 'GRP_ID',
1436
-                'label'      => null,
1437
-                'input'      => 'hidden',
1438
-                'type'       => 'int',
1439
-                'required'   => false,
1440
-                'validation' => true,
1441
-                'value'      => $GRP_ID,
1442
-                'css_class'  => '',
1443
-                'format'     => '%d',
1444
-                'db-col'     => 'GRP_ID'
1445
-            );
1434
+			$template_form_fields['ee-msg-grp-id'] = array(
1435
+				'name'       => 'GRP_ID',
1436
+				'label'      => null,
1437
+				'input'      => 'hidden',
1438
+				'type'       => 'int',
1439
+				'required'   => false,
1440
+				'validation' => true,
1441
+				'value'      => $GRP_ID,
1442
+				'css_class'  => '',
1443
+				'format'     => '%d',
1444
+				'db-col'     => 'GRP_ID'
1445
+			);
1446 1446
             
1447
-            $template_form_fields['ee-msg-messenger'] = array(
1448
-                'name'       => 'MTP_messenger',
1449
-                'label'      => null,
1450
-                'input'      => 'hidden',
1451
-                'type'       => 'string',
1452
-                'required'   => false,
1453
-                'validation' => true,
1454
-                'value'      => $message_template_group->messenger(),
1455
-                'css_class'  => '',
1456
-                'format'     => '%s',
1457
-                'db-col'     => 'MTP_messenger'
1458
-            );
1447
+			$template_form_fields['ee-msg-messenger'] = array(
1448
+				'name'       => 'MTP_messenger',
1449
+				'label'      => null,
1450
+				'input'      => 'hidden',
1451
+				'type'       => 'string',
1452
+				'required'   => false,
1453
+				'validation' => true,
1454
+				'value'      => $message_template_group->messenger(),
1455
+				'css_class'  => '',
1456
+				'format'     => '%s',
1457
+				'db-col'     => 'MTP_messenger'
1458
+			);
1459 1459
             
1460
-            $template_form_fields['ee-msg-message-type'] = array(
1461
-                'name'       => 'MTP_message_type',
1462
-                'label'      => null,
1463
-                'input'      => 'hidden',
1464
-                'type'       => 'string',
1465
-                'required'   => false,
1466
-                'validation' => true,
1467
-                'value'      => $message_template_group->message_type(),
1468
-                'css_class'  => '',
1469
-                'format'     => '%s',
1470
-                'db-col'     => 'MTP_message_type'
1471
-            );
1460
+			$template_form_fields['ee-msg-message-type'] = array(
1461
+				'name'       => 'MTP_message_type',
1462
+				'label'      => null,
1463
+				'input'      => 'hidden',
1464
+				'type'       => 'string',
1465
+				'required'   => false,
1466
+				'validation' => true,
1467
+				'value'      => $message_template_group->message_type(),
1468
+				'css_class'  => '',
1469
+				'format'     => '%s',
1470
+				'db-col'     => 'MTP_message_type'
1471
+			);
1472 1472
             
1473
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1474
-                'name'       => 'MTP_is_global',
1475
-                'label'      => __('Global Template', 'event_espresso'),
1476
-                'input'      => 'hidden',
1477
-                'type'       => 'int',
1478
-                'required'   => false,
1479
-                'validation' => true,
1480
-                'value'      => $message_template_group->get('MTP_is_global'),
1481
-                'css_class'  => '',
1482
-                'format'     => '%d',
1483
-                'db-col'     => 'MTP_is_global'
1484
-            );
1473
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1474
+				'name'       => 'MTP_is_global',
1475
+				'label'      => __('Global Template', 'event_espresso'),
1476
+				'input'      => 'hidden',
1477
+				'type'       => 'int',
1478
+				'required'   => false,
1479
+				'validation' => true,
1480
+				'value'      => $message_template_group->get('MTP_is_global'),
1481
+				'css_class'  => '',
1482
+				'format'     => '%d',
1483
+				'db-col'     => 'MTP_is_global'
1484
+			);
1485 1485
             
1486
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1487
-                'name'       => 'MTP_is_override',
1488
-                'label'      => __('Override all custom', 'event_espresso'),
1489
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1490
-                'type'       => 'int',
1491
-                'required'   => false,
1492
-                'validation' => true,
1493
-                'value'      => $message_template_group->get('MTP_is_override'),
1494
-                'css_class'  => '',
1495
-                'format'     => '%d',
1496
-                'db-col'     => 'MTP_is_override'
1497
-            );
1486
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1487
+				'name'       => 'MTP_is_override',
1488
+				'label'      => __('Override all custom', 'event_espresso'),
1489
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1490
+				'type'       => 'int',
1491
+				'required'   => false,
1492
+				'validation' => true,
1493
+				'value'      => $message_template_group->get('MTP_is_override'),
1494
+				'css_class'  => '',
1495
+				'format'     => '%d',
1496
+				'db-col'     => 'MTP_is_override'
1497
+			);
1498 1498
             
1499
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1500
-                'name'       => 'MTP_is_active',
1501
-                'label'      => __('Active Template', 'event_espresso'),
1502
-                'input'      => 'hidden',
1503
-                'type'       => 'int',
1504
-                'required'   => false,
1505
-                'validation' => true,
1506
-                'value'      => $message_template_group->is_active(),
1507
-                'css_class'  => '',
1508
-                'format'     => '%d',
1509
-                'db-col'     => 'MTP_is_active'
1510
-            );
1499
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1500
+				'name'       => 'MTP_is_active',
1501
+				'label'      => __('Active Template', 'event_espresso'),
1502
+				'input'      => 'hidden',
1503
+				'type'       => 'int',
1504
+				'required'   => false,
1505
+				'validation' => true,
1506
+				'value'      => $message_template_group->is_active(),
1507
+				'css_class'  => '',
1508
+				'format'     => '%d',
1509
+				'db-col'     => 'MTP_is_active'
1510
+			);
1511 1511
             
1512
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1513
-                'name'       => 'MTP_deleted',
1514
-                'label'      => null,
1515
-                'input'      => 'hidden',
1516
-                'type'       => 'int',
1517
-                'required'   => false,
1518
-                'validation' => true,
1519
-                'value'      => $message_template_group->get('MTP_deleted'),
1520
-                'css_class'  => '',
1521
-                'format'     => '%d',
1522
-                'db-col'     => 'MTP_deleted'
1523
-            );
1524
-            $sidebar_form_fields['ee-msg-author']  = array(
1525
-                'name'       => 'MTP_user_id',
1526
-                'label'      => __('Author', 'event_espresso'),
1527
-                'input'      => 'hidden',
1528
-                'type'       => 'int',
1529
-                'required'   => false,
1530
-                'validation' => false,
1531
-                'value'      => $message_template_group->user(),
1532
-                'format'     => '%d',
1533
-                'db-col'     => 'MTP_user_id'
1534
-            );
1512
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1513
+				'name'       => 'MTP_deleted',
1514
+				'label'      => null,
1515
+				'input'      => 'hidden',
1516
+				'type'       => 'int',
1517
+				'required'   => false,
1518
+				'validation' => true,
1519
+				'value'      => $message_template_group->get('MTP_deleted'),
1520
+				'css_class'  => '',
1521
+				'format'     => '%d',
1522
+				'db-col'     => 'MTP_deleted'
1523
+			);
1524
+			$sidebar_form_fields['ee-msg-author']  = array(
1525
+				'name'       => 'MTP_user_id',
1526
+				'label'      => __('Author', 'event_espresso'),
1527
+				'input'      => 'hidden',
1528
+				'type'       => 'int',
1529
+				'required'   => false,
1530
+				'validation' => false,
1531
+				'value'      => $message_template_group->user(),
1532
+				'format'     => '%d',
1533
+				'db-col'     => 'MTP_user_id'
1534
+			);
1535 1535
             
1536
-            $sidebar_form_fields['ee-msg-route'] = array(
1537
-                'name'  => 'action',
1538
-                'input' => 'hidden',
1539
-                'type'  => 'string',
1540
-                'value' => $action
1541
-            );
1536
+			$sidebar_form_fields['ee-msg-route'] = array(
1537
+				'name'  => 'action',
1538
+				'input' => 'hidden',
1539
+				'type'  => 'string',
1540
+				'value' => $action
1541
+			);
1542 1542
             
1543
-            $sidebar_form_fields['ee-msg-id']        = array(
1544
-                'name'  => 'id',
1545
-                'input' => 'hidden',
1546
-                'type'  => 'int',
1547
-                'value' => $GRP_ID
1548
-            );
1549
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1550
-                'name'  => $action . '_nonce',
1551
-                'input' => 'hidden',
1552
-                'type'  => 'string',
1553
-                'value' => wp_create_nonce($action . '_nonce')
1554
-            );
1543
+			$sidebar_form_fields['ee-msg-id']        = array(
1544
+				'name'  => 'id',
1545
+				'input' => 'hidden',
1546
+				'type'  => 'int',
1547
+				'value' => $GRP_ID
1548
+			);
1549
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1550
+				'name'  => $action . '_nonce',
1551
+				'input' => 'hidden',
1552
+				'type'  => 'string',
1553
+				'value' => wp_create_nonce($action . '_nonce')
1554
+			);
1555 1555
             
1556
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1557
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1558
-                    'name'  => 'template_switch',
1559
-                    'input' => 'hidden',
1560
-                    'type'  => 'int',
1561
-                    'value' => 1
1562
-                );
1563
-            }
1556
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1557
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1558
+					'name'  => 'template_switch',
1559
+					'input' => 'hidden',
1560
+					'type'  => 'int',
1561
+					'value' => 1
1562
+				);
1563
+			}
1564 1564
             
1565 1565
             
1566
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1567
-            $sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1566
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1567
+			$sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1568 1568
             
1569 1569
             
1570
-        } //end if ( !empty($template_field_structure) )
1570
+		} //end if ( !empty($template_field_structure) )
1571 1571
         
1572
-        //set extra content for publish box
1573
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1574
-        $this->_set_publish_post_box_vars(
1575
-            'id',
1576
-            $GRP_ID,
1577
-            false,
1578
-            add_query_arg(
1579
-                array('action' => 'global_mtps'),
1580
-                $this->_admin_base_url
1581
-            )
1582
-        );
1583
-        
1584
-        //add preview button
1585
-        $preview_url    = parent::add_query_args_and_nonce(
1586
-            array(
1587
-                'message_type' => $message_template_group->message_type(),
1588
-                'messenger'    => $message_template_group->messenger(),
1589
-                'context'      => $context,
1590
-                'GRP_ID'       => $GRP_ID,
1591
-                'action'       => 'preview_message'
1592
-            ),
1593
-            $this->_admin_base_url
1594
-        );
1595
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1596
-                'event_espresso') . '</a>';
1597
-        
1598
-        
1599
-        //setup context switcher
1600
-        $context_switcher_args = array(
1601
-            'page'    => 'espresso_messages',
1602
-            'action'  => 'edit_message_template',
1603
-            'id'      => $GRP_ID,
1604
-            'context' => $context,
1605
-            'extra'   => $preview_button
1606
-        );
1607
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1608
-        
1609
-        
1610
-        //main box
1611
-        $this->_template_args['template_fields']                         = $template_fields;
1612
-        $this->_template_args['sidebar_box_id']                          = 'details';
1613
-        $this->_template_args['action']                                  = $action;
1614
-        $this->_template_args['context']                                 = $context;
1615
-        $this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1616
-        $this->_template_args['learn_more_about_message_templates_link'] = $this->_learn_more_about_message_templates_link();
1617
-        
1618
-        
1619
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1620
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1621
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1622
-        
1623
-        $this->_template_path = $this->_template_args['GRP_ID']
1624
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1625
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1626
-        
1627
-        //send along EE_Message_Template_Group object for further template use.
1628
-        $this->_template_args['MTP'] = $message_template_group;
1629
-        
1630
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
1631
-            $this->_template_args, true);
1632
-        
1633
-        
1634
-        //finally, let's set the admin_page title
1635
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1636
-        
1637
-        
1638
-        //we need to take care of setting the shortcodes property for use elsewhere.
1639
-        $this->_set_shortcodes();
1640
-        
1641
-        
1642
-        //final template wrapper
1643
-        $this->display_admin_page_with_sidebar();
1644
-    }
1645
-    
1646
-    
1647
-    public function filter_tinymce_init($mceInit, $editor_id)
1648
-    {
1649
-        return $mceInit;
1650
-    }
1651
-    
1652
-    
1653
-    public function add_context_switcher()
1654
-    {
1655
-        return $this->_context_switcher;
1656
-    }
1657
-    
1658
-    public function _add_form_element_before()
1659
-    {
1660
-        return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1661
-    }
1662
-    
1663
-    public function _add_form_element_after()
1664
-    {
1665
-        return '</form>';
1666
-    }
1667
-    
1668
-    
1669
-    /**
1670
-     * This executes switching the template pack for a message template.
1671
-     *
1672
-     * @since 4.5.0
1673
-     *
1674
-     */
1675
-    public function switch_template_pack()
1676
-    {
1677
-        $GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1678
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1679
-        
1680
-        //verify we have needed values.
1681
-        if (empty($GRP_ID) || empty($template_pack)) {
1682
-            $this->_template_args['error'] = true;
1683
-            EE_Error::add_error(__('The required date for switching templates is not available.', 'event_espresso'),
1684
-                __FILE__, __FUNCTION__, __LINE__);
1685
-        } else {
1686
-            //get template, set the new template_pack and then reset to default
1687
-            /** @type EE_Message_Template_Group $message_template_group */
1688
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1572
+		//set extra content for publish box
1573
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1574
+		$this->_set_publish_post_box_vars(
1575
+			'id',
1576
+			$GRP_ID,
1577
+			false,
1578
+			add_query_arg(
1579
+				array('action' => 'global_mtps'),
1580
+				$this->_admin_base_url
1581
+			)
1582
+		);
1583
+        
1584
+		//add preview button
1585
+		$preview_url    = parent::add_query_args_and_nonce(
1586
+			array(
1587
+				'message_type' => $message_template_group->message_type(),
1588
+				'messenger'    => $message_template_group->messenger(),
1589
+				'context'      => $context,
1590
+				'GRP_ID'       => $GRP_ID,
1591
+				'action'       => 'preview_message'
1592
+			),
1593
+			$this->_admin_base_url
1594
+		);
1595
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1596
+				'event_espresso') . '</a>';
1597
+        
1598
+        
1599
+		//setup context switcher
1600
+		$context_switcher_args = array(
1601
+			'page'    => 'espresso_messages',
1602
+			'action'  => 'edit_message_template',
1603
+			'id'      => $GRP_ID,
1604
+			'context' => $context,
1605
+			'extra'   => $preview_button
1606
+		);
1607
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1608
+        
1609
+        
1610
+		//main box
1611
+		$this->_template_args['template_fields']                         = $template_fields;
1612
+		$this->_template_args['sidebar_box_id']                          = 'details';
1613
+		$this->_template_args['action']                                  = $action;
1614
+		$this->_template_args['context']                                 = $context;
1615
+		$this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1616
+		$this->_template_args['learn_more_about_message_templates_link'] = $this->_learn_more_about_message_templates_link();
1617
+        
1618
+        
1619
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1620
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1621
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1622
+        
1623
+		$this->_template_path = $this->_template_args['GRP_ID']
1624
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1625
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1626
+        
1627
+		//send along EE_Message_Template_Group object for further template use.
1628
+		$this->_template_args['MTP'] = $message_template_group;
1629
+        
1630
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
1631
+			$this->_template_args, true);
1632
+        
1633
+        
1634
+		//finally, let's set the admin_page title
1635
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1636
+        
1637
+        
1638
+		//we need to take care of setting the shortcodes property for use elsewhere.
1639
+		$this->_set_shortcodes();
1640
+        
1641
+        
1642
+		//final template wrapper
1643
+		$this->display_admin_page_with_sidebar();
1644
+	}
1645
+    
1646
+    
1647
+	public function filter_tinymce_init($mceInit, $editor_id)
1648
+	{
1649
+		return $mceInit;
1650
+	}
1651
+    
1652
+    
1653
+	public function add_context_switcher()
1654
+	{
1655
+		return $this->_context_switcher;
1656
+	}
1657
+    
1658
+	public function _add_form_element_before()
1659
+	{
1660
+		return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1661
+	}
1662
+    
1663
+	public function _add_form_element_after()
1664
+	{
1665
+		return '</form>';
1666
+	}
1667
+    
1668
+    
1669
+	/**
1670
+	 * This executes switching the template pack for a message template.
1671
+	 *
1672
+	 * @since 4.5.0
1673
+	 *
1674
+	 */
1675
+	public function switch_template_pack()
1676
+	{
1677
+		$GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1678
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1679
+        
1680
+		//verify we have needed values.
1681
+		if (empty($GRP_ID) || empty($template_pack)) {
1682
+			$this->_template_args['error'] = true;
1683
+			EE_Error::add_error(__('The required date for switching templates is not available.', 'event_espresso'),
1684
+				__FILE__, __FUNCTION__, __LINE__);
1685
+		} else {
1686
+			//get template, set the new template_pack and then reset to default
1687
+			/** @type EE_Message_Template_Group $message_template_group */
1688
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1689 1689
             
1690
-            $message_template_group->set_template_pack_name($template_pack);
1691
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1692
-            $this->_req_data['mt']   = $message_template_group->message_type();
1690
+			$message_template_group->set_template_pack_name($template_pack);
1691
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1692
+			$this->_req_data['mt']   = $message_template_group->message_type();
1693 1693
             
1694
-            $query_args = $this->_reset_to_default_template();
1694
+			$query_args = $this->_reset_to_default_template();
1695 1695
             
1696
-            if (empty($query_args['id'])) {
1697
-                EE_Error::add_error(
1698
-                    __(
1699
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1700
-                        'event_espresso'
1701
-                    ),
1702
-                    __FILE__, __FUNCTION__, __LINE__
1703
-                );
1704
-                $this->_template_args['error'] = true;
1705
-            } else {
1706
-                $template_label       = $message_template_group->get_template_pack()->label;
1707
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1708
-                EE_Error::add_success(
1709
-                    sprintf(
1710
-                        __(
1711
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1712
-                            'event_espresso'
1713
-                        ),
1714
-                        $template_label,
1715
-                        $template_pack_labels->template_pack
1716
-                    )
1717
-                );
1718
-                //generate the redirect url for js.
1719
-                $url                                          = self::add_query_args_and_nonce($query_args,
1720
-                    $this->_admin_base_url);
1721
-                $this->_template_args['data']['redirect_url'] = $url;
1722
-                $this->_template_args['success']              = true;
1723
-            }
1696
+			if (empty($query_args['id'])) {
1697
+				EE_Error::add_error(
1698
+					__(
1699
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1700
+						'event_espresso'
1701
+					),
1702
+					__FILE__, __FUNCTION__, __LINE__
1703
+				);
1704
+				$this->_template_args['error'] = true;
1705
+			} else {
1706
+				$template_label       = $message_template_group->get_template_pack()->label;
1707
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1708
+				EE_Error::add_success(
1709
+					sprintf(
1710
+						__(
1711
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1712
+							'event_espresso'
1713
+						),
1714
+						$template_label,
1715
+						$template_pack_labels->template_pack
1716
+					)
1717
+				);
1718
+				//generate the redirect url for js.
1719
+				$url                                          = self::add_query_args_and_nonce($query_args,
1720
+					$this->_admin_base_url);
1721
+				$this->_template_args['data']['redirect_url'] = $url;
1722
+				$this->_template_args['success']              = true;
1723
+			}
1724 1724
             
1725
-            $this->_return_json();
1725
+			$this->_return_json();
1726 1726
             
1727
-        }
1728
-    }
1729
-    
1730
-    
1731
-    /**
1732
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1733
-     * they want.
1734
-     *
1735
-     * @access protected
1736
-     * @return array|null
1737
-     */
1738
-    protected function _reset_to_default_template()
1739
-    {
1740
-        
1741
-        $templates = array();
1742
-        $GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1743
-        //we need to make sure we've got the info we need.
1744
-        if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
1745
-            EE_Error::add_error(
1746
-                __(
1747
-                    'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
1748
-                    'event_espresso'
1749
-                ),
1750
-                __FILE__, __FUNCTION__, __LINE__
1751
-            );
1752
-        }
1753
-        
1754
-        // all templates will be reset to whatever the defaults are
1755
-        // for the global template matching the messenger and message type.
1756
-        $success = ! empty($GRP_ID) ? true : false;
1757
-        
1758
-        if ($success) {
1727
+		}
1728
+	}
1729
+    
1730
+    
1731
+	/**
1732
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1733
+	 * they want.
1734
+	 *
1735
+	 * @access protected
1736
+	 * @return array|null
1737
+	 */
1738
+	protected function _reset_to_default_template()
1739
+	{
1740
+        
1741
+		$templates = array();
1742
+		$GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1743
+		//we need to make sure we've got the info we need.
1744
+		if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
1745
+			EE_Error::add_error(
1746
+				__(
1747
+					'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
1748
+					'event_espresso'
1749
+				),
1750
+				__FILE__, __FUNCTION__, __LINE__
1751
+			);
1752
+		}
1753
+        
1754
+		// all templates will be reset to whatever the defaults are
1755
+		// for the global template matching the messenger and message type.
1756
+		$success = ! empty($GRP_ID) ? true : false;
1757
+        
1758
+		if ($success) {
1759 1759
             
1760
-            //let's first determine if the incoming template is a global template,
1761
-            // if it isn't then we need to get the global template matching messenger and message type.
1762
-            //$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1760
+			//let's first determine if the incoming template is a global template,
1761
+			// if it isn't then we need to get the global template matching messenger and message type.
1762
+			//$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1763 1763
             
1764 1764
             
1765
-            //note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
1766
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
1765
+			//note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
1766
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
1767 1767
             
1768
-            if ($success) {
1769
-                // if successfully deleted, lets generate the new ones.
1770
-                // Note. We set GLOBAL to true, because resets on ANY template
1771
-                // will use the related global template defaults for regeneration.
1772
-                // This means that if a custom template is reset it resets to whatever the related global template is.
1773
-                // HOWEVER, we DO keep the template pack and template variation set
1774
-                // for the current custom template when resetting.
1775
-                $templates = $this->_generate_new_templates(
1776
-                    $this->_req_data['msgr'],
1777
-                    $this->_req_data['mt'],
1778
-                    $GRP_ID,
1779
-                    true
1780
-                );
1781
-            }
1768
+			if ($success) {
1769
+				// if successfully deleted, lets generate the new ones.
1770
+				// Note. We set GLOBAL to true, because resets on ANY template
1771
+				// will use the related global template defaults for regeneration.
1772
+				// This means that if a custom template is reset it resets to whatever the related global template is.
1773
+				// HOWEVER, we DO keep the template pack and template variation set
1774
+				// for the current custom template when resetting.
1775
+				$templates = $this->_generate_new_templates(
1776
+					$this->_req_data['msgr'],
1777
+					$this->_req_data['mt'],
1778
+					$GRP_ID,
1779
+					true
1780
+				);
1781
+			}
1782 1782
             
1783
-        }
1784
-        
1785
-        //any error messages?
1786
-        if ( ! $success) {
1787
-            EE_Error::add_error(
1788
-                __('Something went wrong with deleting existing templates. Unable to reset to default',
1789
-                    'event_espresso'),
1790
-                __FILE__, __FUNCTION__, __LINE__
1791
-            );
1792
-        }
1793
-        
1794
-        //all good, let's add a success message!
1795
-        if ($success && ! empty($templates)) {
1796
-            $templates = $templates[0]; //the info for the template we generated is the first element in the returned array.
1797
-            EE_Error::overwrite_success();
1798
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
1799
-        }
1800
-        
1801
-        
1802
-        $query_args = array(
1803
-            'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
1804
-            'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
1805
-            'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
1806
-        );
1807
-        
1808
-        //if called via ajax then we return query args otherwise redirect
1809
-        if (defined('DOING_AJAX') && DOING_AJAX) {
1810
-            return $query_args;
1811
-        } else {
1812
-            $this->_redirect_after_action(false, '', '', $query_args, true);
1783
+		}
1784
+        
1785
+		//any error messages?
1786
+		if ( ! $success) {
1787
+			EE_Error::add_error(
1788
+				__('Something went wrong with deleting existing templates. Unable to reset to default',
1789
+					'event_espresso'),
1790
+				__FILE__, __FUNCTION__, __LINE__
1791
+			);
1792
+		}
1793
+        
1794
+		//all good, let's add a success message!
1795
+		if ($success && ! empty($templates)) {
1796
+			$templates = $templates[0]; //the info for the template we generated is the first element in the returned array.
1797
+			EE_Error::overwrite_success();
1798
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
1799
+		}
1800
+        
1801
+        
1802
+		$query_args = array(
1803
+			'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
1804
+			'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
1805
+			'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
1806
+		);
1807
+        
1808
+		//if called via ajax then we return query args otherwise redirect
1809
+		if (defined('DOING_AJAX') && DOING_AJAX) {
1810
+			return $query_args;
1811
+		} else {
1812
+			$this->_redirect_after_action(false, '', '', $query_args, true);
1813 1813
             
1814
-            return null;
1815
-        }
1816
-    }
1817
-    
1818
-    
1819
-    /**
1820
-     * Retrieve and set the message preview for display.
1821
-     *
1822
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
1823
-     *
1824
-     * @return string
1825
-     */
1826
-    public function _preview_message($send = false)
1827
-    {
1828
-        //first make sure we've got the necessary parameters
1829
-        if (
1830
-        ! isset(
1831
-            $this->_req_data['message_type'],
1832
-            $this->_req_data['messenger'],
1833
-            $this->_req_data['messenger'],
1834
-            $this->_req_data['GRP_ID']
1835
-        )
1836
-        ) {
1837
-            EE_Error::add_error(
1838
-                __('Missing necessary parameters for displaying preview', 'event_espresso'),
1839
-                __FILE__, __FUNCTION__, __LINE__
1840
-            );
1841
-        }
1842
-        
1843
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
1844
-        
1845
-        
1846
-        //get the preview!
1847
-        $preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
1848
-            $this->_req_data['messenger'], $send);
1849
-        
1850
-        if ($send) {
1851
-            return $preview;
1852
-        }
1853
-        
1854
-        //let's add a button to go back to the edit view
1855
-        $query_args             = array(
1856
-            'id'      => $this->_req_data['GRP_ID'],
1857
-            'context' => $this->_req_data['context'],
1858
-            'action'  => 'edit_message_template'
1859
-        );
1860
-        $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1861
-        $preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1862
-                'event_espresso') . '</a>';
1863
-        $message_types          = $this->get_installed_message_types();
1864
-        $active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1865
-        $active_messenger_label = $active_messenger instanceof EE_messenger
1866
-            ? ucwords($active_messenger->label['singular'])
1867
-            : esc_html__('Unknown Messenger', 'event_espresso');
1868
-        //let's provide a helpful title for context
1869
-        $preview_title = sprintf(
1870
-            __('Viewing Preview for %s %s Message Template', 'event_espresso'),
1871
-            $active_messenger_label,
1872
-            ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
1873
-        );
1874
-        //setup display of preview.
1875
-        $this->_admin_page_title                    = $preview_title;
1876
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1877
-        $this->_template_args['data']['force_json'] = true;
1878
-        
1879
-        return '';
1880
-    }
1881
-    
1882
-    
1883
-    /**
1884
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
1885
-     * gets called automatically.
1886
-     *
1887
-     * @since 4.5.0
1888
-     *
1889
-     * @return string
1890
-     */
1891
-    protected function _display_preview_message()
1892
-    {
1893
-        $this->display_admin_page_with_no_sidebar();
1894
-    }
1895
-    
1896
-    
1897
-    /**
1898
-     * registers metaboxes that should show up on the "edit_message_template" page
1899
-     *
1900
-     * @access protected
1901
-     * @return void
1902
-     */
1903
-    protected function _register_edit_meta_boxes()
1904
-    {
1905
-        add_meta_box('mtp_valid_shortcodes', __('Valid Shortcodes', 'event_espresso'),
1906
-            array($this, 'shortcode_meta_box'), $this->_current_screen->id, 'side', 'default');
1907
-        add_meta_box('mtp_extra_actions', __('Extra Actions', 'event_espresso'), array($this, 'extra_actions_meta_box'),
1908
-            $this->_current_screen->id, 'side', 'high');
1909
-        add_meta_box('mtp_templates', __('Template Styles', 'event_espresso'), array($this, 'template_pack_meta_box'),
1910
-            $this->_current_screen->id, 'side', 'high');
1911
-    }
1912
-    
1913
-    
1914
-    /**
1915
-     * metabox content for all template pack and variation selection.
1916
-     *
1917
-     * @since 4.5.0
1918
-     *
1919
-     * @return string
1920
-     */
1921
-    public function template_pack_meta_box()
1922
-    {
1923
-        $this->_set_message_template_group();
1924
-        
1925
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
1926
-        
1927
-        $tp_select_values = array();
1928
-        
1929
-        foreach ($tp_collection as $tp) {
1930
-            //only include template packs that support this messenger and message type!
1931
-            $supports = $tp->get_supports();
1932
-            if (
1933
-                ! isset($supports[$this->_message_template_group->messenger()])
1934
-                || ! in_array(
1935
-                    $this->_message_template_group->message_type(),
1936
-                    $supports[$this->_message_template_group->messenger()]
1937
-                )
1938
-            ) {
1939
-                //not supported
1940
-                continue;
1941
-            }
1814
+			return null;
1815
+		}
1816
+	}
1817
+    
1818
+    
1819
+	/**
1820
+	 * Retrieve and set the message preview for display.
1821
+	 *
1822
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
1823
+	 *
1824
+	 * @return string
1825
+	 */
1826
+	public function _preview_message($send = false)
1827
+	{
1828
+		//first make sure we've got the necessary parameters
1829
+		if (
1830
+		! isset(
1831
+			$this->_req_data['message_type'],
1832
+			$this->_req_data['messenger'],
1833
+			$this->_req_data['messenger'],
1834
+			$this->_req_data['GRP_ID']
1835
+		)
1836
+		) {
1837
+			EE_Error::add_error(
1838
+				__('Missing necessary parameters for displaying preview', 'event_espresso'),
1839
+				__FILE__, __FUNCTION__, __LINE__
1840
+			);
1841
+		}
1842
+        
1843
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
1844
+        
1845
+        
1846
+		//get the preview!
1847
+		$preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
1848
+			$this->_req_data['messenger'], $send);
1849
+        
1850
+		if ($send) {
1851
+			return $preview;
1852
+		}
1853
+        
1854
+		//let's add a button to go back to the edit view
1855
+		$query_args             = array(
1856
+			'id'      => $this->_req_data['GRP_ID'],
1857
+			'context' => $this->_req_data['context'],
1858
+			'action'  => 'edit_message_template'
1859
+		);
1860
+		$go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1861
+		$preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1862
+				'event_espresso') . '</a>';
1863
+		$message_types          = $this->get_installed_message_types();
1864
+		$active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1865
+		$active_messenger_label = $active_messenger instanceof EE_messenger
1866
+			? ucwords($active_messenger->label['singular'])
1867
+			: esc_html__('Unknown Messenger', 'event_espresso');
1868
+		//let's provide a helpful title for context
1869
+		$preview_title = sprintf(
1870
+			__('Viewing Preview for %s %s Message Template', 'event_espresso'),
1871
+			$active_messenger_label,
1872
+			ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
1873
+		);
1874
+		//setup display of preview.
1875
+		$this->_admin_page_title                    = $preview_title;
1876
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1877
+		$this->_template_args['data']['force_json'] = true;
1878
+        
1879
+		return '';
1880
+	}
1881
+    
1882
+    
1883
+	/**
1884
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
1885
+	 * gets called automatically.
1886
+	 *
1887
+	 * @since 4.5.0
1888
+	 *
1889
+	 * @return string
1890
+	 */
1891
+	protected function _display_preview_message()
1892
+	{
1893
+		$this->display_admin_page_with_no_sidebar();
1894
+	}
1895
+    
1896
+    
1897
+	/**
1898
+	 * registers metaboxes that should show up on the "edit_message_template" page
1899
+	 *
1900
+	 * @access protected
1901
+	 * @return void
1902
+	 */
1903
+	protected function _register_edit_meta_boxes()
1904
+	{
1905
+		add_meta_box('mtp_valid_shortcodes', __('Valid Shortcodes', 'event_espresso'),
1906
+			array($this, 'shortcode_meta_box'), $this->_current_screen->id, 'side', 'default');
1907
+		add_meta_box('mtp_extra_actions', __('Extra Actions', 'event_espresso'), array($this, 'extra_actions_meta_box'),
1908
+			$this->_current_screen->id, 'side', 'high');
1909
+		add_meta_box('mtp_templates', __('Template Styles', 'event_espresso'), array($this, 'template_pack_meta_box'),
1910
+			$this->_current_screen->id, 'side', 'high');
1911
+	}
1912
+    
1913
+    
1914
+	/**
1915
+	 * metabox content for all template pack and variation selection.
1916
+	 *
1917
+	 * @since 4.5.0
1918
+	 *
1919
+	 * @return string
1920
+	 */
1921
+	public function template_pack_meta_box()
1922
+	{
1923
+		$this->_set_message_template_group();
1924
+        
1925
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
1926
+        
1927
+		$tp_select_values = array();
1928
+        
1929
+		foreach ($tp_collection as $tp) {
1930
+			//only include template packs that support this messenger and message type!
1931
+			$supports = $tp->get_supports();
1932
+			if (
1933
+				! isset($supports[$this->_message_template_group->messenger()])
1934
+				|| ! in_array(
1935
+					$this->_message_template_group->message_type(),
1936
+					$supports[$this->_message_template_group->messenger()]
1937
+				)
1938
+			) {
1939
+				//not supported
1940
+				continue;
1941
+			}
1942 1942
             
1943
-            $tp_select_values[] = array(
1944
-                'text' => $tp->label,
1945
-                'id'   => $tp->dbref
1946
-            );
1947
-        }
1948
-        
1949
-        //if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by the default template pack.  This still allows for the odd template pack to override.
1950
-        if (empty($tp_select_values)) {
1951
-            $tp_select_values[] = array(
1952
-                'text' => __('Default', 'event_espresso'),
1953
-                'id'   => 'default'
1954
-            );
1955
-        }
1956
-        
1957
-        //setup variation select values for the currently selected template.
1958
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
1959
-            $this->_message_template_group->messenger(),
1960
-            $this->_message_template_group->message_type()
1961
-        );
1962
-        $variations_select_values = array();
1963
-        foreach ($variations as $variation => $label) {
1964
-            $variations_select_values[] = array(
1965
-                'text' => $label,
1966
-                'id'   => $variation
1967
-            );
1968
-        }
1969
-        
1970
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1971
-        
1972
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1973
-            'MTP_template_pack',
1974
-            $tp_select_values,
1975
-            $this->_message_template_group->get_template_pack_name()
1976
-        );
1977
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
1978
-            'MTP_template_variation',
1979
-            $variations_select_values,
1980
-            $this->_message_template_group->get_template_pack_variation()
1981
-        );
1982
-        $template_args['template_pack_label']            = $template_pack_labels->template_pack;
1983
-        $template_args['template_variation_label']       = $template_pack_labels->template_variation;
1984
-        $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1985
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1986
-        
1987
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1988
-        
1989
-        EEH_Template::display_template($template, $template_args);
1990
-    }
1991
-    
1992
-    
1993
-    /**
1994
-     * This meta box holds any extra actions related to Message Templates
1995
-     * For now, this includes Resetting templates to defaults and sending a test email.
1996
-     *
1997
-     * @access  public
1998
-     * @return void
1999
-     * @throws \EE_Error
2000
-     */
2001
-    public function extra_actions_meta_box()
2002
-    {
2003
-        $template_form_fields = array();
2004
-        
2005
-        $extra_args = array(
2006
-            'msgr'   => $this->_message_template_group->messenger(),
2007
-            'mt'     => $this->_message_template_group->message_type(),
2008
-            'GRP_ID' => $this->_message_template_group->GRP_ID()
2009
-        );
2010
-        //first we need to see if there are any fields
2011
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2012
-        
2013
-        if ( ! empty($fields)) {
2014
-            //yup there be fields
2015
-            foreach ($fields as $field => $config) {
2016
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2017
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2018
-                $default  = isset($config['default']) ? $config['default'] : '';
2019
-                $default  = isset($config['value']) ? $config['value'] : $default;
1943
+			$tp_select_values[] = array(
1944
+				'text' => $tp->label,
1945
+				'id'   => $tp->dbref
1946
+			);
1947
+		}
1948
+        
1949
+		//if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by the default template pack.  This still allows for the odd template pack to override.
1950
+		if (empty($tp_select_values)) {
1951
+			$tp_select_values[] = array(
1952
+				'text' => __('Default', 'event_espresso'),
1953
+				'id'   => 'default'
1954
+			);
1955
+		}
1956
+        
1957
+		//setup variation select values for the currently selected template.
1958
+		$variations               = $this->_message_template_group->get_template_pack()->get_variations(
1959
+			$this->_message_template_group->messenger(),
1960
+			$this->_message_template_group->message_type()
1961
+		);
1962
+		$variations_select_values = array();
1963
+		foreach ($variations as $variation => $label) {
1964
+			$variations_select_values[] = array(
1965
+				'text' => $label,
1966
+				'id'   => $variation
1967
+			);
1968
+		}
1969
+        
1970
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1971
+        
1972
+		$template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1973
+			'MTP_template_pack',
1974
+			$tp_select_values,
1975
+			$this->_message_template_group->get_template_pack_name()
1976
+		);
1977
+		$template_args['variations_selector']            = EEH_Form_Fields::select_input(
1978
+			'MTP_template_variation',
1979
+			$variations_select_values,
1980
+			$this->_message_template_group->get_template_pack_variation()
1981
+		);
1982
+		$template_args['template_pack_label']            = $template_pack_labels->template_pack;
1983
+		$template_args['template_variation_label']       = $template_pack_labels->template_variation;
1984
+		$template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1985
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1986
+        
1987
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1988
+        
1989
+		EEH_Template::display_template($template, $template_args);
1990
+	}
1991
+    
1992
+    
1993
+	/**
1994
+	 * This meta box holds any extra actions related to Message Templates
1995
+	 * For now, this includes Resetting templates to defaults and sending a test email.
1996
+	 *
1997
+	 * @access  public
1998
+	 * @return void
1999
+	 * @throws \EE_Error
2000
+	 */
2001
+	public function extra_actions_meta_box()
2002
+	{
2003
+		$template_form_fields = array();
2004
+        
2005
+		$extra_args = array(
2006
+			'msgr'   => $this->_message_template_group->messenger(),
2007
+			'mt'     => $this->_message_template_group->message_type(),
2008
+			'GRP_ID' => $this->_message_template_group->GRP_ID()
2009
+		);
2010
+		//first we need to see if there are any fields
2011
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2012
+        
2013
+		if ( ! empty($fields)) {
2014
+			//yup there be fields
2015
+			foreach ($fields as $field => $config) {
2016
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2017
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2018
+				$default  = isset($config['default']) ? $config['default'] : '';
2019
+				$default  = isset($config['value']) ? $config['value'] : $default;
2020 2020
                 
2021
-                // if type is hidden and the value is empty
2022
-                // something may have gone wrong so let's correct with the defaults
2023
-                $fix              = $config['input'] === 'hidden' && isset($existing[$field]) && empty($existing[$field])
2024
-                    ? $default
2025
-                    : '';
2026
-                $existing[$field] = isset($existing[$field]) && empty($fix)
2027
-                    ? $existing[$field]
2028
-                    : $fix;
2021
+				// if type is hidden and the value is empty
2022
+				// something may have gone wrong so let's correct with the defaults
2023
+				$fix              = $config['input'] === 'hidden' && isset($existing[$field]) && empty($existing[$field])
2024
+					? $default
2025
+					: '';
2026
+				$existing[$field] = isset($existing[$field]) && empty($fix)
2027
+					? $existing[$field]
2028
+					: $fix;
2029 2029
                 
2030
-                $template_form_fields[$field_id] = array(
2031
-                    'name'       => 'test_settings_fld[' . $field . ']',
2032
-                    'label'      => $config['label'],
2033
-                    'input'      => $config['input'],
2034
-                    'type'       => $config['type'],
2035
-                    'required'   => $config['required'],
2036
-                    'validation' => $config['validation'],
2037
-                    'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2038
-                    'css_class'  => $config['css_class'],
2039
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2040
-                    'default'    => $default,
2041
-                    'format'     => $config['format']
2042
-                );
2043
-            }
2044
-        }
2045
-        
2046
-        $test_settings_fields = ! empty($template_form_fields)
2047
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2048
-            : '';
2049
-        
2050
-        $test_settings_html = '';
2051
-        //print out $test_settings_fields
2052
-        if ( ! empty($test_settings_fields)) {
2053
-            echo $test_settings_fields;
2054
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2055
-            $test_settings_html .= 'name="test_button" value="';
2056
-            $test_settings_html .= __('Test Send', 'event_espresso');
2057
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2058
-        }
2059
-        
2060
-        //and button
2061
-        $test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2062
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2063
-        $test_settings_html .= $this->get_action_link_or_button(
2064
-            'reset_to_default',
2065
-            'reset',
2066
-            $extra_args,
2067
-            'button-primary reset-default-button'
2068
-        );
2069
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2070
-        echo $test_settings_html;
2071
-    }
2072
-    
2073
-    
2074
-    /**
2075
-     * This returns the shortcode selector skeleton for a given context and field.
2076
-     *
2077
-     * @since 4.9.rc.000
2078
-     *
2079
-     * @param string $field           The name of the field retrieving shortcodes for.
2080
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2081
-     *
2082
-     * @return string
2083
-     */
2084
-    protected function _get_shortcode_selector($field, $linked_input_id)
2085
-    {
2086
-        $template_args = array(
2087
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2088
-            'fieldname'       => $field,
2089
-            'linked_input_id' => $linked_input_id
2090
-        );
2091
-        
2092
-        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2093
-            $template_args, true);
2094
-    }
2095
-    
2096
-    
2097
-    /**
2098
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2099
-     * page)
2100
-     *
2101
-     * @access public
2102
-     * @return void
2103
-     */
2104
-    public function shortcode_meta_box()
2105
-    {
2106
-        $shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2107
-        //$messenger = $this->_message_template_group->messenger_obj();
2108
-        //now let's set the content depending on the status of the shortcodes array
2109
-        if (empty($shortcodes)) {
2110
-            $content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2111
-            echo $content;
2112
-        } else {
2113
-            //$alt = 0;
2114
-            ?>
2030
+				$template_form_fields[$field_id] = array(
2031
+					'name'       => 'test_settings_fld[' . $field . ']',
2032
+					'label'      => $config['label'],
2033
+					'input'      => $config['input'],
2034
+					'type'       => $config['type'],
2035
+					'required'   => $config['required'],
2036
+					'validation' => $config['validation'],
2037
+					'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2038
+					'css_class'  => $config['css_class'],
2039
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2040
+					'default'    => $default,
2041
+					'format'     => $config['format']
2042
+				);
2043
+			}
2044
+		}
2045
+        
2046
+		$test_settings_fields = ! empty($template_form_fields)
2047
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2048
+			: '';
2049
+        
2050
+		$test_settings_html = '';
2051
+		//print out $test_settings_fields
2052
+		if ( ! empty($test_settings_fields)) {
2053
+			echo $test_settings_fields;
2054
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2055
+			$test_settings_html .= 'name="test_button" value="';
2056
+			$test_settings_html .= __('Test Send', 'event_espresso');
2057
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2058
+		}
2059
+        
2060
+		//and button
2061
+		$test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2062
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2063
+		$test_settings_html .= $this->get_action_link_or_button(
2064
+			'reset_to_default',
2065
+			'reset',
2066
+			$extra_args,
2067
+			'button-primary reset-default-button'
2068
+		);
2069
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2070
+		echo $test_settings_html;
2071
+	}
2072
+    
2073
+    
2074
+	/**
2075
+	 * This returns the shortcode selector skeleton for a given context and field.
2076
+	 *
2077
+	 * @since 4.9.rc.000
2078
+	 *
2079
+	 * @param string $field           The name of the field retrieving shortcodes for.
2080
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2081
+	 *
2082
+	 * @return string
2083
+	 */
2084
+	protected function _get_shortcode_selector($field, $linked_input_id)
2085
+	{
2086
+		$template_args = array(
2087
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2088
+			'fieldname'       => $field,
2089
+			'linked_input_id' => $linked_input_id
2090
+		);
2091
+        
2092
+		return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2093
+			$template_args, true);
2094
+	}
2095
+    
2096
+    
2097
+	/**
2098
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2099
+	 * page)
2100
+	 *
2101
+	 * @access public
2102
+	 * @return void
2103
+	 */
2104
+	public function shortcode_meta_box()
2105
+	{
2106
+		$shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2107
+		//$messenger = $this->_message_template_group->messenger_obj();
2108
+		//now let's set the content depending on the status of the shortcodes array
2109
+		if (empty($shortcodes)) {
2110
+			$content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2111
+			echo $content;
2112
+		} else {
2113
+			//$alt = 0;
2114
+			?>
2115 2115
             <div
2116 2116
                 style="float:right; margin-top:10px"><?php echo $this->_get_help_tab_link('message_template_shortcodes'); ?></div>
2117 2117
             <p class="small-text"><?php printf(__('You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2118
-                    'event_espresso'), '<span class="dashicons dashicons-menu"></span>'); ?></p>
2118
+					'event_espresso'), '<span class="dashicons dashicons-menu"></span>'); ?></p>
2119 2119
             <?php
2120
-        }
2121
-        
2122
-        
2123
-    }
2124
-    
2125
-    
2126
-    /**
2127
-     * used to set the $_shortcodes property for when its needed elsewhere.
2128
-     *
2129
-     * @access protected
2130
-     * @return void
2131
-     */
2132
-    protected function _set_shortcodes()
2133
-    {
2134
-        
2135
-        //no need to run this if the property is already set
2136
-        if ( ! empty($this->_shortcodes)) {
2137
-            return;
2138
-        }
2139
-        
2140
-        $this->_shortcodes = $this->_get_shortcodes();
2141
-    }
2142
-    
2143
-    
2144
-    /**
2145
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2146
-     * property)
2147
-     *
2148
-     * @access  protected
2149
-     *
2150
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2151
-     *                         for. Defaults to all (for the given context)
2152
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2153
-     *
2154
-     * @return array          Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2155
-     *                        true just an array of shortcode/label pairs.
2156
-     */
2157
-    protected function _get_shortcodes($fields = array(), $merged = true)
2158
-    {
2159
-        $this->_set_message_template_group();
2160
-        
2161
-        //we need the messenger and message template to retrieve the valid shortcodes array.
2162
-        $GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id']) : false;
2163
-        $context = isset($this->_req_data['context']) ? $this->_req_data['context'] : key($this->_message_template_group->contexts_config());
2164
-        
2165
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2166
-    }
2167
-    
2168
-    
2169
-    /**
2170
-     * This sets the _message_template property (containing the called message_template object)
2171
-     *
2172
-     * @access protected
2173
-     * @return  void
2174
-     */
2175
-    protected function _set_message_template_group()
2176
-    {
2177
-        
2178
-        if ( ! empty($this->_message_template_group)) {
2179
-            return;
2180
-        } //get out if this is already set.
2181
-        
2182
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2183
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2184
-        
2185
-        //let's get the message templates
2186
-        $MTP = EEM_Message_Template_Group::instance();
2187
-        
2188
-        if (empty($GRP_ID)) {
2189
-            $this->_message_template_group = $MTP->create_default_object();
2190
-        } else {
2191
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2192
-        }
2193
-        
2194
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2195
-        $this->_variation     = $this->_message_template_group->get_template_pack_variation();
2196
-        
2197
-    }
2198
-    
2199
-    
2200
-    /**
2201
-     * sets up a context switcher for edit forms
2202
-     *
2203
-     * @access  protected
2204
-     *
2205
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2206
-     * @param array                      $args                  various things the context switcher needs.
2207
-     *
2208
-     */
2209
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2210
-    {
2211
-        $context_details = $template_group_object->contexts_config();
2212
-        $context_label   = $template_group_object->context_label();
2213
-        ob_start();
2214
-        ?>
2120
+		}
2121
+        
2122
+        
2123
+	}
2124
+    
2125
+    
2126
+	/**
2127
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2128
+	 *
2129
+	 * @access protected
2130
+	 * @return void
2131
+	 */
2132
+	protected function _set_shortcodes()
2133
+	{
2134
+        
2135
+		//no need to run this if the property is already set
2136
+		if ( ! empty($this->_shortcodes)) {
2137
+			return;
2138
+		}
2139
+        
2140
+		$this->_shortcodes = $this->_get_shortcodes();
2141
+	}
2142
+    
2143
+    
2144
+	/**
2145
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2146
+	 * property)
2147
+	 *
2148
+	 * @access  protected
2149
+	 *
2150
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2151
+	 *                         for. Defaults to all (for the given context)
2152
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2153
+	 *
2154
+	 * @return array          Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2155
+	 *                        true just an array of shortcode/label pairs.
2156
+	 */
2157
+	protected function _get_shortcodes($fields = array(), $merged = true)
2158
+	{
2159
+		$this->_set_message_template_group();
2160
+        
2161
+		//we need the messenger and message template to retrieve the valid shortcodes array.
2162
+		$GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id']) : false;
2163
+		$context = isset($this->_req_data['context']) ? $this->_req_data['context'] : key($this->_message_template_group->contexts_config());
2164
+        
2165
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2166
+	}
2167
+    
2168
+    
2169
+	/**
2170
+	 * This sets the _message_template property (containing the called message_template object)
2171
+	 *
2172
+	 * @access protected
2173
+	 * @return  void
2174
+	 */
2175
+	protected function _set_message_template_group()
2176
+	{
2177
+        
2178
+		if ( ! empty($this->_message_template_group)) {
2179
+			return;
2180
+		} //get out if this is already set.
2181
+        
2182
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2183
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2184
+        
2185
+		//let's get the message templates
2186
+		$MTP = EEM_Message_Template_Group::instance();
2187
+        
2188
+		if (empty($GRP_ID)) {
2189
+			$this->_message_template_group = $MTP->create_default_object();
2190
+		} else {
2191
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2192
+		}
2193
+        
2194
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2195
+		$this->_variation     = $this->_message_template_group->get_template_pack_variation();
2196
+        
2197
+	}
2198
+    
2199
+    
2200
+	/**
2201
+	 * sets up a context switcher for edit forms
2202
+	 *
2203
+	 * @access  protected
2204
+	 *
2205
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2206
+	 * @param array                      $args                  various things the context switcher needs.
2207
+	 *
2208
+	 */
2209
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2210
+	{
2211
+		$context_details = $template_group_object->contexts_config();
2212
+		$context_label   = $template_group_object->context_label();
2213
+		ob_start();
2214
+		?>
2215 2215
         <div class="ee-msg-switcher-container">
2216 2216
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2217 2217
                 <?php
2218
-                foreach ($args as $name => $value) {
2219
-                    if ($name == 'context' || empty($value) || $name == 'extra') {
2220
-                        continue;
2221
-                    }
2222
-                    ?>
2218
+				foreach ($args as $name => $value) {
2219
+					if ($name == 'context' || empty($value) || $name == 'extra') {
2220
+						continue;
2221
+					}
2222
+					?>
2223 2223
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2224 2224
                     <?php
2225
-                }
2226
-                //setup nonce_url
2227
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2228
-                ?>
2225
+				}
2226
+				//setup nonce_url
2227
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2228
+				?>
2229 2229
                 <select name="context">
2230 2230
                     <?php
2231
-                    $context_templates = $template_group_object->context_templates();
2232
-                    if (is_array($context_templates)) :
2233
-                        foreach ($context_templates as $context => $template_fields) :
2234
-                            $checked = ($context == $args['context']) ? 'selected="selected"' : '';
2235
-                            ?>
2231
+					$context_templates = $template_group_object->context_templates();
2232
+					if (is_array($context_templates)) :
2233
+						foreach ($context_templates as $context => $template_fields) :
2234
+							$checked = ($context == $args['context']) ? 'selected="selected"' : '';
2235
+							?>
2236 2236
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2237 2237
                                 <?php echo $context_details[$context]['label']; ?>
2238 2238
                             </option>
@@ -2245,1584 +2245,1584 @@  discard block
 block discarded – undo
2245 2245
             <?php echo $args['extra']; ?>
2246 2246
         </div> <!-- end .ee-msg-switcher-container -->
2247 2247
         <?php
2248
-        $output = ob_get_contents();
2249
-        ob_clean();
2250
-        $this->_context_switcher = $output;
2251
-    }
2252
-    
2253
-    
2254
-    /**
2255
-     * utility for sanitizing new values coming in.
2256
-     * Note: this is only used when updating a context.
2257
-     *
2258
-     * @access protected
2259
-     *
2260
-     * @param int $index This helps us know which template field to select from the request array.
2261
-     *
2262
-     * @return array
2263
-     */
2264
-    protected function _set_message_template_column_values($index)
2265
-    {
2266
-        if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2267
-            foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2268
-                $this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2269
-            }
2270
-        } /*else {
2248
+		$output = ob_get_contents();
2249
+		ob_clean();
2250
+		$this->_context_switcher = $output;
2251
+	}
2252
+    
2253
+    
2254
+	/**
2255
+	 * utility for sanitizing new values coming in.
2256
+	 * Note: this is only used when updating a context.
2257
+	 *
2258
+	 * @access protected
2259
+	 *
2260
+	 * @param int $index This helps us know which template field to select from the request array.
2261
+	 *
2262
+	 * @return array
2263
+	 */
2264
+	protected function _set_message_template_column_values($index)
2265
+	{
2266
+		if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2267
+			foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2268
+				$this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2269
+			}
2270
+		} /*else {
2271 2271
 			$this->_req_data['MTP_template_fields'][$index]['content'] = $this->_req_data['MTP_template_fields'][$index]['content'];
2272 2272
 		}*/
2273 2273
         
2274 2274
         
2275
-        $set_column_values = array(
2276
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2277
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2278
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2279
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2280
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2281
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2282
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2283
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2284
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2285
-                ? absint($this->_req_data['MTP_is_global'])
2286
-                : 0,
2287
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2288
-                ? absint($this->_req_data['MTP_is_override'])
2289
-                : 0,
2290
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2291
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2292
-        );
2293
-        
2294
-        
2295
-        return $set_column_values;
2296
-    }
2297
-    
2298
-    
2299
-    protected function _insert_or_update_message_template($new = false)
2300
-    {
2301
-        
2302
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2303
-        $success  = 0;
2304
-        $override = false;
2305
-        
2306
-        //setup notices description
2307
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2308
-        
2309
-        //need the message type and messenger objects to be able to use the labels for the notices
2310
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2311
-        $messenger_label  = $messenger_object instanceof EE_messenger ? ucwords($messenger_object->label['singular']) : '';
2312
-        
2313
-        $message_type_slug   = ! empty($this->_req_data['MTP_message_type']) ? $this->_req_data['MTP_message_type'] : '';
2314
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2315
-        
2316
-        $message_type_label = $message_type_object instanceof EE_message_type
2317
-            ? ucwords($message_type_object->label['singular'])
2318
-            : '';
2319
-        
2320
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2321
-            ? $this->_req_data['MTP_context']
2322
-            : '';
2323
-        $context      = ucwords(str_replace('_', ' ', $context_slug));
2324
-        
2325
-        $item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2326
-        $item_desc .= 'Message Template';
2327
-        $query_args  = array();
2328
-        $edit_array  = array();
2329
-        $action_desc = '';
2330
-        
2331
-        //if this is "new" then we need to generate the default contexts for the selected messenger/message_type for user to edit.
2332
-        if ($new) {
2333
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2334
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2335
-                if (empty($edit_array)) {
2336
-                    $success = 0;
2337
-                } else {
2338
-                    $success    = 1;
2339
-                    $edit_array = $edit_array[0];
2340
-                    $query_args = array(
2341
-                        'id'      => $edit_array['GRP_ID'],
2342
-                        'context' => $edit_array['MTP_context'],
2343
-                        'action'  => 'edit_message_template'
2344
-                    );
2345
-                }
2346
-            }
2347
-            $action_desc = 'created';
2348
-        } else {
2349
-            $MTPG = EEM_Message_Template_Group::instance();
2350
-            $MTP  = EEM_Message_Template::instance();
2275
+		$set_column_values = array(
2276
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2277
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2278
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2279
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2280
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2281
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2282
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2283
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2284
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2285
+				? absint($this->_req_data['MTP_is_global'])
2286
+				: 0,
2287
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2288
+				? absint($this->_req_data['MTP_is_override'])
2289
+				: 0,
2290
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2291
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2292
+		);
2293
+        
2294
+        
2295
+		return $set_column_values;
2296
+	}
2297
+    
2298
+    
2299
+	protected function _insert_or_update_message_template($new = false)
2300
+	{
2301
+        
2302
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2303
+		$success  = 0;
2304
+		$override = false;
2305
+        
2306
+		//setup notices description
2307
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2308
+        
2309
+		//need the message type and messenger objects to be able to use the labels for the notices
2310
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2311
+		$messenger_label  = $messenger_object instanceof EE_messenger ? ucwords($messenger_object->label['singular']) : '';
2312
+        
2313
+		$message_type_slug   = ! empty($this->_req_data['MTP_message_type']) ? $this->_req_data['MTP_message_type'] : '';
2314
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2315
+        
2316
+		$message_type_label = $message_type_object instanceof EE_message_type
2317
+			? ucwords($message_type_object->label['singular'])
2318
+			: '';
2319
+        
2320
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2321
+			? $this->_req_data['MTP_context']
2322
+			: '';
2323
+		$context      = ucwords(str_replace('_', ' ', $context_slug));
2324
+        
2325
+		$item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2326
+		$item_desc .= 'Message Template';
2327
+		$query_args  = array();
2328
+		$edit_array  = array();
2329
+		$action_desc = '';
2330
+        
2331
+		//if this is "new" then we need to generate the default contexts for the selected messenger/message_type for user to edit.
2332
+		if ($new) {
2333
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2334
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2335
+				if (empty($edit_array)) {
2336
+					$success = 0;
2337
+				} else {
2338
+					$success    = 1;
2339
+					$edit_array = $edit_array[0];
2340
+					$query_args = array(
2341
+						'id'      => $edit_array['GRP_ID'],
2342
+						'context' => $edit_array['MTP_context'],
2343
+						'action'  => 'edit_message_template'
2344
+					);
2345
+				}
2346
+			}
2347
+			$action_desc = 'created';
2348
+		} else {
2349
+			$MTPG = EEM_Message_Template_Group::instance();
2350
+			$MTP  = EEM_Message_Template::instance();
2351 2351
             
2352 2352
             
2353
-            //run update for each template field in displayed context
2354
-            if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2355
-                EE_Error::add_error(
2356
-                    __('There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2357
-                        'event_espresso'),
2358
-                    __FILE__, __FUNCTION__, __LINE__
2359
-                );
2360
-                $success = 0;
2353
+			//run update for each template field in displayed context
2354
+			if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2355
+				EE_Error::add_error(
2356
+					__('There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2357
+						'event_espresso'),
2358
+					__FILE__, __FUNCTION__, __LINE__
2359
+				);
2360
+				$success = 0;
2361 2361
                 
2362
-            } else {
2363
-                //first validate all fields!
2364
-                $validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2365
-                    $message_type_slug);
2362
+			} else {
2363
+				//first validate all fields!
2364
+				$validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2365
+					$message_type_slug);
2366 2366
                 
2367
-                //if $validate returned error messages (i.e. is_array()) then we need to process them and setup an appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.  WE need to make sure there is no actual error messages in validates.
2368
-                if (is_array($validates) && ! empty($validates)) {
2369
-                    //add the transient so when the form loads we know which fields to highlight
2370
-                    $this->_add_transient('edit_message_template', $validates);
2367
+				//if $validate returned error messages (i.e. is_array()) then we need to process them and setup an appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.  WE need to make sure there is no actual error messages in validates.
2368
+				if (is_array($validates) && ! empty($validates)) {
2369
+					//add the transient so when the form loads we know which fields to highlight
2370
+					$this->_add_transient('edit_message_template', $validates);
2371 2371
                     
2372
-                    $success = 0;
2372
+					$success = 0;
2373 2373
                     
2374
-                    //setup notices
2375
-                    foreach ($validates as $field => $error) {
2376
-                        if (isset($error['msg'])) {
2377
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2378
-                        }
2379
-                    }
2374
+					//setup notices
2375
+					foreach ($validates as $field => $error) {
2376
+						if (isset($error['msg'])) {
2377
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2378
+						}
2379
+					}
2380 2380
                     
2381
-                } else {
2382
-                    $set_column_values = array();
2383
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2384
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2381
+				} else {
2382
+					$set_column_values = array();
2383
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2384
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2385 2385
                         
2386
-                        $where_cols_n_values = array(
2387
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2388
-                        );
2386
+						$where_cols_n_values = array(
2387
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2388
+						);
2389 2389
                         
2390
-                        $message_template_fields = array(
2391
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2392
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2393
-                            'MTP_context'        => $set_column_values['MTP_context'],
2394
-                            'MTP_content'        => $set_column_values['MTP_content']
2395
-                        );
2396
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2397
-                            if ($updated === false) {
2398
-                                EE_Error::add_error(
2399
-                                    sprintf(
2400
-                                        __('%s field was NOT updated for some reason', 'event_espresso'),
2401
-                                        $template_field
2402
-                                    ),
2403
-                                    __FILE__, __FUNCTION__, __LINE__
2404
-                                );
2405
-                            } else {
2406
-                                $success = 1;
2407
-                            }
2408
-                        }
2409
-                        $action_desc = 'updated';
2410
-                    }
2390
+						$message_template_fields = array(
2391
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2392
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2393
+							'MTP_context'        => $set_column_values['MTP_context'],
2394
+							'MTP_content'        => $set_column_values['MTP_content']
2395
+						);
2396
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2397
+							if ($updated === false) {
2398
+								EE_Error::add_error(
2399
+									sprintf(
2400
+										__('%s field was NOT updated for some reason', 'event_espresso'),
2401
+										$template_field
2402
+									),
2403
+									__FILE__, __FUNCTION__, __LINE__
2404
+								);
2405
+							} else {
2406
+								$success = 1;
2407
+							}
2408
+						}
2409
+						$action_desc = 'updated';
2410
+					}
2411 2411
                     
2412
-                    //we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2413
-                    $mtpg_fields = array(
2414
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2415
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2416
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2417
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2418
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2419
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2420
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2421
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2422
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2423
-                            : '',
2424
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2425
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2426
-                            : ''
2427
-                    );
2412
+					//we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2413
+					$mtpg_fields = array(
2414
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2415
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2416
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2417
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2418
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2419
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2420
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2421
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2422
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2423
+							: '',
2424
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2425
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2426
+							: ''
2427
+					);
2428 2428
                     
2429
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2430
-                    $updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2429
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2430
+					$updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2431 2431
                     
2432
-                    if ($updated === false) {
2433
-                        EE_Error::add_error(
2434
-                            sprintf(
2435
-                                __('The Message Template Group (%d) was NOT updated for some reason', 'event_espresso'),
2436
-                                $set_column_values['GRP_ID']
2437
-                            ),
2438
-                            __FILE__, __FUNCTION__, __LINE__
2439
-                        );
2440
-                    } else {
2441
-                        //k now we need to ensure the template_pack and template_variation fields are set.
2442
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2443
-                            ? $this->_req_data['MTP_template_pack']
2444
-                            : 'default';
2432
+					if ($updated === false) {
2433
+						EE_Error::add_error(
2434
+							sprintf(
2435
+								__('The Message Template Group (%d) was NOT updated for some reason', 'event_espresso'),
2436
+								$set_column_values['GRP_ID']
2437
+							),
2438
+							__FILE__, __FUNCTION__, __LINE__
2439
+						);
2440
+					} else {
2441
+						//k now we need to ensure the template_pack and template_variation fields are set.
2442
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2443
+							? $this->_req_data['MTP_template_pack']
2444
+							: 'default';
2445 2445
                         
2446
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2447
-                            ? $this->_req_data['MTP_template_variation']
2448
-                            : 'default';
2446
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2447
+							? $this->_req_data['MTP_template_variation']
2448
+							: 'default';
2449 2449
                         
2450
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2451
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2452
-                            $mtpg_obj->set_template_pack_name($template_pack);
2453
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2454
-                        }
2455
-                        $success = 1;
2456
-                    }
2457
-                }
2458
-            }
2450
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2451
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2452
+							$mtpg_obj->set_template_pack_name($template_pack);
2453
+							$mtpg_obj->set_template_pack_variation($template_variation);
2454
+						}
2455
+						$success = 1;
2456
+					}
2457
+				}
2458
+			}
2459 2459
             
2460
-        }
2461
-        
2462
-        //we return things differently if doing ajax
2463
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2464
-            $this->_template_args['success'] = $success;
2465
-            $this->_template_args['error']   = ! $success ? true : false;
2466
-            $this->_template_args['content'] = '';
2467
-            $this->_template_args['data']    = array(
2468
-                'grpID'        => $edit_array['GRP_ID'],
2469
-                'templateName' => $edit_array['template_name']
2470
-            );
2471
-            if ($success) {
2472
-                EE_Error::overwrite_success();
2473
-                EE_Error::add_success(__('The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2474
-                    'event_espresso'));
2475
-            }
2460
+		}
2461
+        
2462
+		//we return things differently if doing ajax
2463
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2464
+			$this->_template_args['success'] = $success;
2465
+			$this->_template_args['error']   = ! $success ? true : false;
2466
+			$this->_template_args['content'] = '';
2467
+			$this->_template_args['data']    = array(
2468
+				'grpID'        => $edit_array['GRP_ID'],
2469
+				'templateName' => $edit_array['template_name']
2470
+			);
2471
+			if ($success) {
2472
+				EE_Error::overwrite_success();
2473
+				EE_Error::add_success(__('The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2474
+					'event_espresso'));
2475
+			}
2476 2476
             
2477
-            $this->_return_json();
2478
-        }
2479
-        
2480
-        
2481
-        //was a test send triggered?
2482
-        if (isset($this->_req_data['test_button'])) {
2483
-            EE_Error::overwrite_success();
2484
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2485
-            $override = true;
2486
-        }
2487
-        
2488
-        if (empty($query_args)) {
2489
-            $query_args = array(
2490
-                'id'      => $this->_req_data['GRP_ID'],
2491
-                'context' => $context_slug,
2492
-                'action'  => 'edit_message_template'
2493
-            );
2494
-        }
2495
-        
2496
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2497
-    }
2498
-    
2499
-    
2500
-    /**
2501
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
2502
-     *
2503
-     * @param  string $context      what context being tested
2504
-     * @param  string $messenger    messenger being tested
2505
-     * @param  string $message_type message type being tested
2506
-     *
2507
-     */
2508
-    protected function _do_test_send($context, $messenger, $message_type)
2509
-    {
2510
-        //set things up for preview
2511
-        $this->_req_data['messenger']    = $messenger;
2512
-        $this->_req_data['message_type'] = $message_type;
2513
-        $this->_req_data['context']      = $context;
2514
-        $this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2515
-        $active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2516
-        
2517
-        //let's save any existing fields that might be required by the messenger
2518
-        if (
2519
-            isset($this->_req_data['test_settings_fld'])
2520
-            && $active_messenger instanceof EE_messenger
2521
-            && apply_filters(
2522
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2523
-                true,
2524
-                $this->_req_data['test_settings_fld'],
2525
-                $active_messenger
2526
-            )
2527
-        ) {
2528
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2529
-        }
2530
-        
2531
-        $success = $this->_preview_message(true);
2532
-        
2533
-        if ($success) {
2534
-            EE_Error::add_success(__('Test message sent', 'event_espresso'));
2535
-        } else {
2536
-            EE_Error::add_error(__('The test message was not sent', 'event_espresso'), __FILE__, __FUNCTION__,
2537
-                __LINE__);
2538
-        }
2539
-    }
2540
-    
2541
-    
2542
-    /**
2543
-     * _generate_new_templates
2544
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2545
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2546
-     * for the event.
2547
-     *
2548
-     *
2549
-     * @param  string $messenger     the messenger we are generating templates for
2550
-     * @param array   $message_types array of message types that the templates are generated for.
2551
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2552
-     *                               indicate the message_template_group being used as the base.
2553
-     *
2554
-     * @param bool    $global
2555
-     *
2556
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
2557
-     *                               encountering problems.
2558
-     * @throws \EE_Error
2559
-     */
2560
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2561
-    {
2562
-        
2563
-        //if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we just don't generate any templates.
2564
-        if (empty($message_types)) {
2565
-            return true;
2566
-        }
2567
-        
2568
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2569
-    }
2570
-    
2571
-    
2572
-    /**
2573
-     * [_trash_or_restore_message_template]
2574
-     *
2575
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2576
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2577
-     *                        an individual context (FALSE).
2578
-     *
2579
-     * @return void
2580
-     */
2581
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
2582
-    {
2583
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2584
-        $MTP = EEM_Message_Template_Group::instance();
2585
-        
2586
-        $success = 1;
2587
-        
2588
-        //incoming GRP_IDs
2589
-        if ($all) {
2590
-            //Checkboxes
2591
-            if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2592
-                //if array has more than one element then success message should be plural.
2593
-                //todo: what about nonce?
2594
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2477
+			$this->_return_json();
2478
+		}
2479
+        
2480
+        
2481
+		//was a test send triggered?
2482
+		if (isset($this->_req_data['test_button'])) {
2483
+			EE_Error::overwrite_success();
2484
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2485
+			$override = true;
2486
+		}
2487
+        
2488
+		if (empty($query_args)) {
2489
+			$query_args = array(
2490
+				'id'      => $this->_req_data['GRP_ID'],
2491
+				'context' => $context_slug,
2492
+				'action'  => 'edit_message_template'
2493
+			);
2494
+		}
2495
+        
2496
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2497
+	}
2498
+    
2499
+    
2500
+	/**
2501
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2502
+	 *
2503
+	 * @param  string $context      what context being tested
2504
+	 * @param  string $messenger    messenger being tested
2505
+	 * @param  string $message_type message type being tested
2506
+	 *
2507
+	 */
2508
+	protected function _do_test_send($context, $messenger, $message_type)
2509
+	{
2510
+		//set things up for preview
2511
+		$this->_req_data['messenger']    = $messenger;
2512
+		$this->_req_data['message_type'] = $message_type;
2513
+		$this->_req_data['context']      = $context;
2514
+		$this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2515
+		$active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2516
+        
2517
+		//let's save any existing fields that might be required by the messenger
2518
+		if (
2519
+			isset($this->_req_data['test_settings_fld'])
2520
+			&& $active_messenger instanceof EE_messenger
2521
+			&& apply_filters(
2522
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2523
+				true,
2524
+				$this->_req_data['test_settings_fld'],
2525
+				$active_messenger
2526
+			)
2527
+		) {
2528
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2529
+		}
2530
+        
2531
+		$success = $this->_preview_message(true);
2532
+        
2533
+		if ($success) {
2534
+			EE_Error::add_success(__('Test message sent', 'event_espresso'));
2535
+		} else {
2536
+			EE_Error::add_error(__('The test message was not sent', 'event_espresso'), __FILE__, __FUNCTION__,
2537
+				__LINE__);
2538
+		}
2539
+	}
2540
+    
2541
+    
2542
+	/**
2543
+	 * _generate_new_templates
2544
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2545
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2546
+	 * for the event.
2547
+	 *
2548
+	 *
2549
+	 * @param  string $messenger     the messenger we are generating templates for
2550
+	 * @param array   $message_types array of message types that the templates are generated for.
2551
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2552
+	 *                               indicate the message_template_group being used as the base.
2553
+	 *
2554
+	 * @param bool    $global
2555
+	 *
2556
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
2557
+	 *                               encountering problems.
2558
+	 * @throws \EE_Error
2559
+	 */
2560
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2561
+	{
2562
+        
2563
+		//if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we just don't generate any templates.
2564
+		if (empty($message_types)) {
2565
+			return true;
2566
+		}
2567
+        
2568
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2569
+	}
2570
+    
2571
+    
2572
+	/**
2573
+	 * [_trash_or_restore_message_template]
2574
+	 *
2575
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2576
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2577
+	 *                        an individual context (FALSE).
2578
+	 *
2579
+	 * @return void
2580
+	 */
2581
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
2582
+	{
2583
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2584
+		$MTP = EEM_Message_Template_Group::instance();
2585
+        
2586
+		$success = 1;
2587
+        
2588
+		//incoming GRP_IDs
2589
+		if ($all) {
2590
+			//Checkboxes
2591
+			if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2592
+				//if array has more than one element then success message should be plural.
2593
+				//todo: what about nonce?
2594
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2595 2595
                 
2596
-                //cycle through checkboxes
2597
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2598
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2599
-                    if ( ! $trashed_or_restored) {
2600
-                        $success = 0;
2601
-                    }
2602
-                }
2603
-            } else {
2604
-                //grab single GRP_ID and handle
2605
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
2606
-                if ( ! empty($GRP_ID)) {
2607
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2608
-                    if ( ! $trashed_or_restored) {
2609
-                        $success = 0;
2610
-                    }
2611
-                } else {
2612
-                    $success = 0;
2613
-                }
2614
-            }
2596
+				//cycle through checkboxes
2597
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2598
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2599
+					if ( ! $trashed_or_restored) {
2600
+						$success = 0;
2601
+					}
2602
+				}
2603
+			} else {
2604
+				//grab single GRP_ID and handle
2605
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
2606
+				if ( ! empty($GRP_ID)) {
2607
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2608
+					if ( ! $trashed_or_restored) {
2609
+						$success = 0;
2610
+					}
2611
+				} else {
2612
+					$success = 0;
2613
+				}
2614
+			}
2615 2615
             
2616
-        }
2616
+		}
2617 2617
         
2618
-        $action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2618
+		$action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2619 2619
         
2620
-        $action_desc = ! empty($this->_req_data['template_switch']) ? __('switched') : $action_desc;
2620
+		$action_desc = ! empty($this->_req_data['template_switch']) ? __('switched') : $action_desc;
2621 2621
         
2622
-        $item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
2623
-            'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
2622
+		$item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
2623
+			'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
2624 2624
         
2625
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
2626
-            'event_espresso') : $item_desc;
2625
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
2626
+			'event_espresso') : $item_desc;
2627 2627
         
2628
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
2628
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
2629 2629
         
2630
-    }
2630
+	}
2631 2631
     
2632 2632
     
2633
-    /**
2634
-     * [_delete_message_template]
2635
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
2636
-     * @return void
2637
-     */
2638
-    protected function _delete_message_template()
2639
-    {
2640
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2633
+	/**
2634
+	 * [_delete_message_template]
2635
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
2636
+	 * @return void
2637
+	 */
2638
+	protected function _delete_message_template()
2639
+	{
2640
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2641 2641
         
2642
-        //checkboxes
2643
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2644
-            //if array has more than one element then success message should be plural
2645
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2642
+		//checkboxes
2643
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2644
+			//if array has more than one element then success message should be plural
2645
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2646 2646
             
2647
-            //cycle through bulk action checkboxes
2648
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2649
-                $success = $this->_delete_mtp_permanently($GRP_ID);
2650
-            }
2651
-        } else {
2652
-            //grab single grp_id and delete
2653
-            $GRP_ID  = absint($this->_req_data['id']);
2654
-            $success = $this->_delete_mtp_permanently($GRP_ID);
2655
-        }
2656
-        
2657
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
2658
-        
2659
-    }
2660
-    
2661
-    
2662
-    /**
2663
-     * helper for permanently deleting a mtP group and all related message_templates
2664
-     *
2665
-     * @param  int  $GRP_ID        The group being deleted
2666
-     * @param  bool $include_group whether to delete the Message Template Group as well.
2667
-     *
2668
-     * @return bool        boolean to indicate the success of the deletes or not.
2669
-     */
2670
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
2671
-    {
2672
-        $success = 1;
2673
-        $MTPG    = EEM_Message_Template_Group::instance();
2674
-        //first let's GET this group
2675
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
2676
-        //then delete permanently all the related Message Templates
2677
-        $deleted = $MTG->delete_related_permanently('Message_Template');
2678
-        
2679
-        if ($deleted === 0) {
2680
-            $success = 0;
2681
-        }
2682
-        
2683
-        //now delete permanently this particular group
2684
-        
2685
-        if ($include_group && ! $MTG->delete_permanently()) {
2686
-            $success = 0;
2687
-        }
2688
-        
2689
-        return $success;
2690
-    }
2691
-    
2692
-    
2693
-    /**
2694
-     *    _learn_more_about_message_templates_link
2695
-     * @access protected
2696
-     * @return string
2697
-     */
2698
-    protected function _learn_more_about_message_templates_link()
2699
-    {
2700
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2701
-            'event_espresso') . '</a>';
2702
-    }
2703
-    
2704
-    
2705
-    /**
2706
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
2707
-     * ajax and other routes.
2708
-     * @return void
2709
-     */
2710
-    protected function _settings()
2711
-    {
2712
-        
2713
-        
2714
-        $this->_set_m_mt_settings();
2715
-        
2716
-        $selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2717
-        
2718
-        //let's setup the messenger tabs
2719
-        $this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links($this->_m_mt_settings['messenger_tabs'],
2720
-            'messenger_links', '|', $selected_messenger);
2721
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
2722
-        $this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
2723
-        
2724
-        $this->display_admin_page_with_sidebar();
2725
-        
2726
-    }
2727
-    
2728
-    
2729
-    /**
2730
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
2731
-     *
2732
-     * @access protected
2733
-     * @return void
2734
-     */
2735
-    protected function _set_m_mt_settings()
2736
-    {
2737
-        //first if this is already set then lets get out no need to regenerate data.
2738
-        if ( ! empty($this->_m_mt_settings)) {
2739
-            return;
2740
-        }
2741
-        
2742
-        //$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2743
-        
2744
-        //get all installed messengers and message_types
2745
-        /** @type EE_messenger[] $messengers */
2746
-        $messengers = $this->_message_resource_manager->installed_messengers();
2747
-        /** @type EE_message_type[] $message_types */
2748
-        $message_types = $this->_message_resource_manager->installed_message_types();
2749
-        
2750
-        
2751
-        //assemble the array for the _tab_text_links helper
2752
-        
2753
-        foreach ($messengers as $messenger) {
2754
-            $this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
2755
-                'label' => ucwords($messenger->label['singular']),
2756
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name) ? 'messenger-active' : '',
2757
-                'href'  => $messenger->name,
2758
-                'title' => __('Modify this Messenger', 'event_espresso'),
2759
-                'slug'  => $messenger->name,
2760
-                'obj'   => $messenger
2761
-            );
2647
+			//cycle through bulk action checkboxes
2648
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2649
+				$success = $this->_delete_mtp_permanently($GRP_ID);
2650
+			}
2651
+		} else {
2652
+			//grab single grp_id and delete
2653
+			$GRP_ID  = absint($this->_req_data['id']);
2654
+			$success = $this->_delete_mtp_permanently($GRP_ID);
2655
+		}
2656
+        
2657
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
2658
+        
2659
+	}
2660
+    
2661
+    
2662
+	/**
2663
+	 * helper for permanently deleting a mtP group and all related message_templates
2664
+	 *
2665
+	 * @param  int  $GRP_ID        The group being deleted
2666
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
2667
+	 *
2668
+	 * @return bool        boolean to indicate the success of the deletes or not.
2669
+	 */
2670
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
2671
+	{
2672
+		$success = 1;
2673
+		$MTPG    = EEM_Message_Template_Group::instance();
2674
+		//first let's GET this group
2675
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
2676
+		//then delete permanently all the related Message Templates
2677
+		$deleted = $MTG->delete_related_permanently('Message_Template');
2678
+        
2679
+		if ($deleted === 0) {
2680
+			$success = 0;
2681
+		}
2682
+        
2683
+		//now delete permanently this particular group
2684
+        
2685
+		if ($include_group && ! $MTG->delete_permanently()) {
2686
+			$success = 0;
2687
+		}
2688
+        
2689
+		return $success;
2690
+	}
2691
+    
2692
+    
2693
+	/**
2694
+	 *    _learn_more_about_message_templates_link
2695
+	 * @access protected
2696
+	 * @return string
2697
+	 */
2698
+	protected function _learn_more_about_message_templates_link()
2699
+	{
2700
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2701
+			'event_espresso') . '</a>';
2702
+	}
2703
+    
2704
+    
2705
+	/**
2706
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
2707
+	 * ajax and other routes.
2708
+	 * @return void
2709
+	 */
2710
+	protected function _settings()
2711
+	{
2712
+        
2713
+        
2714
+		$this->_set_m_mt_settings();
2715
+        
2716
+		$selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2717
+        
2718
+		//let's setup the messenger tabs
2719
+		$this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links($this->_m_mt_settings['messenger_tabs'],
2720
+			'messenger_links', '|', $selected_messenger);
2721
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
2722
+		$this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
2723
+        
2724
+		$this->display_admin_page_with_sidebar();
2725
+        
2726
+	}
2727
+    
2728
+    
2729
+	/**
2730
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
2731
+	 *
2732
+	 * @access protected
2733
+	 * @return void
2734
+	 */
2735
+	protected function _set_m_mt_settings()
2736
+	{
2737
+		//first if this is already set then lets get out no need to regenerate data.
2738
+		if ( ! empty($this->_m_mt_settings)) {
2739
+			return;
2740
+		}
2741
+        
2742
+		//$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2743
+        
2744
+		//get all installed messengers and message_types
2745
+		/** @type EE_messenger[] $messengers */
2746
+		$messengers = $this->_message_resource_manager->installed_messengers();
2747
+		/** @type EE_message_type[] $message_types */
2748
+		$message_types = $this->_message_resource_manager->installed_message_types();
2749
+        
2750
+        
2751
+		//assemble the array for the _tab_text_links helper
2752
+        
2753
+		foreach ($messengers as $messenger) {
2754
+			$this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
2755
+				'label' => ucwords($messenger->label['singular']),
2756
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name) ? 'messenger-active' : '',
2757
+				'href'  => $messenger->name,
2758
+				'title' => __('Modify this Messenger', 'event_espresso'),
2759
+				'slug'  => $messenger->name,
2760
+				'obj'   => $messenger
2761
+			);
2762 2762
             
2763 2763
             
2764
-            $message_types_for_messenger = $messenger->get_valid_message_types();
2764
+			$message_types_for_messenger = $messenger->get_valid_message_types();
2765 2765
             
2766
-            foreach ($message_types as $message_type) {
2767
-                //first we need to verify that this message type is valid with this messenger. Cause if it isn't then it shouldn't show in either the inactive OR active metabox.
2768
-                if ( ! in_array($message_type->name, $message_types_for_messenger)) {
2769
-                    continue;
2770
-                }
2766
+			foreach ($message_types as $message_type) {
2767
+				//first we need to verify that this message type is valid with this messenger. Cause if it isn't then it shouldn't show in either the inactive OR active metabox.
2768
+				if ( ! in_array($message_type->name, $message_types_for_messenger)) {
2769
+					continue;
2770
+				}
2771 2771
                 
2772
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger($messenger->name,
2773
-                    $message_type->name) ? 'active' : 'inactive';
2772
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger($messenger->name,
2773
+					$message_type->name) ? 'active' : 'inactive';
2774 2774
                 
2775
-                $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2776
-                    'label'    => ucwords($message_type->label['singular']),
2777
-                    'class'    => 'message-type-' . $a_or_i,
2778
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2779
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2780
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2781
-                    'title'    => $a_or_i == 'active'
2782
-                        ? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2783
-                        : __('Drag this message type to the messenger to activate', 'event_espresso'),
2784
-                    'content'  => $a_or_i == 'active'
2785
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
2786
-                        : $this->_message_type_settings_content($message_type, $messenger),
2787
-                    'slug'     => $message_type->name,
2788
-                    'active'   => $a_or_i == 'active' ? true : false,
2789
-                    'obj'      => $message_type
2790
-                );
2791
-            }
2792
-        }
2793
-    }
2794
-    
2795
-    
2796
-    /**
2797
-     * This just prepares the content for the message type settings
2798
-     *
2799
-     * @param  object  $message_type The message type object
2800
-     * @param  object  $messenger    The messenger object
2801
-     * @param  boolean $active       Whether the message type is active or not
2802
-     *
2803
-     * @return string                html output for the content
2804
-     */
2805
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
2806
-    {
2807
-        //get message type fields
2808
-        $fields                                         = $message_type->get_admin_settings_fields();
2809
-        $settings_template_args['template_form_fields'] = '';
2810
-        
2811
-        if ( ! empty($fields) && $active) {
2775
+				$this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2776
+					'label'    => ucwords($message_type->label['singular']),
2777
+					'class'    => 'message-type-' . $a_or_i,
2778
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2779
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2780
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2781
+					'title'    => $a_or_i == 'active'
2782
+						? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2783
+						: __('Drag this message type to the messenger to activate', 'event_espresso'),
2784
+					'content'  => $a_or_i == 'active'
2785
+						? $this->_message_type_settings_content($message_type, $messenger, true)
2786
+						: $this->_message_type_settings_content($message_type, $messenger),
2787
+					'slug'     => $message_type->name,
2788
+					'active'   => $a_or_i == 'active' ? true : false,
2789
+					'obj'      => $message_type
2790
+				);
2791
+			}
2792
+		}
2793
+	}
2794
+    
2795
+    
2796
+	/**
2797
+	 * This just prepares the content for the message type settings
2798
+	 *
2799
+	 * @param  object  $message_type The message type object
2800
+	 * @param  object  $messenger    The messenger object
2801
+	 * @param  boolean $active       Whether the message type is active or not
2802
+	 *
2803
+	 * @return string                html output for the content
2804
+	 */
2805
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
2806
+	{
2807
+		//get message type fields
2808
+		$fields                                         = $message_type->get_admin_settings_fields();
2809
+		$settings_template_args['template_form_fields'] = '';
2810
+        
2811
+		if ( ! empty($fields) && $active) {
2812 2812
             
2813
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2813
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2814 2814
             
2815
-            foreach ($fields as $fldname => $fldprops) {
2816
-                $field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2817
-                $template_form_field[$field_id] = array(
2818
-                    'name'       => 'message_type_settings[' . $fldname . ']',
2819
-                    'label'      => $fldprops['label'],
2820
-                    'input'      => $fldprops['field_type'],
2821
-                    'type'       => $fldprops['value_type'],
2822
-                    'required'   => $fldprops['required'],
2823
-                    'validation' => $fldprops['validation'],
2824
-                    'value'      => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2825
-                    'options'    => isset($fldprops['options']) ? $fldprops['options'] : array(),
2826
-                    'default'    => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2827
-                    'css_class'  => 'no-drag',
2828
-                    'format'     => $fldprops['format']
2829
-                );
2830
-            }
2815
+			foreach ($fields as $fldname => $fldprops) {
2816
+				$field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2817
+				$template_form_field[$field_id] = array(
2818
+					'name'       => 'message_type_settings[' . $fldname . ']',
2819
+					'label'      => $fldprops['label'],
2820
+					'input'      => $fldprops['field_type'],
2821
+					'type'       => $fldprops['value_type'],
2822
+					'required'   => $fldprops['required'],
2823
+					'validation' => $fldprops['validation'],
2824
+					'value'      => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2825
+					'options'    => isset($fldprops['options']) ? $fldprops['options'] : array(),
2826
+					'default'    => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2827
+					'css_class'  => 'no-drag',
2828
+					'format'     => $fldprops['format']
2829
+				);
2830
+			}
2831 2831
             
2832 2832
             
2833
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field) ? $this->_generate_admin_form_fields($template_form_field,
2834
-                'string', 'ee_mt_activate_form') : '';
2835
-        }
2836
-        
2837
-        $settings_template_args['description'] = $message_type->description;
2838
-        //we also need some hidden fields
2839
-        $settings_template_args['hidden_fields'] = array(
2840
-            'message_type_settings[messenger]'    => array(
2841
-                'type'  => 'hidden',
2842
-                'value' => $messenger->name
2843
-            ),
2844
-            'message_type_settings[message_type]' => array(
2845
-                'type'  => 'hidden',
2846
-                'value' => $message_type->name
2847
-            ),
2848
-            'type'                                => array(
2849
-                'type'  => 'hidden',
2850
-                'value' => 'message_type'
2851
-            )
2852
-        );
2853
-        
2854
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields($settings_template_args['hidden_fields'],
2855
-            'array');
2856
-        $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2857
-        
2858
-        
2859
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2860
-        $content  = EEH_Template::display_template($template, $settings_template_args, true);
2861
-        
2862
-        return $content;
2863
-    }
2864
-    
2865
-    
2866
-    /**
2867
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
2868
-     *
2869
-     * @access protected
2870
-     * @return void
2871
-     */
2872
-    protected function _messages_settings_metaboxes()
2873
-    {
2874
-        $this->_set_m_mt_settings();
2875
-        $m_boxes         = $mt_boxes = array();
2876
-        $m_template_args = $mt_template_args = array();
2877
-        
2878
-        $selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2879
-        
2880
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
2881
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
2882
-                $hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
2883
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
2884
-                //messenger meta boxes
2885
-                $active                                 = $selected_messenger == $messenger ? true : false;
2886
-                $active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2887
-                    ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2888
-                    : '';
2889
-                $m_boxes[$messenger . '_a_box']         = sprintf(
2890
-                    __('%s Settings', 'event_espresso'),
2891
-                    $tab_array['label']
2892
-                );
2893
-                $m_template_args[$messenger . '_a_box'] = array(
2894
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2895
-                    'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2896
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2897
-                        : '',
2898
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
2899
-                    'hidden'                 => $active ? '' : ' hidden',
2900
-                    'hide_on_message'        => $hide_on_message,
2901
-                    'messenger'              => $messenger,
2902
-                    'active'                 => $active
2903
-                );
2904
-                // message type meta boxes
2905
-                // (which is really just the inactive container for each messenger
2906
-                // showing inactive message types for that messenger)
2907
-                $mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2908
-                $mt_template_args[$messenger . '_i_box'] = array(
2909
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2910
-                    'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2911
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2912
-                        : '',
2913
-                    'hidden'                 => $active ? '' : ' hidden',
2914
-                    'hide_on_message'        => $hide_on_message,
2915
-                    'hide_off_message'       => $hide_off_message,
2916
-                    'messenger'              => $messenger,
2917
-                    'active'                 => $active
2918
-                );
2919
-            }
2920
-        }
2921
-        
2922
-        
2923
-        //register messenger metaboxes
2924
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2925
-        foreach ($m_boxes as $box => $label) {
2926
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2927
-            $msgr          = str_replace('_a_box', '', $box);
2928
-            add_meta_box(
2929
-                'espresso_' . $msgr . '_settings',
2930
-                $label,
2931
-                function ($post, $metabox) {
2932
-                    echo EEH_Template::display_template($metabox["args"]["template_path"],
2933
-                        $metabox["args"]["template_args"], true);
2934
-                },
2935
-                $this->_current_screen->id,
2936
-                'normal',
2937
-                'high',
2938
-                $callback_args
2939
-            );
2940
-        }
2941
-        
2942
-        //register message type metaboxes
2943
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2944
-        foreach ($mt_boxes as $box => $label) {
2945
-            $callback_args = array(
2946
-                'template_path' => $mt_template_path,
2947
-                'template_args' => $mt_template_args[$box]
2948
-            );
2949
-            $mt            = str_replace('_i_box', '', $box);
2950
-            add_meta_box(
2951
-                'espresso_' . $mt . '_inactive_mts',
2952
-                $label,
2953
-                function ($post, $metabox) {
2954
-                    echo EEH_Template::display_template($metabox["args"]["template_path"],
2955
-                        $metabox["args"]["template_args"], true);
2956
-                },
2957
-                $this->_current_screen->id,
2958
-                'side',
2959
-                'high',
2960
-                $callback_args
2961
-            );
2962
-        }
2963
-        
2964
-        //register metabox for global messages settings but only when on the main site.  On single site installs this will
2965
-        //always result in the metabox showing, on multisite installs the metabox will only show on the main site.
2966
-        if (is_main_site()) {
2967
-            add_meta_box(
2968
-                'espresso_global_message_settings',
2969
-                __('Global Message Settings', 'event_espresso'),
2970
-                array($this, 'global_messages_settings_metabox_content'),
2971
-                $this->_current_screen->id,
2972
-                'normal',
2973
-                'low',
2974
-                array()
2975
-            );
2976
-        }
2977
-        
2978
-    }
2979
-    
2980
-    
2981
-    /**
2982
-     *  This generates the content for the global messages settings metabox.
2983
-     * @return string
2984
-     */
2985
-    public function global_messages_settings_metabox_content()
2986
-    {
2987
-        $form = $this->_generate_global_settings_form();
2988
-        echo $form->form_open(
2989
-                $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
2990
-                'POST'
2991
-            )
2992
-             . $form->get_html()
2993
-             . $form->form_close();
2994
-    }
2995
-    
2996
-    
2997
-    /**
2998
-     * This generates and returns the form object for the global messages settings.
2999
-     * @return EE_Form_Section_Proper
3000
-     */
3001
-    protected function _generate_global_settings_form()
3002
-    {
3003
-        EE_Registry::instance()->load_helper('HTML');
3004
-        /** @var EE_Network_Core_Config $network_config */
3005
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3006
-        
3007
-        return new EE_Form_Section_Proper(
3008
-            array(
3009
-                'name'            => 'global_messages_settings',
3010
-                'html_id'         => 'global_messages_settings',
3011
-                'html_class'      => 'form-table',
3012
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3013
-                'subsections'     => apply_filters(
3014
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3015
-                    array(
3016
-                        'do_messages_on_same_request' => new EE_Select_Input(
3017
-                            array(
3018
-                                true  => esc_html__("On the same request", "event_espresso"),
3019
-                                false => esc_html__("On a separate request", "event_espresso")
3020
-                            ),
3021
-                            array(
3022
-                                'default'         => $network_config->do_messages_on_same_request,
3023
-                                'html_label_text' => esc_html__('Generate and send all messages:', 'event_espresso'),
3024
-                                'html_help_text'  => esc_html__('By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3025
-                                    'event_espresso'),
3026
-                            )
3027
-                        ),
3028
-                        'delete_threshold' => new EE_Select_Input(
3029
-                            array(
3030
-                                0 => esc_html__('Forever', 'event_espresso'),
3031
-                                3 => esc_html__('3 Months', 'event_espresso'),
3032
-                                6 => esc_html__('6 Months', 'event_espresso'),
3033
-                                9 => esc_html__('9 Months', 'event_espresso'),
3034
-                                12 => esc_html__('12 Months', 'event_espresso'),
3035
-                                24 => esc_html__('24 Months', 'event_espresso'),
3036
-                                36 => esc_html__('36 Months', 'event_espresso')
3037
-                            ),
3038
-                            array(
3039
-                                'default' => EE_Registry::instance()->CFG->messages->delete_threshold,
3040
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3041
-                                'html_help_text' => esc_html__('You can control how long a record of processed messages is kept 
2833
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field) ? $this->_generate_admin_form_fields($template_form_field,
2834
+				'string', 'ee_mt_activate_form') : '';
2835
+		}
2836
+        
2837
+		$settings_template_args['description'] = $message_type->description;
2838
+		//we also need some hidden fields
2839
+		$settings_template_args['hidden_fields'] = array(
2840
+			'message_type_settings[messenger]'    => array(
2841
+				'type'  => 'hidden',
2842
+				'value' => $messenger->name
2843
+			),
2844
+			'message_type_settings[message_type]' => array(
2845
+				'type'  => 'hidden',
2846
+				'value' => $message_type->name
2847
+			),
2848
+			'type'                                => array(
2849
+				'type'  => 'hidden',
2850
+				'value' => 'message_type'
2851
+			)
2852
+		);
2853
+        
2854
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields($settings_template_args['hidden_fields'],
2855
+			'array');
2856
+		$settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2857
+        
2858
+        
2859
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2860
+		$content  = EEH_Template::display_template($template, $settings_template_args, true);
2861
+        
2862
+		return $content;
2863
+	}
2864
+    
2865
+    
2866
+	/**
2867
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
2868
+	 *
2869
+	 * @access protected
2870
+	 * @return void
2871
+	 */
2872
+	protected function _messages_settings_metaboxes()
2873
+	{
2874
+		$this->_set_m_mt_settings();
2875
+		$m_boxes         = $mt_boxes = array();
2876
+		$m_template_args = $mt_template_args = array();
2877
+        
2878
+		$selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2879
+        
2880
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
2881
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
2882
+				$hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
2883
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
2884
+				//messenger meta boxes
2885
+				$active                                 = $selected_messenger == $messenger ? true : false;
2886
+				$active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2887
+					? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2888
+					: '';
2889
+				$m_boxes[$messenger . '_a_box']         = sprintf(
2890
+					__('%s Settings', 'event_espresso'),
2891
+					$tab_array['label']
2892
+				);
2893
+				$m_template_args[$messenger . '_a_box'] = array(
2894
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2895
+					'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2896
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2897
+						: '',
2898
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
2899
+					'hidden'                 => $active ? '' : ' hidden',
2900
+					'hide_on_message'        => $hide_on_message,
2901
+					'messenger'              => $messenger,
2902
+					'active'                 => $active
2903
+				);
2904
+				// message type meta boxes
2905
+				// (which is really just the inactive container for each messenger
2906
+				// showing inactive message types for that messenger)
2907
+				$mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2908
+				$mt_template_args[$messenger . '_i_box'] = array(
2909
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2910
+					'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2911
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2912
+						: '',
2913
+					'hidden'                 => $active ? '' : ' hidden',
2914
+					'hide_on_message'        => $hide_on_message,
2915
+					'hide_off_message'       => $hide_off_message,
2916
+					'messenger'              => $messenger,
2917
+					'active'                 => $active
2918
+				);
2919
+			}
2920
+		}
2921
+        
2922
+        
2923
+		//register messenger metaboxes
2924
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2925
+		foreach ($m_boxes as $box => $label) {
2926
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2927
+			$msgr          = str_replace('_a_box', '', $box);
2928
+			add_meta_box(
2929
+				'espresso_' . $msgr . '_settings',
2930
+				$label,
2931
+				function ($post, $metabox) {
2932
+					echo EEH_Template::display_template($metabox["args"]["template_path"],
2933
+						$metabox["args"]["template_args"], true);
2934
+				},
2935
+				$this->_current_screen->id,
2936
+				'normal',
2937
+				'high',
2938
+				$callback_args
2939
+			);
2940
+		}
2941
+        
2942
+		//register message type metaboxes
2943
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2944
+		foreach ($mt_boxes as $box => $label) {
2945
+			$callback_args = array(
2946
+				'template_path' => $mt_template_path,
2947
+				'template_args' => $mt_template_args[$box]
2948
+			);
2949
+			$mt            = str_replace('_i_box', '', $box);
2950
+			add_meta_box(
2951
+				'espresso_' . $mt . '_inactive_mts',
2952
+				$label,
2953
+				function ($post, $metabox) {
2954
+					echo EEH_Template::display_template($metabox["args"]["template_path"],
2955
+						$metabox["args"]["template_args"], true);
2956
+				},
2957
+				$this->_current_screen->id,
2958
+				'side',
2959
+				'high',
2960
+				$callback_args
2961
+			);
2962
+		}
2963
+        
2964
+		//register metabox for global messages settings but only when on the main site.  On single site installs this will
2965
+		//always result in the metabox showing, on multisite installs the metabox will only show on the main site.
2966
+		if (is_main_site()) {
2967
+			add_meta_box(
2968
+				'espresso_global_message_settings',
2969
+				__('Global Message Settings', 'event_espresso'),
2970
+				array($this, 'global_messages_settings_metabox_content'),
2971
+				$this->_current_screen->id,
2972
+				'normal',
2973
+				'low',
2974
+				array()
2975
+			);
2976
+		}
2977
+        
2978
+	}
2979
+    
2980
+    
2981
+	/**
2982
+	 *  This generates the content for the global messages settings metabox.
2983
+	 * @return string
2984
+	 */
2985
+	public function global_messages_settings_metabox_content()
2986
+	{
2987
+		$form = $this->_generate_global_settings_form();
2988
+		echo $form->form_open(
2989
+				$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
2990
+				'POST'
2991
+			)
2992
+			 . $form->get_html()
2993
+			 . $form->form_close();
2994
+	}
2995
+    
2996
+    
2997
+	/**
2998
+	 * This generates and returns the form object for the global messages settings.
2999
+	 * @return EE_Form_Section_Proper
3000
+	 */
3001
+	protected function _generate_global_settings_form()
3002
+	{
3003
+		EE_Registry::instance()->load_helper('HTML');
3004
+		/** @var EE_Network_Core_Config $network_config */
3005
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3006
+        
3007
+		return new EE_Form_Section_Proper(
3008
+			array(
3009
+				'name'            => 'global_messages_settings',
3010
+				'html_id'         => 'global_messages_settings',
3011
+				'html_class'      => 'form-table',
3012
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3013
+				'subsections'     => apply_filters(
3014
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3015
+					array(
3016
+						'do_messages_on_same_request' => new EE_Select_Input(
3017
+							array(
3018
+								true  => esc_html__("On the same request", "event_espresso"),
3019
+								false => esc_html__("On a separate request", "event_espresso")
3020
+							),
3021
+							array(
3022
+								'default'         => $network_config->do_messages_on_same_request,
3023
+								'html_label_text' => esc_html__('Generate and send all messages:', 'event_espresso'),
3024
+								'html_help_text'  => esc_html__('By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3025
+									'event_espresso'),
3026
+							)
3027
+						),
3028
+						'delete_threshold' => new EE_Select_Input(
3029
+							array(
3030
+								0 => esc_html__('Forever', 'event_espresso'),
3031
+								3 => esc_html__('3 Months', 'event_espresso'),
3032
+								6 => esc_html__('6 Months', 'event_espresso'),
3033
+								9 => esc_html__('9 Months', 'event_espresso'),
3034
+								12 => esc_html__('12 Months', 'event_espresso'),
3035
+								24 => esc_html__('24 Months', 'event_espresso'),
3036
+								36 => esc_html__('36 Months', 'event_espresso')
3037
+							),
3038
+							array(
3039
+								'default' => EE_Registry::instance()->CFG->messages->delete_threshold,
3040
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3041
+								'html_help_text' => esc_html__('You can control how long a record of processed messages is kept 
3042 3042
                                                     via this option.', 'event_espresso'),
3043
-                            )
3044
-                        ),
3045
-                        'update_settings'             => new EE_Submit_Input(
3046
-                            array(
3047
-                                'default'         => esc_html__('Update', 'event_espresso'),
3048
-                                'html_label_text' => '&nbsp'
3049
-                            )
3050
-                        )
3051
-                    )
3052
-                )
3053
-            )
3054
-        );
3055
-    }
3056
-    
3057
-    
3058
-    /**
3059
-     * This handles updating the global settings set on the admin page.
3060
-     * @throws \EE_Error
3061
-     */
3062
-    protected function _update_global_settings()
3063
-    {
3064
-        /** @var EE_Network_Core_Config $network_config */
3065
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3066
-        $messages_config = EE_Registry::instance()->CFG->messages;
3067
-        $form           = $this->_generate_global_settings_form();
3068
-        if ($form->was_submitted()) {
3069
-            $form->receive_form_submission();
3070
-            if ($form->is_valid()) {
3071
-                $valid_data = $form->valid_data();
3072
-                foreach ($valid_data as $property => $value) {
3073
-                    $setter = 'set_' . $property;
3074
-                    if (method_exists($network_config, $setter)) {
3075
-                        $network_config->{$setter}($value);
3076
-                    } else if (
3077
-                        property_exists($network_config, $property)
3078
-                        && $network_config->{$property} !== $value
3079
-                    ) {
3080
-                        $network_config->{$property} = $value;
3081
-                    } else if (
3082
-                        property_exists($messages_config, $property)
3083
-                        && $messages_config->{$property} !== $value
3084
-                    ) {
3085
-                        $messages_config->{$property} = $value;
3086
-                    }
3087
-                }
3088
-                //only update if the form submission was valid!
3089
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3090
-                EE_Registry::instance()->CFG->update_espresso_config();
3091
-                EE_Error::overwrite_success();
3092
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3093
-            }
3094
-        }
3095
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3096
-    }
3097
-    
3098
-    
3099
-    /**
3100
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3101
-     *
3102
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3103
-     *
3104
-     * @return string            html formatted tabs
3105
-     */
3106
-    protected function _get_mt_tabs($tab_array)
3107
-    {
3108
-        $tab_array = (array)$tab_array;
3109
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3110
-        $tabs      = '';
3111
-        
3112
-        foreach ($tab_array as $tab) {
3113
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3114
-        }
3115
-        
3116
-        return $tabs;
3117
-    }
3118
-    
3119
-    
3120
-    /**
3121
-     * This prepares the content of the messenger meta box admin settings
3122
-     *
3123
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3124
-     *
3125
-     * @return string            html formatted content
3126
-     */
3127
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3128
-    {
3129
-        
3130
-        $fields                                         = $messenger->get_admin_settings_fields();
3131
-        $settings_template_args['template_form_fields'] = '';
3132
-        
3133
-        //is $messenger active?
3134
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3135
-        
3136
-        
3137
-        if ( ! empty($fields)) {
3043
+							)
3044
+						),
3045
+						'update_settings'             => new EE_Submit_Input(
3046
+							array(
3047
+								'default'         => esc_html__('Update', 'event_espresso'),
3048
+								'html_label_text' => '&nbsp'
3049
+							)
3050
+						)
3051
+					)
3052
+				)
3053
+			)
3054
+		);
3055
+	}
3056
+    
3057
+    
3058
+	/**
3059
+	 * This handles updating the global settings set on the admin page.
3060
+	 * @throws \EE_Error
3061
+	 */
3062
+	protected function _update_global_settings()
3063
+	{
3064
+		/** @var EE_Network_Core_Config $network_config */
3065
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3066
+		$messages_config = EE_Registry::instance()->CFG->messages;
3067
+		$form           = $this->_generate_global_settings_form();
3068
+		if ($form->was_submitted()) {
3069
+			$form->receive_form_submission();
3070
+			if ($form->is_valid()) {
3071
+				$valid_data = $form->valid_data();
3072
+				foreach ($valid_data as $property => $value) {
3073
+					$setter = 'set_' . $property;
3074
+					if (method_exists($network_config, $setter)) {
3075
+						$network_config->{$setter}($value);
3076
+					} else if (
3077
+						property_exists($network_config, $property)
3078
+						&& $network_config->{$property} !== $value
3079
+					) {
3080
+						$network_config->{$property} = $value;
3081
+					} else if (
3082
+						property_exists($messages_config, $property)
3083
+						&& $messages_config->{$property} !== $value
3084
+					) {
3085
+						$messages_config->{$property} = $value;
3086
+					}
3087
+				}
3088
+				//only update if the form submission was valid!
3089
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3090
+				EE_Registry::instance()->CFG->update_espresso_config();
3091
+				EE_Error::overwrite_success();
3092
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3093
+			}
3094
+		}
3095
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3096
+	}
3097
+    
3098
+    
3099
+	/**
3100
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3101
+	 *
3102
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3103
+	 *
3104
+	 * @return string            html formatted tabs
3105
+	 */
3106
+	protected function _get_mt_tabs($tab_array)
3107
+	{
3108
+		$tab_array = (array)$tab_array;
3109
+		$template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3110
+		$tabs      = '';
3111
+        
3112
+		foreach ($tab_array as $tab) {
3113
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3114
+		}
3115
+        
3116
+		return $tabs;
3117
+	}
3118
+    
3119
+    
3120
+	/**
3121
+	 * This prepares the content of the messenger meta box admin settings
3122
+	 *
3123
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3124
+	 *
3125
+	 * @return string            html formatted content
3126
+	 */
3127
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3128
+	{
3129
+        
3130
+		$fields                                         = $messenger->get_admin_settings_fields();
3131
+		$settings_template_args['template_form_fields'] = '';
3132
+        
3133
+		//is $messenger active?
3134
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3135
+        
3136
+        
3137
+		if ( ! empty($fields)) {
3138 3138
             
3139
-            $existing_settings = $messenger->get_existing_admin_settings();
3139
+			$existing_settings = $messenger->get_existing_admin_settings();
3140 3140
             
3141
-            foreach ($fields as $fldname => $fldprops) {
3142
-                $field_id                       = $messenger->name . '-' . $fldname;
3143
-                $template_form_field[$field_id] = array(
3144
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3145
-                    'label'      => $fldprops['label'],
3146
-                    'input'      => $fldprops['field_type'],
3147
-                    'type'       => $fldprops['value_type'],
3148
-                    'required'   => $fldprops['required'],
3149
-                    'validation' => $fldprops['validation'],
3150
-                    'value'      => isset($existing_settings[$field_id])
3151
-                        ? $existing_settings[$field_id]
3152
-                        : $fldprops['default'],
3153
-                    'css_class'  => '',
3154
-                    'format'     => $fldprops['format']
3155
-                );
3156
-            }
3141
+			foreach ($fields as $fldname => $fldprops) {
3142
+				$field_id                       = $messenger->name . '-' . $fldname;
3143
+				$template_form_field[$field_id] = array(
3144
+					'name'       => 'messenger_settings[' . $field_id . ']',
3145
+					'label'      => $fldprops['label'],
3146
+					'input'      => $fldprops['field_type'],
3147
+					'type'       => $fldprops['value_type'],
3148
+					'required'   => $fldprops['required'],
3149
+					'validation' => $fldprops['validation'],
3150
+					'value'      => isset($existing_settings[$field_id])
3151
+						? $existing_settings[$field_id]
3152
+						: $fldprops['default'],
3153
+					'css_class'  => '',
3154
+					'format'     => $fldprops['format']
3155
+				);
3156
+			}
3157 3157
             
3158 3158
             
3159
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3160
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3161
-                : '';
3162
-        }
3163
-        
3164
-        //we also need some hidden fields
3165
-        $settings_template_args['hidden_fields'] = array(
3166
-            'messenger_settings[messenger]' => array(
3167
-                'type'  => 'hidden',
3168
-                'value' => $messenger->name
3169
-            ),
3170
-            'type'                          => array(
3171
-                'type'  => 'hidden',
3172
-                'value' => 'messenger'
3173
-            )
3174
-        );
3175
-        
3176
-        //make sure any active message types that are existing are included in the hidden fields
3177
-        if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3178
-            foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3179
-                $settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3180
-                    'type'  => 'hidden',
3181
-                    'value' => $mt
3182
-                );
3183
-            }
3184
-        }
3185
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3186
-            $settings_template_args['hidden_fields'],
3187
-            'array'
3188
-        );
3189
-        $active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3190
-        
3191
-        $settings_template_args['messenger']           = $messenger->name;
3192
-        $settings_template_args['description']         = $messenger->description;
3193
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3194
-        
3195
-        
3196
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active($messenger->name)
3197
-            ? $settings_template_args['show_hide_edit_form']
3198
-            : ' hidden';
3199
-        
3200
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3201
-            ? ' hidden'
3202
-            : $settings_template_args['show_hide_edit_form'];
3203
-        
3204
-        
3205
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3206
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3207
-        $settings_template_args['on_off_status'] = $active ? true : false;
3208
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3209
-        $content                                 = EEH_Template::display_template($template, $settings_template_args,
3210
-            true);
3211
-        
3212
-        return $content;
3213
-    }
3214
-    
3215
-    
3216
-    /**
3217
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3218
-     */
3219
-    public function activate_messenger_toggle()
3220
-    {
3221
-        $success = true;
3222
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3223
-        //let's check that we have required data
3224
-        if ( ! isset($this->_req_data['messenger'])) {
3225
-            EE_Error::add_error(
3226
-                __('Messenger name needed to toggle activation. None given', 'event_espresso'),
3227
-                __FILE__,
3228
-                __FUNCTION__,
3229
-                __LINE__
3230
-            );
3231
-            $success = false;
3232
-        }
3233
-        
3234
-        //do a nonce check here since we're not arriving via a normal route
3235
-        $nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3236
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3237
-        
3238
-        $this->_verify_nonce($nonce, $nonce_ref);
3239
-        
3240
-        
3241
-        if ( ! isset($this->_req_data['status'])) {
3242
-            EE_Error::add_error(
3243
-                __(
3244
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3245
-                    'event_espresso'
3246
-                ),
3247
-                __FILE__,
3248
-                __FUNCTION__,
3249
-                __LINE__
3250
-            );
3251
-            $success = false;
3252
-        }
3253
-        
3254
-        //do check to verify we have a valid status.
3255
-        $status = $this->_req_data['status'];
3256
-        
3257
-        if ($status != 'off' && $status != 'on') {
3258
-            EE_Error::add_error(
3259
-                sprintf(
3260
-                    __('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3261
-                    $this->_req_data['status']
3262
-                ),
3263
-                __FILE__,
3264
-                __FUNCTION__,
3265
-                __LINE__
3266
-            );
3267
-            $success = false;
3268
-        }
3269
-        
3270
-        if ($success) {
3271
-            //made it here?  Stop dawdling then!!
3272
-            $success = $status == 'off'
3273
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3274
-                : $this->_activate_messenger($this->_req_data['messenger']);
3275
-        }
3276
-        
3277
-        $this->_template_args['success'] = $success;
3278
-        
3279
-        //no special instructions so let's just do the json return (which should automatically do all the special stuff).
3280
-        $this->_return_json();
3281
-        
3282
-    }
3283
-    
3284
-    
3285
-    /**
3286
-     * used by ajax from the messages settings page to activate|deactivate a message type
3287
-     *
3288
-     */
3289
-    public function activate_mt_toggle()
3290
-    {
3291
-        $success = true;
3292
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3293
-        
3294
-        //let's make sure we have the necessary data
3295
-        if ( ! isset($this->_req_data['message_type'])) {
3296
-            EE_Error::add_error(
3297
-                __('Message Type name needed to toggle activation. None given', 'event_espresso'),
3298
-                __FILE__, __FUNCTION__, __LINE__
3299
-            );
3300
-            $success = false;
3301
-        }
3302
-        
3303
-        if ( ! isset($this->_req_data['messenger'])) {
3304
-            EE_Error::add_error(
3305
-                __('Messenger name needed to toggle activation. None given', 'event_espresso'),
3306
-                __FILE__, __FUNCTION__, __LINE__
3307
-            );
3308
-            $success = false;
3309
-        }
3310
-        
3311
-        if ( ! isset($this->_req_data['status'])) {
3312
-            EE_Error::add_error(
3313
-                __('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3314
-                    'event_espresso'),
3315
-                __FILE__, __FUNCTION__, __LINE__
3316
-            );
3317
-            $success = false;
3318
-        }
3319
-        
3320
-        
3321
-        //do check to verify we have a valid status.
3322
-        $status = $this->_req_data['status'];
3323
-        
3324
-        if ($status != 'activate' && $status != 'deactivate') {
3325
-            EE_Error::add_error(
3326
-                sprintf(
3327
-                    __('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3328
-                    $this->_req_data['status']
3329
-                ),
3330
-                __FILE__, __FUNCTION__, __LINE__
3331
-            );
3332
-            $success = false;
3333
-        }
3334
-        
3335
-        
3336
-        //do a nonce check here since we're not arriving via a normal route
3337
-        $nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3338
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3339
-        
3340
-        $this->_verify_nonce($nonce, $nonce_ref);
3341
-        
3342
-        if ($success) {
3343
-            //made it here? um, what are you waiting for then?
3344
-            $success = $status == 'deactivate'
3345
-                ? $this->_deactivate_message_type_for_messenger($this->_req_data['messenger'],
3346
-                    $this->_req_data['message_type'])
3347
-                : $this->_activate_message_type_for_messenger($this->_req_data['messenger'],
3348
-                    $this->_req_data['message_type']);
3349
-        }
3350
-        
3351
-        $this->_template_args['success'] = $success;
3352
-        $this->_return_json();
3353
-    }
3354
-    
3355
-    
3356
-    /**
3357
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3358
-     *
3359
-     * @param string $messenger_name The name of the messenger being activated
3360
-     *
3361
-     * @return bool
3362
-     */
3363
-    protected function _activate_messenger($messenger_name)
3364
-    {
3365
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3366
-        $active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3367
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger ? $active_messenger->get_default_message_types() : array();
3368
-        
3369
-        //ensure is active
3370
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3371
-        
3372
-        //set response_data for reload
3373
-        foreach ($message_types_to_activate as $message_type_name) {
3374
-            /** @var EE_message_type $message_type */
3375
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3376
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3377
-                    $message_type_name)
3378
-                && $message_type instanceof EE_message_type
3379
-            ) {
3380
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
3381
-                if ($message_type->get_admin_settings_fields()) {
3382
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
3383
-                }
3384
-            }
3385
-        }
3386
-        
3387
-        //add success message for activating messenger
3388
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3389
-        
3390
-    }
3391
-    
3392
-    
3393
-    /**
3394
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
3395
-     *
3396
-     * @param string $messenger_name The name of the messenger being activated
3397
-     *
3398
-     * @return bool
3399
-     */
3400
-    protected function _deactivate_messenger($messenger_name)
3401
-    {
3402
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3403
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3404
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
3405
-        
3406
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3407
-    }
3408
-    
3409
-    
3410
-    /**
3411
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3412
-     *
3413
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
3414
-     * @param string $message_type_name The name of the message type being activated for the messenger
3415
-     *
3416
-     * @return bool
3417
-     */
3418
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3419
-    {
3420
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3421
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3422
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3423
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3424
-        
3425
-        //ensure is active
3426
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3427
-        
3428
-        //set response for load
3429
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3430
-            $message_type_name)
3431
-        ) {
3432
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
3433
-            if ($message_type_to_activate->get_admin_settings_fields()) {
3434
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
3435
-            }
3436
-        }
3437
-        
3438
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3439
-            $message_type_to_activate);
3440
-    }
3441
-    
3442
-    
3443
-    /**
3444
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3445
-     *
3446
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3447
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
3448
-     *
3449
-     * @return bool
3450
-     */
3451
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
3452
-    {
3453
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3454
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3455
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3456
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
3457
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
3458
-        
3459
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
3460
-            $message_type_to_deactivate);
3461
-    }
3462
-    
3463
-    
3464
-    /**
3465
-     * This just initializes the defaults for activating messenger and message type responses.
3466
-     */
3467
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
3468
-    {
3469
-        $this->_template_args['data']['active_mts'] = array();
3470
-        $this->_template_args['data']['mt_reload']  = array();
3471
-    }
3472
-    
3473
-    
3474
-    /**
3475
-     * Setup appropriate response for activating a messenger and/or message types
3476
-     *
3477
-     * @param EE_messenger         $messenger
3478
-     * @param EE_message_type|null $message_type
3479
-     *
3480
-     * @return bool
3481
-     * @throws EE_Error
3482
-     */
3483
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
3484
-        $messenger,
3485
-        EE_Message_Type $message_type = null
3486
-    ) {
3487
-        //if $messenger isn't a valid messenger object then get out.
3488
-        if ( ! $messenger instanceof EE_Messenger) {
3489
-            EE_Error::add_error(
3490
-                __('The messenger being activated is not a valid messenger', 'event_espresso'),
3491
-                __FILE__,
3492
-                __FUNCTION__,
3493
-                __LINE__
3494
-            );
3159
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3160
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3161
+				: '';
3162
+		}
3163
+        
3164
+		//we also need some hidden fields
3165
+		$settings_template_args['hidden_fields'] = array(
3166
+			'messenger_settings[messenger]' => array(
3167
+				'type'  => 'hidden',
3168
+				'value' => $messenger->name
3169
+			),
3170
+			'type'                          => array(
3171
+				'type'  => 'hidden',
3172
+				'value' => 'messenger'
3173
+			)
3174
+		);
3175
+        
3176
+		//make sure any active message types that are existing are included in the hidden fields
3177
+		if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3178
+			foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3179
+				$settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3180
+					'type'  => 'hidden',
3181
+					'value' => $mt
3182
+				);
3183
+			}
3184
+		}
3185
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3186
+			$settings_template_args['hidden_fields'],
3187
+			'array'
3188
+		);
3189
+		$active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3190
+        
3191
+		$settings_template_args['messenger']           = $messenger->name;
3192
+		$settings_template_args['description']         = $messenger->description;
3193
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3194
+        
3195
+        
3196
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active($messenger->name)
3197
+			? $settings_template_args['show_hide_edit_form']
3198
+			: ' hidden';
3199
+        
3200
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3201
+			? ' hidden'
3202
+			: $settings_template_args['show_hide_edit_form'];
3203
+        
3204
+        
3205
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3206
+		$settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3207
+		$settings_template_args['on_off_status'] = $active ? true : false;
3208
+		$template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3209
+		$content                                 = EEH_Template::display_template($template, $settings_template_args,
3210
+			true);
3211
+        
3212
+		return $content;
3213
+	}
3214
+    
3215
+    
3216
+	/**
3217
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3218
+	 */
3219
+	public function activate_messenger_toggle()
3220
+	{
3221
+		$success = true;
3222
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3223
+		//let's check that we have required data
3224
+		if ( ! isset($this->_req_data['messenger'])) {
3225
+			EE_Error::add_error(
3226
+				__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3227
+				__FILE__,
3228
+				__FUNCTION__,
3229
+				__LINE__
3230
+			);
3231
+			$success = false;
3232
+		}
3233
+        
3234
+		//do a nonce check here since we're not arriving via a normal route
3235
+		$nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3236
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3237
+        
3238
+		$this->_verify_nonce($nonce, $nonce_ref);
3239
+        
3240
+        
3241
+		if ( ! isset($this->_req_data['status'])) {
3242
+			EE_Error::add_error(
3243
+				__(
3244
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3245
+					'event_espresso'
3246
+				),
3247
+				__FILE__,
3248
+				__FUNCTION__,
3249
+				__LINE__
3250
+			);
3251
+			$success = false;
3252
+		}
3253
+        
3254
+		//do check to verify we have a valid status.
3255
+		$status = $this->_req_data['status'];
3256
+        
3257
+		if ($status != 'off' && $status != 'on') {
3258
+			EE_Error::add_error(
3259
+				sprintf(
3260
+					__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3261
+					$this->_req_data['status']
3262
+				),
3263
+				__FILE__,
3264
+				__FUNCTION__,
3265
+				__LINE__
3266
+			);
3267
+			$success = false;
3268
+		}
3269
+        
3270
+		if ($success) {
3271
+			//made it here?  Stop dawdling then!!
3272
+			$success = $status == 'off'
3273
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3274
+				: $this->_activate_messenger($this->_req_data['messenger']);
3275
+		}
3276
+        
3277
+		$this->_template_args['success'] = $success;
3278
+        
3279
+		//no special instructions so let's just do the json return (which should automatically do all the special stuff).
3280
+		$this->_return_json();
3281
+        
3282
+	}
3283
+    
3284
+    
3285
+	/**
3286
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3287
+	 *
3288
+	 */
3289
+	public function activate_mt_toggle()
3290
+	{
3291
+		$success = true;
3292
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3293
+        
3294
+		//let's make sure we have the necessary data
3295
+		if ( ! isset($this->_req_data['message_type'])) {
3296
+			EE_Error::add_error(
3297
+				__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3298
+				__FILE__, __FUNCTION__, __LINE__
3299
+			);
3300
+			$success = false;
3301
+		}
3302
+        
3303
+		if ( ! isset($this->_req_data['messenger'])) {
3304
+			EE_Error::add_error(
3305
+				__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3306
+				__FILE__, __FUNCTION__, __LINE__
3307
+			);
3308
+			$success = false;
3309
+		}
3310
+        
3311
+		if ( ! isset($this->_req_data['status'])) {
3312
+			EE_Error::add_error(
3313
+				__('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3314
+					'event_espresso'),
3315
+				__FILE__, __FUNCTION__, __LINE__
3316
+			);
3317
+			$success = false;
3318
+		}
3319
+        
3320
+        
3321
+		//do check to verify we have a valid status.
3322
+		$status = $this->_req_data['status'];
3323
+        
3324
+		if ($status != 'activate' && $status != 'deactivate') {
3325
+			EE_Error::add_error(
3326
+				sprintf(
3327
+					__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3328
+					$this->_req_data['status']
3329
+				),
3330
+				__FILE__, __FUNCTION__, __LINE__
3331
+			);
3332
+			$success = false;
3333
+		}
3334
+        
3335
+        
3336
+		//do a nonce check here since we're not arriving via a normal route
3337
+		$nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3338
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3339
+        
3340
+		$this->_verify_nonce($nonce, $nonce_ref);
3341
+        
3342
+		if ($success) {
3343
+			//made it here? um, what are you waiting for then?
3344
+			$success = $status == 'deactivate'
3345
+				? $this->_deactivate_message_type_for_messenger($this->_req_data['messenger'],
3346
+					$this->_req_data['message_type'])
3347
+				: $this->_activate_message_type_for_messenger($this->_req_data['messenger'],
3348
+					$this->_req_data['message_type']);
3349
+		}
3350
+        
3351
+		$this->_template_args['success'] = $success;
3352
+		$this->_return_json();
3353
+	}
3354
+    
3355
+    
3356
+	/**
3357
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3358
+	 *
3359
+	 * @param string $messenger_name The name of the messenger being activated
3360
+	 *
3361
+	 * @return bool
3362
+	 */
3363
+	protected function _activate_messenger($messenger_name)
3364
+	{
3365
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3366
+		$active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3367
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger ? $active_messenger->get_default_message_types() : array();
3368
+        
3369
+		//ensure is active
3370
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3371
+        
3372
+		//set response_data for reload
3373
+		foreach ($message_types_to_activate as $message_type_name) {
3374
+			/** @var EE_message_type $message_type */
3375
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3376
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3377
+					$message_type_name)
3378
+				&& $message_type instanceof EE_message_type
3379
+			) {
3380
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
3381
+				if ($message_type->get_admin_settings_fields()) {
3382
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
3383
+				}
3384
+			}
3385
+		}
3386
+        
3387
+		//add success message for activating messenger
3388
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3389
+        
3390
+	}
3391
+    
3392
+    
3393
+	/**
3394
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
3395
+	 *
3396
+	 * @param string $messenger_name The name of the messenger being activated
3397
+	 *
3398
+	 * @return bool
3399
+	 */
3400
+	protected function _deactivate_messenger($messenger_name)
3401
+	{
3402
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3403
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3404
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
3405
+        
3406
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3407
+	}
3408
+    
3409
+    
3410
+	/**
3411
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3412
+	 *
3413
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
3414
+	 * @param string $message_type_name The name of the message type being activated for the messenger
3415
+	 *
3416
+	 * @return bool
3417
+	 */
3418
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3419
+	{
3420
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3421
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3422
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3423
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3424
+        
3425
+		//ensure is active
3426
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3427
+        
3428
+		//set response for load
3429
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3430
+			$message_type_name)
3431
+		) {
3432
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
3433
+			if ($message_type_to_activate->get_admin_settings_fields()) {
3434
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
3435
+			}
3436
+		}
3437
+        
3438
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3439
+			$message_type_to_activate);
3440
+	}
3441
+    
3442
+    
3443
+	/**
3444
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3445
+	 *
3446
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3447
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
3448
+	 *
3449
+	 * @return bool
3450
+	 */
3451
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
3452
+	{
3453
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3454
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3455
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3456
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
3457
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
3458
+        
3459
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
3460
+			$message_type_to_deactivate);
3461
+	}
3462
+    
3463
+    
3464
+	/**
3465
+	 * This just initializes the defaults for activating messenger and message type responses.
3466
+	 */
3467
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
3468
+	{
3469
+		$this->_template_args['data']['active_mts'] = array();
3470
+		$this->_template_args['data']['mt_reload']  = array();
3471
+	}
3472
+    
3473
+    
3474
+	/**
3475
+	 * Setup appropriate response for activating a messenger and/or message types
3476
+	 *
3477
+	 * @param EE_messenger         $messenger
3478
+	 * @param EE_message_type|null $message_type
3479
+	 *
3480
+	 * @return bool
3481
+	 * @throws EE_Error
3482
+	 */
3483
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
3484
+		$messenger,
3485
+		EE_Message_Type $message_type = null
3486
+	) {
3487
+		//if $messenger isn't a valid messenger object then get out.
3488
+		if ( ! $messenger instanceof EE_Messenger) {
3489
+			EE_Error::add_error(
3490
+				__('The messenger being activated is not a valid messenger', 'event_espresso'),
3491
+				__FILE__,
3492
+				__FUNCTION__,
3493
+				__LINE__
3494
+			);
3495 3495
             
3496
-            return false;
3497
-        }
3498
-        //activated
3499
-        if ($this->_template_args['data']['active_mts']) {
3500
-            EE_Error::overwrite_success();
3501
-            //activated a message type with the messenger
3502
-            if ($message_type instanceof EE_message_type) {
3503
-                EE_Error::add_success(
3504
-                    sprintf(
3505
-                        __('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
3506
-                        ucwords($message_type->label['singular']),
3507
-                        ucwords($messenger->label['singular'])
3508
-                    )
3509
-                );
3496
+			return false;
3497
+		}
3498
+		//activated
3499
+		if ($this->_template_args['data']['active_mts']) {
3500
+			EE_Error::overwrite_success();
3501
+			//activated a message type with the messenger
3502
+			if ($message_type instanceof EE_message_type) {
3503
+				EE_Error::add_success(
3504
+					sprintf(
3505
+						__('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
3506
+						ucwords($message_type->label['singular']),
3507
+						ucwords($messenger->label['singular'])
3508
+					)
3509
+				);
3510 3510
                 
3511
-                //if message type was invoice then let's make sure we activate the invoice payment method.
3512
-                if ($message_type->name == 'invoice') {
3513
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
3514
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
3515
-                    if ($pm instanceof EE_Payment_Method) {
3516
-                        EE_Error::add_attention(__('Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
3517
-                            'event_espresso'));
3518
-                    }
3519
-                }
3520
-                //just toggles the entire messenger
3521
-            } else {
3522
-                EE_Error::add_success(
3523
-                    sprintf(
3524
-                        __('%s messenger has been successfully activated', 'event_espresso'),
3525
-                        ucwords($messenger->label['singular'])
3526
-                    )
3527
-                );
3528
-            }
3511
+				//if message type was invoice then let's make sure we activate the invoice payment method.
3512
+				if ($message_type->name == 'invoice') {
3513
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
3514
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
3515
+					if ($pm instanceof EE_Payment_Method) {
3516
+						EE_Error::add_attention(__('Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
3517
+							'event_espresso'));
3518
+					}
3519
+				}
3520
+				//just toggles the entire messenger
3521
+			} else {
3522
+				EE_Error::add_success(
3523
+					sprintf(
3524
+						__('%s messenger has been successfully activated', 'event_espresso'),
3525
+						ucwords($messenger->label['singular'])
3526
+					)
3527
+				);
3528
+			}
3529 3529
             
3530
-            return true;
3530
+			return true;
3531 3531
             
3532
-            //possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
3533
-            //message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
3534
-            //in which case we just give a success message for the messenger being successfully activated.
3535
-        } else {
3536
-            if ( ! $messenger->get_default_message_types()) {
3537
-                //messenger doesn't have any default message types so still a success.
3538
-                EE_Error::add_success(
3539
-                    sprintf(
3540
-                        __('%s messenger was successfully activated.', 'event_espresso'),
3541
-                        ucwords($messenger->label['singular'])
3542
-                    )
3543
-                );
3532
+			//possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
3533
+			//message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
3534
+			//in which case we just give a success message for the messenger being successfully activated.
3535
+		} else {
3536
+			if ( ! $messenger->get_default_message_types()) {
3537
+				//messenger doesn't have any default message types so still a success.
3538
+				EE_Error::add_success(
3539
+					sprintf(
3540
+						__('%s messenger was successfully activated.', 'event_espresso'),
3541
+						ucwords($messenger->label['singular'])
3542
+					)
3543
+				);
3544 3544
                 
3545
-                return true;
3546
-            } else {
3547
-                EE_Error::add_error(
3548
-                    $message_type instanceof EE_message_type
3549
-                        ? sprintf(
3550
-                        __('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
3551
-                        ucwords($message_type->label['singular']),
3552
-                        ucwords($messenger->label['singular'])
3553
-                    )
3554
-                        : sprintf(
3555
-                        __('%s messenger was not successfully activated', 'event_espresso'),
3556
-                        ucwords($messenger->label['singular'])
3557
-                    ),
3558
-                    __FILE__,
3559
-                    __FUNCTION__,
3560
-                    __LINE__
3561
-                );
3545
+				return true;
3546
+			} else {
3547
+				EE_Error::add_error(
3548
+					$message_type instanceof EE_message_type
3549
+						? sprintf(
3550
+						__('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
3551
+						ucwords($message_type->label['singular']),
3552
+						ucwords($messenger->label['singular'])
3553
+					)
3554
+						: sprintf(
3555
+						__('%s messenger was not successfully activated', 'event_espresso'),
3556
+						ucwords($messenger->label['singular'])
3557
+					),
3558
+					__FILE__,
3559
+					__FUNCTION__,
3560
+					__LINE__
3561
+				);
3562 3562
                 
3563
-                return false;
3564
-            }
3565
-        }
3566
-    }
3567
-    
3568
-    
3569
-    /**
3570
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
3571
-     *
3572
-     * @param EE_messenger         $messenger
3573
-     * @param EE_message_type|null $message_type
3574
-     *
3575
-     * @return bool
3576
-     */
3577
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
3578
-        $messenger,
3579
-        EE_message_type $message_type = null
3580
-    ) {
3581
-        EE_Error::overwrite_success();
3582
-        
3583
-        //if $messenger isn't a valid messenger object then get out.
3584
-        if ( ! $messenger instanceof EE_Messenger) {
3585
-            EE_Error::add_error(
3586
-                __('The messenger being deactivated is not a valid messenger', 'event_espresso'),
3587
-                __FILE__,
3588
-                __FUNCTION__,
3589
-                __LINE__
3590
-            );
3563
+				return false;
3564
+			}
3565
+		}
3566
+	}
3567
+    
3568
+    
3569
+	/**
3570
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
3571
+	 *
3572
+	 * @param EE_messenger         $messenger
3573
+	 * @param EE_message_type|null $message_type
3574
+	 *
3575
+	 * @return bool
3576
+	 */
3577
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
3578
+		$messenger,
3579
+		EE_message_type $message_type = null
3580
+	) {
3581
+		EE_Error::overwrite_success();
3582
+        
3583
+		//if $messenger isn't a valid messenger object then get out.
3584
+		if ( ! $messenger instanceof EE_Messenger) {
3585
+			EE_Error::add_error(
3586
+				__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
3587
+				__FILE__,
3588
+				__FUNCTION__,
3589
+				__LINE__
3590
+			);
3591 3591
             
3592
-            return false;
3593
-        }
3594
-        
3595
-        if ($message_type instanceof EE_message_type) {
3596
-            $message_type_name = $message_type->name;
3597
-            EE_Error::add_success(
3598
-                sprintf(
3599
-                    __('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
3600
-                    ucwords($message_type->label['singular']),
3601
-                    ucwords($messenger->label['singular'])
3602
-                )
3603
-            );
3604
-        } else {
3605
-            $message_type_name = '';
3606
-            EE_Error::add_success(
3607
-                sprintf(
3608
-                    __('%s messenger has been successfully deactivated.', 'event_espresso'),
3609
-                    ucwords($messenger->label['singular'])
3610
-                )
3611
-            );
3612
-        }
3613
-        
3614
-        //if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
3615
-        if ($messenger->name == 'html' || $message_type_name == 'invoice') {
3616
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
3617
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
3618
-            if ($count_updated > 0) {
3619
-                $msg = $message_type_name == 'invoice'
3620
-                    ? __('Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
3621
-                        'event_espresso')
3622
-                    : __('Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
3623
-                        'event_espresso');
3624
-                EE_Error::add_attention($msg);
3625
-            }
3626
-        }
3627
-        
3628
-        return true;
3629
-    }
3630
-    
3631
-    
3632
-    /**
3633
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
3634
-     */
3635
-    public function update_mt_form()
3636
-    {
3637
-        if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
3638
-            EE_Error::add_error(__('Require message type or messenger to send an updated form'), __FILE__, __FUNCTION__,
3639
-                __LINE__);
3640
-            $this->_return_json();
3641
-        }
3642
-        
3643
-        $message_types = $this->get_installed_message_types();
3644
-        
3645
-        $message_type = $message_types[$this->_req_data['message_type']];
3646
-        $messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
3647
-        
3648
-        $content                         = $this->_message_type_settings_content($message_type, $messenger, true);
3649
-        $this->_template_args['success'] = true;
3650
-        $this->_template_args['content'] = $content;
3651
-        $this->_return_json();
3652
-    }
3653
-    
3654
-    
3655
-    /**
3656
-     * this handles saving the settings for a messenger or message type
3657
-     *
3658
-     */
3659
-    public function save_settings()
3660
-    {
3661
-        if ( ! isset($this->_req_data['type'])) {
3662
-            EE_Error::add_error(__('Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
3663
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3664
-            $this->_template_args['error'] = true;
3665
-            $this->_return_json();
3666
-        }
3667
-        
3668
-        
3669
-        if ($this->_req_data['type'] == 'messenger') {
3670
-            $settings  = $this->_req_data['messenger_settings']; //this should be an array.
3671
-            $messenger = $settings['messenger'];
3672
-            //let's setup the settings data
3673
-            foreach ($settings as $key => $value) {
3674
-                switch ($key) {
3675
-                    case 'messenger' :
3676
-                        unset($settings['messenger']);
3677
-                        break;
3678
-                    case 'message_types' :
3679
-                        unset($settings['message_types']);
3680
-                        break;
3681
-                    default :
3682
-                        $settings[$key] = $value;
3683
-                        break;
3684
-                }
3685
-            }
3686
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
3687
-        } else if ($this->_req_data['type'] == 'message_type') {
3688
-            $settings     = $this->_req_data['message_type_settings'];
3689
-            $messenger    = $settings['messenger'];
3690
-            $message_type = $settings['message_type'];
3592
+			return false;
3593
+		}
3594
+        
3595
+		if ($message_type instanceof EE_message_type) {
3596
+			$message_type_name = $message_type->name;
3597
+			EE_Error::add_success(
3598
+				sprintf(
3599
+					__('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
3600
+					ucwords($message_type->label['singular']),
3601
+					ucwords($messenger->label['singular'])
3602
+				)
3603
+			);
3604
+		} else {
3605
+			$message_type_name = '';
3606
+			EE_Error::add_success(
3607
+				sprintf(
3608
+					__('%s messenger has been successfully deactivated.', 'event_espresso'),
3609
+					ucwords($messenger->label['singular'])
3610
+				)
3611
+			);
3612
+		}
3613
+        
3614
+		//if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
3615
+		if ($messenger->name == 'html' || $message_type_name == 'invoice') {
3616
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
3617
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
3618
+			if ($count_updated > 0) {
3619
+				$msg = $message_type_name == 'invoice'
3620
+					? __('Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
3621
+						'event_espresso')
3622
+					: __('Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
3623
+						'event_espresso');
3624
+				EE_Error::add_attention($msg);
3625
+			}
3626
+		}
3627
+        
3628
+		return true;
3629
+	}
3630
+    
3631
+    
3632
+	/**
3633
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
3634
+	 */
3635
+	public function update_mt_form()
3636
+	{
3637
+		if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
3638
+			EE_Error::add_error(__('Require message type or messenger to send an updated form'), __FILE__, __FUNCTION__,
3639
+				__LINE__);
3640
+			$this->_return_json();
3641
+		}
3642
+        
3643
+		$message_types = $this->get_installed_message_types();
3644
+        
3645
+		$message_type = $message_types[$this->_req_data['message_type']];
3646
+		$messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
3647
+        
3648
+		$content                         = $this->_message_type_settings_content($message_type, $messenger, true);
3649
+		$this->_template_args['success'] = true;
3650
+		$this->_template_args['content'] = $content;
3651
+		$this->_return_json();
3652
+	}
3653
+    
3654
+    
3655
+	/**
3656
+	 * this handles saving the settings for a messenger or message type
3657
+	 *
3658
+	 */
3659
+	public function save_settings()
3660
+	{
3661
+		if ( ! isset($this->_req_data['type'])) {
3662
+			EE_Error::add_error(__('Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
3663
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3664
+			$this->_template_args['error'] = true;
3665
+			$this->_return_json();
3666
+		}
3667
+        
3668
+        
3669
+		if ($this->_req_data['type'] == 'messenger') {
3670
+			$settings  = $this->_req_data['messenger_settings']; //this should be an array.
3671
+			$messenger = $settings['messenger'];
3672
+			//let's setup the settings data
3673
+			foreach ($settings as $key => $value) {
3674
+				switch ($key) {
3675
+					case 'messenger' :
3676
+						unset($settings['messenger']);
3677
+						break;
3678
+					case 'message_types' :
3679
+						unset($settings['message_types']);
3680
+						break;
3681
+					default :
3682
+						$settings[$key] = $value;
3683
+						break;
3684
+				}
3685
+			}
3686
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
3687
+		} else if ($this->_req_data['type'] == 'message_type') {
3688
+			$settings     = $this->_req_data['message_type_settings'];
3689
+			$messenger    = $settings['messenger'];
3690
+			$message_type = $settings['message_type'];
3691 3691
             
3692
-            foreach ($settings as $key => $value) {
3693
-                switch ($key) {
3694
-                    case 'messenger' :
3695
-                        unset($settings['messenger']);
3696
-                        break;
3697
-                    case 'message_type' :
3698
-                        unset($settings['message_type']);
3699
-                        break;
3700
-                    default :
3701
-                        $settings[$key] = $value;
3702
-                        break;
3703
-                }
3704
-            }
3692
+			foreach ($settings as $key => $value) {
3693
+				switch ($key) {
3694
+					case 'messenger' :
3695
+						unset($settings['messenger']);
3696
+						break;
3697
+					case 'message_type' :
3698
+						unset($settings['message_type']);
3699
+						break;
3700
+					default :
3701
+						$settings[$key] = $value;
3702
+						break;
3703
+				}
3704
+			}
3705 3705
             
3706
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
3707
-        }
3708
-        
3709
-        //okay we should have the data all setup.  Now we just update!
3710
-        $success = $this->_message_resource_manager->update_active_messengers_option();
3711
-        
3712
-        if ($success) {
3713
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
3714
-        } else {
3715
-            EE_Error::add_error(__('Settings did not get updated', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3716
-        }
3717
-        
3718
-        $this->_template_args['success'] = $success;
3719
-        $this->_return_json();
3720
-    }
3721
-    
3722
-    
3723
-    
3724
-    
3725
-    /**  EE MESSAGE PROCESSING ACTIONS **/
3726
-    
3727
-    
3728
-    /**
3729
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
3730
-     * However, this does not send immediately, it just queues for sending.
3731
-     *
3732
-     * @since 4.9.0
3733
-     */
3734
-    protected function _generate_now()
3735
-    {
3736
-        $msg_ids = $this->_get_msg_ids_from_request();
3737
-        EED_Messages::generate_now($msg_ids);
3738
-        $this->_redirect_after_action(false, '', '', array(), true);
3739
-    }
3740
-    
3741
-    
3742
-    /**
3743
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
3744
-     * are EEM_Message::status_resend or EEM_Message::status_idle
3745
-     *
3746
-     * @since 4.9.0
3747
-     *
3748
-     */
3749
-    protected function _generate_and_send_now()
3750
-    {
3751
-        $this->_generate_now();
3752
-        $this->_send_now();
3753
-        $this->_redirect_after_action(false, '', '', array(), true);
3754
-    }
3755
-    
3756
-    
3757
-    /**
3758
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
3759
-     *
3760
-     * @since 4.9.0
3761
-     */
3762
-    protected function _queue_for_resending()
3763
-    {
3764
-        $msg_ids = $this->_get_msg_ids_from_request();
3765
-        EED_Messages::queue_for_resending($msg_ids);
3766
-        $this->_redirect_after_action(false, '', '', array(), true);
3767
-    }
3768
-    
3769
-    
3770
-    /**
3771
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
3772
-     *
3773
-     * @since 4.9.0
3774
-     */
3775
-    protected function _send_now()
3776
-    {
3777
-        $msg_ids = $this->_get_msg_ids_from_request();
3778
-        EED_Messages::send_now($msg_ids);
3779
-        $this->_redirect_after_action(false, '', '', array(), true);
3780
-    }
3781
-    
3782
-    
3783
-    /**
3784
-     * Deletes EE_messages for IDs in the request.
3785
-     *
3786
-     * @since 4.9.0
3787
-     */
3788
-    protected function _delete_ee_messages()
3789
-    {
3790
-        $msg_ids       = $this->_get_msg_ids_from_request();
3791
-        $deleted_count = 0;
3792
-        foreach ($msg_ids as $msg_id) {
3793
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
3794
-                $deleted_count++;
3795
-            }
3796
-        }
3797
-        if ($deleted_count) {
3798
-            $this->_redirect_after_action(
3799
-                true,
3800
-                _n('message', 'messages', $deleted_count, 'event_espresso'),
3801
-                __('deleted', 'event_espresso')
3802
-            );
3803
-        } else {
3804
-            EE_Error::add_error(
3805
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
3806
-                __FILE__, __FUNCTION__, __LINE__
3807
-            );
3808
-            $this->_redirect_after_action(false, '', '', array(), true);
3809
-        }
3810
-    }
3811
-    
3812
-    
3813
-    /**
3814
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
3815
-     * @since 4.9.0
3816
-     * @return array
3817
-     */
3818
-    protected function _get_msg_ids_from_request()
3819
-    {
3820
-        if ( ! isset($this->_req_data['MSG_ID'])) {
3821
-            return array();
3822
-        }
3823
-        
3824
-        return is_array($this->_req_data['MSG_ID']) ? array_keys($this->_req_data['MSG_ID']) : array($this->_req_data['MSG_ID']);
3825
-    }
3706
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
3707
+		}
3708
+        
3709
+		//okay we should have the data all setup.  Now we just update!
3710
+		$success = $this->_message_resource_manager->update_active_messengers_option();
3711
+        
3712
+		if ($success) {
3713
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
3714
+		} else {
3715
+			EE_Error::add_error(__('Settings did not get updated', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3716
+		}
3717
+        
3718
+		$this->_template_args['success'] = $success;
3719
+		$this->_return_json();
3720
+	}
3721
+    
3722
+    
3723
+    
3724
+    
3725
+	/**  EE MESSAGE PROCESSING ACTIONS **/
3726
+    
3727
+    
3728
+	/**
3729
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
3730
+	 * However, this does not send immediately, it just queues for sending.
3731
+	 *
3732
+	 * @since 4.9.0
3733
+	 */
3734
+	protected function _generate_now()
3735
+	{
3736
+		$msg_ids = $this->_get_msg_ids_from_request();
3737
+		EED_Messages::generate_now($msg_ids);
3738
+		$this->_redirect_after_action(false, '', '', array(), true);
3739
+	}
3740
+    
3741
+    
3742
+	/**
3743
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
3744
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
3745
+	 *
3746
+	 * @since 4.9.0
3747
+	 *
3748
+	 */
3749
+	protected function _generate_and_send_now()
3750
+	{
3751
+		$this->_generate_now();
3752
+		$this->_send_now();
3753
+		$this->_redirect_after_action(false, '', '', array(), true);
3754
+	}
3755
+    
3756
+    
3757
+	/**
3758
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
3759
+	 *
3760
+	 * @since 4.9.0
3761
+	 */
3762
+	protected function _queue_for_resending()
3763
+	{
3764
+		$msg_ids = $this->_get_msg_ids_from_request();
3765
+		EED_Messages::queue_for_resending($msg_ids);
3766
+		$this->_redirect_after_action(false, '', '', array(), true);
3767
+	}
3768
+    
3769
+    
3770
+	/**
3771
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
3772
+	 *
3773
+	 * @since 4.9.0
3774
+	 */
3775
+	protected function _send_now()
3776
+	{
3777
+		$msg_ids = $this->_get_msg_ids_from_request();
3778
+		EED_Messages::send_now($msg_ids);
3779
+		$this->_redirect_after_action(false, '', '', array(), true);
3780
+	}
3781
+    
3782
+    
3783
+	/**
3784
+	 * Deletes EE_messages for IDs in the request.
3785
+	 *
3786
+	 * @since 4.9.0
3787
+	 */
3788
+	protected function _delete_ee_messages()
3789
+	{
3790
+		$msg_ids       = $this->_get_msg_ids_from_request();
3791
+		$deleted_count = 0;
3792
+		foreach ($msg_ids as $msg_id) {
3793
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
3794
+				$deleted_count++;
3795
+			}
3796
+		}
3797
+		if ($deleted_count) {
3798
+			$this->_redirect_after_action(
3799
+				true,
3800
+				_n('message', 'messages', $deleted_count, 'event_espresso'),
3801
+				__('deleted', 'event_espresso')
3802
+			);
3803
+		} else {
3804
+			EE_Error::add_error(
3805
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
3806
+				__FILE__, __FUNCTION__, __LINE__
3807
+			);
3808
+			$this->_redirect_after_action(false, '', '', array(), true);
3809
+		}
3810
+	}
3811
+    
3812
+    
3813
+	/**
3814
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
3815
+	 * @since 4.9.0
3816
+	 * @return array
3817
+	 */
3818
+	protected function _get_msg_ids_from_request()
3819
+	{
3820
+		if ( ! isset($this->_req_data['MSG_ID'])) {
3821
+			return array();
3822
+		}
3823
+        
3824
+		return is_array($this->_req_data['MSG_ID']) ? array_keys($this->_req_data['MSG_ID']) : array($this->_req_data['MSG_ID']);
3825
+	}
3826 3826
     
3827 3827
     
3828 3828
 }
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Shortcode.lib.php 2 patches
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -27,89 +27,89 @@  discard block
 block discarded – undo
27 27
 class EE_Register_Shortcode implements EEI_Plugin_API
28 28
 {
29 29
 
30
-    /**
31
-     * Holds values for registered shortcodes
32
-     *
33
-     * @var array
34
-     */
35
-    protected static $_settings = array();
30
+	/**
31
+	 * Holds values for registered shortcodes
32
+	 *
33
+	 * @var array
34
+	 */
35
+	protected static $_settings = array();
36 36
 
37 37
 
38
-    /**
39
-     *    Method for registering new EE_Shortcodes
40
-     *
41
-     * @since    4.3.0
42
-     * @param string $shortcode_id a unique identifier for this set of modules Required.
43
-     * @param  array $setup_args   an array of arguments provided for registering shortcodes Required.
44
-     * @type array shortcode_paths        an array of full server paths to folders containing any EES_Shortcodes, or to
45
-     *       the EES_Shortcode files themselves
46
-     * @throws EE_Error
47
-     * @return void
48
-     */
49
-    public static function register($shortcode_id = null, $setup_args = array())
50
-    {
38
+	/**
39
+	 *    Method for registering new EE_Shortcodes
40
+	 *
41
+	 * @since    4.3.0
42
+	 * @param string $shortcode_id a unique identifier for this set of modules Required.
43
+	 * @param  array $setup_args   an array of arguments provided for registering shortcodes Required.
44
+	 * @type array shortcode_paths        an array of full server paths to folders containing any EES_Shortcodes, or to
45
+	 *       the EES_Shortcode files themselves
46
+	 * @throws EE_Error
47
+	 * @return void
48
+	 */
49
+	public static function register($shortcode_id = null, $setup_args = array())
50
+	{
51 51
 
52
-        //required fields MUST be present, so let's make sure they are.
53
-        if (empty($shortcode_id) || ! is_array($setup_args) || empty($setup_args['shortcode_paths'])) {
54
-            throw new EE_Error(__('In order to register Modules with EE_Register_Shortcode::register(), you must include a "shortcode_id" (a unique identifier for this set of shortcodes), and an array containing the following keys: "shortcode_paths" (an array of full server paths to folders that contain shortcodes, or to the shortcode files themselves)',
55
-                'event_espresso'));
56
-        }
52
+		//required fields MUST be present, so let's make sure they are.
53
+		if (empty($shortcode_id) || ! is_array($setup_args) || empty($setup_args['shortcode_paths'])) {
54
+			throw new EE_Error(__('In order to register Modules with EE_Register_Shortcode::register(), you must include a "shortcode_id" (a unique identifier for this set of shortcodes), and an array containing the following keys: "shortcode_paths" (an array of full server paths to folders that contain shortcodes, or to the shortcode files themselves)',
55
+				'event_espresso'));
56
+		}
57 57
 
58
-        //make sure we don't register twice
59
-        if (isset(self::$_settings[$shortcode_id])) {
60
-            return;
61
-        }
58
+		//make sure we don't register twice
59
+		if (isset(self::$_settings[$shortcode_id])) {
60
+			return;
61
+		}
62 62
 
63
-        //make sure this was called in the right place!
64
-        if (! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_System__register_shortcodes_modules_and_widgets')) {
65
-            EE_Error::doing_it_wrong(
66
-                __METHOD__,
67
-                __('An attempt to register shortcodes has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__register_shortcodes_modules_and_widgets" hook to register shortcodes.',
68
-                    'event_espresso'),
69
-                '4.3.0'
70
-            );
71
-        }
72
-        //setup $_settings array from incoming values.
73
-        self::$_settings[$shortcode_id] = array(
74
-            // array of full server paths to any EES_Shortcodes used by the shortcode
75
-            'shortcode_paths' => isset($setup_args['shortcode_paths']) ? (array)$setup_args['shortcode_paths'] : array(),
76
-        );
77
-        // add to list of shortcodes to be registered
78
-        add_filter('FHEE__EE_Config__register_shortcodes__shortcodes_to_register',
79
-            array('EE_Register_Shortcode', 'add_shortcodes'));
80
-    }
63
+		//make sure this was called in the right place!
64
+		if (! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_System__register_shortcodes_modules_and_widgets')) {
65
+			EE_Error::doing_it_wrong(
66
+				__METHOD__,
67
+				__('An attempt to register shortcodes has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__register_shortcodes_modules_and_widgets" hook to register shortcodes.',
68
+					'event_espresso'),
69
+				'4.3.0'
70
+			);
71
+		}
72
+		//setup $_settings array from incoming values.
73
+		self::$_settings[$shortcode_id] = array(
74
+			// array of full server paths to any EES_Shortcodes used by the shortcode
75
+			'shortcode_paths' => isset($setup_args['shortcode_paths']) ? (array)$setup_args['shortcode_paths'] : array(),
76
+		);
77
+		// add to list of shortcodes to be registered
78
+		add_filter('FHEE__EE_Config__register_shortcodes__shortcodes_to_register',
79
+			array('EE_Register_Shortcode', 'add_shortcodes'));
80
+	}
81 81
 
82 82
 
83
-    /**
84
-     * Filters the list of shortcodes to add ours.
85
-     * and they're just full filepaths to FOLDERS containing a shortcode class file. Eg.
86
-     * array('espresso_monkey'=>'/public_html/wonder-site/wp-content/plugins/ee4/shortcodes/espresso_monkey',...)
87
-     *
88
-     * @param array $shortcodes_to_register array of paths to all shortcodes that require registering
89
-     * @return array
90
-     */
91
-    public static function add_shortcodes($shortcodes_to_register)
92
-    {
93
-        foreach (self::$_settings as $settings) {
94
-            $shortcodes_to_register = array_merge($shortcodes_to_register, $settings['shortcode_paths']);
95
-        }
96
-        return $shortcodes_to_register;
97
-    }
83
+	/**
84
+	 * Filters the list of shortcodes to add ours.
85
+	 * and they're just full filepaths to FOLDERS containing a shortcode class file. Eg.
86
+	 * array('espresso_monkey'=>'/public_html/wonder-site/wp-content/plugins/ee4/shortcodes/espresso_monkey',...)
87
+	 *
88
+	 * @param array $shortcodes_to_register array of paths to all shortcodes that require registering
89
+	 * @return array
90
+	 */
91
+	public static function add_shortcodes($shortcodes_to_register)
92
+	{
93
+		foreach (self::$_settings as $settings) {
94
+			$shortcodes_to_register = array_merge($shortcodes_to_register, $settings['shortcode_paths']);
95
+		}
96
+		return $shortcodes_to_register;
97
+	}
98 98
 
99 99
 
100
-    /**
101
-     * This deregisters a shortcode that was previously registered with a specific $shortcode_id.
102
-     *
103
-     * @since    4.3.0
104
-     * @param string $shortcode_id the name for the shortcode that was previously registered
105
-     * @return void
106
-     */
107
-    public static function deregister($shortcode_id = null)
108
-    {
109
-        if (isset(self::$_settings[$shortcode_id])) {
110
-            unset(self::$_settings[$shortcode_id]);
111
-        }
112
-    }
100
+	/**
101
+	 * This deregisters a shortcode that was previously registered with a specific $shortcode_id.
102
+	 *
103
+	 * @since    4.3.0
104
+	 * @param string $shortcode_id the name for the shortcode that was previously registered
105
+	 * @return void
106
+	 */
107
+	public static function deregister($shortcode_id = null)
108
+	{
109
+		if (isset(self::$_settings[$shortcode_id])) {
110
+			unset(self::$_settings[$shortcode_id]);
111
+		}
112
+	}
113 113
 
114 114
 }
115 115
 // End of file EE_Register_Shortcode.lib.php
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 /**
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
         }
62 62
 
63 63
         //make sure this was called in the right place!
64
-        if (! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_System__register_shortcodes_modules_and_widgets')) {
64
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_System__register_shortcodes_modules_and_widgets')) {
65 65
             EE_Error::doing_it_wrong(
66 66
                 __METHOD__,
67 67
                 __('An attempt to register shortcodes has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__register_shortcodes_modules_and_widgets" hook to register shortcodes.',
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
         //setup $_settings array from incoming values.
73 73
         self::$_settings[$shortcode_id] = array(
74 74
             // array of full server paths to any EES_Shortcodes used by the shortcode
75
-            'shortcode_paths' => isset($setup_args['shortcode_paths']) ? (array)$setup_args['shortcode_paths'] : array(),
75
+            'shortcode_paths' => isset($setup_args['shortcode_paths']) ? (array) $setup_args['shortcode_paths'] : array(),
76 76
         );
77 77
         // add to list of shortcodes to be registered
78 78
         add_filter('FHEE__EE_Config__register_shortcodes__shortcodes_to_register',
Please login to merge, or discard this patch.
core/request_stack/EE_Request.core.php 1 patch
Indentation   +216 added lines, -216 removed lines patch added patch discarded remove patch
@@ -15,222 +15,222 @@
 block discarded – undo
15 15
 class EE_Request implements InterminableInterface
16 16
 {
17 17
 
18
-    /**
19
-     * $_GET parameters
20
-     *
21
-     * @var array $_get
22
-     */
23
-    private $_get;
24
-
25
-    /**
26
-     * $_POST parameters
27
-     *
28
-     * @var    array $_post
29
-     */
30
-    private $_post;
31
-
32
-    /**
33
-     * $_COOKIE parameters
34
-     *
35
-     * @var array $_cookie
36
-     */
37
-    private $_cookie;
38
-
39
-    /**
40
-     * $_REQUEST parameters
41
-     *
42
-     * @var array $_params
43
-     */
44
-    private $_params;
45
-
46
-    /**
47
-     * whether current request is via AJAX
48
-     *
49
-     * @access public
50
-     */
51
-    public $ajax = false;
52
-
53
-    /**
54
-     * whether current request is via AJAX from the frontend of the site
55
-     *
56
-     * @access public
57
-     */
58
-    public $front_ajax = false;
59
-
60
-    /**
61
-     * IP address for request
62
-     *
63
-     * @var string $_ip_address
64
-     */
65
-    private $_ip_address;
66
-
67
-
68
-
69
-    /**
70
-     * class constructor
71
-     *
72
-     * @access    public
73
-     * @param array $get
74
-     * @param array $post
75
-     * @param array $cookie
76
-     */
77
-    public function __construct($get, $post, $cookie)
78
-    {
79
-        // grab request vars
80
-        $this->_get = (array)$get;
81
-        $this->_post = (array)$post;
82
-        $this->_cookie = (array)$cookie;
83
-        $this->_params = array_merge($this->_get, $this->_post);
84
-        // AJAX ???
85
-        $this->ajax = defined('DOING_AJAX') ? true : false;
86
-        $this->front_ajax = $this->is_set('ee_front_ajax') && (int)$this->get('ee_front_ajax') === 1;
87
-        // grab user IP
88
-        $this->_ip_address = $this->_visitor_ip();
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     * @return array
95
-     */
96
-    public function get_params()
97
-    {
98
-        return $this->_get;
99
-    }
100
-
101
-
102
-
103
-    /**
104
-     * @return array
105
-     */
106
-    public function post_params()
107
-    {
108
-        return $this->_post;
109
-    }
110
-
111
-
112
-
113
-    /**
114
-     * @return array
115
-     */
116
-    public function cookie_params()
117
-    {
118
-        return $this->_cookie;
119
-    }
120
-
121
-
122
-
123
-    /**
124
-     * returns contents of $_REQUEST
125
-     *
126
-     * @return array
127
-     */
128
-    public function params()
129
-    {
130
-        return $this->_params;
131
-    }
132
-
133
-
134
-
135
-    /**
136
-     * @param      $key
137
-     * @param      $value
138
-     * @param bool $override_ee
139
-     * @return    void
140
-     */
141
-    public function set($key, $value, $override_ee = false)
142
-    {
143
-        // don't allow "ee" to be overwritten unless explicitly instructed to do so
144
-        if (
145
-            $key !== 'ee'
146
-            || ($key === 'ee' && empty($this->_params['ee']))
147
-            || ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
148
-        ) {
149
-            $this->_params[$key] = $value;
150
-        }
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * @param      $key
157
-     * @param null $default
158
-     * @return    mixed
159
-     */
160
-    public function get($key, $default = null)
161
-    {
162
-        return isset($this->_params[$key]) ? $this->_params[$key] : $default;
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * @param $key
169
-     * @return    boolean
170
-     */
171
-    public function is_set($key)
172
-    {
173
-        return isset($this->_params[$key]) ? true : false;
174
-    }
175
-
176
-
177
-
178
-    /**
179
-     * remove param
180
-     * @param      $key
181
-     * @param bool $unset_from_global_too
182
-     */
183
-    public function un_set($key, $unset_from_global_too = false)
184
-    {
185
-        unset($this->_params[$key]);
186
-        if ($unset_from_global_too) {
187
-            unset($_REQUEST[$key]);
188
-        }
189
-    }
190
-
191
-
192
-
193
-    /**
194
-     * @return string
195
-     */
196
-    public function ip_address()
197
-    {
198
-        return $this->_ip_address;
199
-    }
200
-
201
-
202
-
203
-    /**
204
-     * _visitor_ip
205
-     *    attempt to get IP address of current visitor from server
206
-     * plz see: http://stackoverflow.com/a/2031935/1475279
207
-     *
208
-     * @access public
209
-     * @return string
210
-     */
211
-    private function _visitor_ip()
212
-    {
213
-        $visitor_ip = '0.0.0.0';
214
-        $server_keys = array(
215
-            'HTTP_CLIENT_IP',
216
-            'HTTP_X_FORWARDED_FOR',
217
-            'HTTP_X_FORWARDED',
218
-            'HTTP_X_CLUSTER_CLIENT_IP',
219
-            'HTTP_FORWARDED_FOR',
220
-            'HTTP_FORWARDED',
221
-            'REMOTE_ADDR',
222
-        );
223
-        foreach ($server_keys as $key) {
224
-            if (isset($_SERVER[$key])) {
225
-                foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
226
-                    if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
227
-                        $visitor_ip = $ip;
228
-                    }
229
-                }
230
-            }
231
-        }
232
-        return $visitor_ip;
233
-    }
18
+	/**
19
+	 * $_GET parameters
20
+	 *
21
+	 * @var array $_get
22
+	 */
23
+	private $_get;
24
+
25
+	/**
26
+	 * $_POST parameters
27
+	 *
28
+	 * @var    array $_post
29
+	 */
30
+	private $_post;
31
+
32
+	/**
33
+	 * $_COOKIE parameters
34
+	 *
35
+	 * @var array $_cookie
36
+	 */
37
+	private $_cookie;
38
+
39
+	/**
40
+	 * $_REQUEST parameters
41
+	 *
42
+	 * @var array $_params
43
+	 */
44
+	private $_params;
45
+
46
+	/**
47
+	 * whether current request is via AJAX
48
+	 *
49
+	 * @access public
50
+	 */
51
+	public $ajax = false;
52
+
53
+	/**
54
+	 * whether current request is via AJAX from the frontend of the site
55
+	 *
56
+	 * @access public
57
+	 */
58
+	public $front_ajax = false;
59
+
60
+	/**
61
+	 * IP address for request
62
+	 *
63
+	 * @var string $_ip_address
64
+	 */
65
+	private $_ip_address;
66
+
67
+
68
+
69
+	/**
70
+	 * class constructor
71
+	 *
72
+	 * @access    public
73
+	 * @param array $get
74
+	 * @param array $post
75
+	 * @param array $cookie
76
+	 */
77
+	public function __construct($get, $post, $cookie)
78
+	{
79
+		// grab request vars
80
+		$this->_get = (array)$get;
81
+		$this->_post = (array)$post;
82
+		$this->_cookie = (array)$cookie;
83
+		$this->_params = array_merge($this->_get, $this->_post);
84
+		// AJAX ???
85
+		$this->ajax = defined('DOING_AJAX') ? true : false;
86
+		$this->front_ajax = $this->is_set('ee_front_ajax') && (int)$this->get('ee_front_ajax') === 1;
87
+		// grab user IP
88
+		$this->_ip_address = $this->_visitor_ip();
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 * @return array
95
+	 */
96
+	public function get_params()
97
+	{
98
+		return $this->_get;
99
+	}
100
+
101
+
102
+
103
+	/**
104
+	 * @return array
105
+	 */
106
+	public function post_params()
107
+	{
108
+		return $this->_post;
109
+	}
110
+
111
+
112
+
113
+	/**
114
+	 * @return array
115
+	 */
116
+	public function cookie_params()
117
+	{
118
+		return $this->_cookie;
119
+	}
120
+
121
+
122
+
123
+	/**
124
+	 * returns contents of $_REQUEST
125
+	 *
126
+	 * @return array
127
+	 */
128
+	public function params()
129
+	{
130
+		return $this->_params;
131
+	}
132
+
133
+
134
+
135
+	/**
136
+	 * @param      $key
137
+	 * @param      $value
138
+	 * @param bool $override_ee
139
+	 * @return    void
140
+	 */
141
+	public function set($key, $value, $override_ee = false)
142
+	{
143
+		// don't allow "ee" to be overwritten unless explicitly instructed to do so
144
+		if (
145
+			$key !== 'ee'
146
+			|| ($key === 'ee' && empty($this->_params['ee']))
147
+			|| ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
148
+		) {
149
+			$this->_params[$key] = $value;
150
+		}
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * @param      $key
157
+	 * @param null $default
158
+	 * @return    mixed
159
+	 */
160
+	public function get($key, $default = null)
161
+	{
162
+		return isset($this->_params[$key]) ? $this->_params[$key] : $default;
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * @param $key
169
+	 * @return    boolean
170
+	 */
171
+	public function is_set($key)
172
+	{
173
+		return isset($this->_params[$key]) ? true : false;
174
+	}
175
+
176
+
177
+
178
+	/**
179
+	 * remove param
180
+	 * @param      $key
181
+	 * @param bool $unset_from_global_too
182
+	 */
183
+	public function un_set($key, $unset_from_global_too = false)
184
+	{
185
+		unset($this->_params[$key]);
186
+		if ($unset_from_global_too) {
187
+			unset($_REQUEST[$key]);
188
+		}
189
+	}
190
+
191
+
192
+
193
+	/**
194
+	 * @return string
195
+	 */
196
+	public function ip_address()
197
+	{
198
+		return $this->_ip_address;
199
+	}
200
+
201
+
202
+
203
+	/**
204
+	 * _visitor_ip
205
+	 *    attempt to get IP address of current visitor from server
206
+	 * plz see: http://stackoverflow.com/a/2031935/1475279
207
+	 *
208
+	 * @access public
209
+	 * @return string
210
+	 */
211
+	private function _visitor_ip()
212
+	{
213
+		$visitor_ip = '0.0.0.0';
214
+		$server_keys = array(
215
+			'HTTP_CLIENT_IP',
216
+			'HTTP_X_FORWARDED_FOR',
217
+			'HTTP_X_FORWARDED',
218
+			'HTTP_X_CLUSTER_CLIENT_IP',
219
+			'HTTP_FORWARDED_FOR',
220
+			'HTTP_FORWARDED',
221
+			'REMOTE_ADDR',
222
+		);
223
+		foreach ($server_keys as $key) {
224
+			if (isset($_SERVER[$key])) {
225
+				foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
226
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
227
+						$visitor_ip = $ip;
228
+					}
229
+				}
230
+			}
231
+		}
232
+		return $visitor_ip;
233
+	}
234 234
 
235 235
 
236 236
 
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +19 added lines, -16 removed lines patch added patch discarded remove patch
@@ -960,7 +960,7 @@  discard block
 block discarded – undo
960 960
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961 961
      * foreign key to the WP_User table)
962 962
      *
963
-     * @return string|boolean string on success, boolean false when there is no
963
+     * @return string|false string on success, boolean false when there is no
964 964
      * foreign key to the WP_User table
965 965
      */
966 966
     public function wp_user_field_name()
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
      *
1067 1067
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1068 1068
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1069
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070 1070
      *                                  fields on the model, and the models we joined to in the query. However, you can
1071 1071
      *                                  override this and set the select to "*", or a specific column name, like
1072 1072
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1404,6 +1404,7 @@  discard block
 block discarded – undo
1404 1404
      * This sets the _timezone property after model object has been instantiated.
1405 1405
      *
1406 1406
      * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+     * @param string|null $timezone
1407 1408
      */
1408 1409
     public function set_timezone($timezone)
1409 1410
     {
@@ -1458,7 +1459,7 @@  discard block
 block discarded – undo
1458 1459
      * @param string $field_name The name of the field the formats are being retrieved for.
1459 1460
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460 1461
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
+     * @return string[] formats in an array with the date format first, and the time format last.
1462 1463
      */
1463 1464
     public function get_formats_for($field_name, $pretty = false)
1464 1465
     {
@@ -1493,7 +1494,7 @@  discard block
 block discarded – undo
1493 1494
      *                                 be returned.
1494 1495
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495 1496
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497 1498
      *                                 exception is triggered.
1498 1499
      */
1499 1500
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1533,7 +1534,7 @@  discard block
 block discarded – undo
1533 1534
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534 1535
      *                                format is
1535 1536
      *                                'U', this is ignored.
1536
-     * @return DateTime
1537
+     * @return string
1537 1538
      * @throws EE_Error
1538 1539
      */
1539 1540
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -1831,7 +1832,7 @@  discard block
 block discarded – undo
1831 1832
      * Wrapper for EEM_Base::delete_permanently()
1832 1833
      *
1833 1834
      * @param mixed $id
1834
-     * @return boolean whether the row got deleted or not
1835
+     * @return integer whether the row got deleted or not
1835 1836
      * @throws EE_Error
1836 1837
      */
1837 1838
     public function delete_permanently_by_ID($id)
@@ -1851,7 +1852,7 @@  discard block
 block discarded – undo
1851 1852
      * Wrapper for EEM_Base::delete()
1852 1853
      *
1853 1854
      * @param mixed $id
1854
-     * @return boolean whether the row got deleted or not
1855
+     * @return integer whether the row got deleted or not
1855 1856
      * @throws EE_Error
1856 1857
      */
1857 1858
     public function delete_by_ID($id)
@@ -2365,7 +2366,7 @@  discard block
 block discarded – undo
2365 2366
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2366 2367
      * EEM_Base::$_db_verification_level
2367 2368
      *
2368
-     * @param $wpdb_method
2369
+     * @param string $wpdb_method
2369 2370
      * @param $arguments_to_provide
2370 2371
      * @return string
2371 2372
      */
@@ -2489,6 +2490,7 @@  discard block
 block discarded – undo
2489 2490
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2490 2491
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2491 2492
      *                             because these will be inserted in any new rows created as well.
2493
+     * @param EE_Base_Class $id_or_obj
2492 2494
      */
2493 2495
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2494 2496
     {
@@ -2499,7 +2501,7 @@  discard block
 block discarded – undo
2499 2501
 
2500 2502
 
2501 2503
     /**
2502
-     * @param mixed           $id_or_obj
2504
+     * @param EE_Base_Class           $id_or_obj
2503 2505
      * @param string          $relationName
2504 2506
      * @param array           $where_query_params
2505 2507
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2540,7 +2542,7 @@  discard block
 block discarded – undo
2540 2542
      * However, if the model objects can't be deleted because of blocking related model objects, then
2541 2543
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2542 2544
      *
2543
-     * @param EE_Base_Class|int|string $id_or_obj
2545
+     * @param EE_Base_Class $id_or_obj
2544 2546
      * @param string                   $model_name
2545 2547
      * @param array                    $query_params
2546 2548
      * @return int how many deleted
@@ -2561,7 +2563,7 @@  discard block
 block discarded – undo
2561 2563
      * the model objects can't be hard deleted because of blocking related model objects,
2562 2564
      * just does a soft-delete on them instead.
2563 2565
      *
2564
-     * @param EE_Base_Class|int|string $id_or_obj
2566
+     * @param EE_Base_Class $id_or_obj
2565 2567
      * @param string                   $model_name
2566 2568
      * @param array                    $query_params
2567 2569
      * @return int how many deleted
@@ -2618,6 +2620,7 @@  discard block
 block discarded – undo
2618 2620
      * @param string $model_name   like 'Event', or 'Registration'
2619 2621
      * @param array  $query_params like EEM_Base::get_all's
2620 2622
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2623
+     * @param EE_Base_Class $id_or_obj
2621 2624
      * @return float
2622 2625
      * @throws EE_Error
2623 2626
      */
@@ -3092,7 +3095,7 @@  discard block
 block discarded – undo
3092 3095
      * Finds all the fields that correspond to the given table
3093 3096
      *
3094 3097
      * @param string $table_alias , array key in EEM_Base::_tables
3095
-     * @return EE_Model_Field_Base[]
3098
+     * @return EE_Model_Field_Base
3096 3099
      */
3097 3100
     public function _get_fields_for_table($table_alias)
3098 3101
     {
@@ -3577,7 +3580,7 @@  discard block
 block discarded – undo
3577 3580
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3578 3581
      * We should use default where conditions on related models when they requested to use default where conditions
3579 3582
      * on all models, or specifically just on other related models
3580
-     * @param      $default_where_conditions_value
3583
+     * @param      string $default_where_conditions_value
3581 3584
      * @param bool $for_this_model false means this is for OTHER related models
3582 3585
      * @return bool
3583 3586
      */
@@ -3615,7 +3618,7 @@  discard block
 block discarded – undo
3615 3618
      * where conditions.
3616 3619
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3617 3620
      * on this model or others
3618
-     * @param      $default_where_conditions_value
3621
+     * @param      string $default_where_conditions_value
3619 3622
      * @param bool $for_this_model false means this is for OTHER related models
3620 3623
      * @return bool
3621 3624
      */
@@ -4668,7 +4671,7 @@  discard block
 block discarded – undo
4668 4671
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4669 4672
      * Eg, on EE_Answer that would be ANS_ID field object
4670 4673
      *
4671
-     * @param $field_obj
4674
+     * @param EE_Model_Field_Base $field_obj
4672 4675
      * @return boolean
4673 4676
      */
4674 4677
     public function is_primary_key_field($field_obj)
@@ -5399,7 +5402,7 @@  discard block
 block discarded – undo
5399 5402
     /**
5400 5403
      * Read comments for assume_values_already_prepared_by_model_object()
5401 5404
      *
5402
-     * @return int
5405
+     * @return boolean
5403 5406
      */
5404 5407
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5405 5408
     {
Please login to merge, or discard this patch.
Indentation   +5917 added lines, -5917 removed lines patch added patch discarded remove patch
@@ -28,5929 +28,5929 @@
 block discarded – undo
28 28
 abstract class EEM_Base extends EE_Base implements EventEspresso\core\interfaces\ResettableInterface
29 29
 {
30 30
 
31
-    //admin posty
32
-    //basic -> grants access to mine -> if they don't have it, select none
33
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
-    //*_published -> grants access to published -> if they dont have it, select non-published
36
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
38
-    //frontend posty
39
-    //by default has access to published
40
-    //basic -> grants access to mine that aren't published, and all published
41
-    //*_others ->grants access to others that aren't private, all mine
42
-    //*_private -> grants full access
43
-    //frontend non-posty
44
-    //like admin posty
45
-    //category-y
46
-    //assign -> grants access to join-table
47
-    //(delete, edit)
48
-    //payment-method-y
49
-    //for each registered payment method,
50
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
-    /**
52
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
-     * They almost always WILL NOT, but it's not necessarily a requirement.
55
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
-     *
57
-     * @var boolean
58
-     */
59
-    private $_values_already_prepared_by_model_object = 0;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the data is just like form input that needs to have the model fields'
64
-     * prepare_for_set and prepare_for_use_in_db called on it
65
-     */
66
-    const not_prepared_by_model_object = 0;
67
-
68
-    /**
69
-     * when $_values_already_prepared_by_model_object equals this, we
70
-     * assume this value is coming from a model object and doesn't need to have
71
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
72
-     */
73
-    const prepared_by_model_object = 1;
74
-
75
-    /**
76
-     * when $_values_already_prepared_by_model_object equals this, we assume
77
-     * the values are already to be used in the database (ie no processing is done
78
-     * on them by the model's fields)
79
-     */
80
-    const prepared_for_use_in_db = 2;
81
-
82
-
83
-    protected $singular_item = 'Item';
84
-
85
-    protected $plural_item   = 'Items';
86
-
87
-    /**
88
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
-     */
90
-    protected $_tables;
91
-
92
-    /**
93
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
-     *
97
-     * @var \EE_Model_Field_Base[] $_fields
98
-     */
99
-    protected $_fields;
100
-
101
-    /**
102
-     * array of different kinds of relations
103
-     *
104
-     * @var \EE_Model_Relation_Base[] $_model_relations
105
-     */
106
-    protected $_model_relations;
107
-
108
-    /**
109
-     * @var \EE_Index[] $_indexes
110
-     */
111
-    protected $_indexes = array();
112
-
113
-    /**
114
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
115
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
-     * by setting the same columns as used in these queries in the query yourself.
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_default_where_conditions_strategy;
121
-
122
-    /**
123
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
-     * This is particularly useful when you want something between 'none' and 'default'
125
-     *
126
-     * @var EE_Default_Where_Conditions
127
-     */
128
-    protected $_minimum_where_conditions_strategy;
129
-
130
-    /**
131
-     * String describing how to find the "owner" of this model's objects.
132
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
-     * But when there isn't, this indicates which related model, or transiently-related model,
134
-     * has the foreign key to the wp_users table.
135
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
-     * related to events, and events have a foreign key to wp_users.
137
-     * On EEM_Transaction, this would be 'Transaction.Event'
138
-     *
139
-     * @var string
140
-     */
141
-    protected $_model_chain_to_wp_user = '';
142
-
143
-    /**
144
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
-     * don't need it (particularly CPT models)
146
-     *
147
-     * @var bool
148
-     */
149
-    protected $_ignore_where_strategy = false;
150
-
151
-    /**
152
-     * String used in caps relating to this model. Eg, if the caps relating to this
153
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
-     *
155
-     * @var string. If null it hasn't been initialized yet. If false then we
156
-     * have indicated capabilities don't apply to this
157
-     */
158
-    protected $_caps_slug = null;
159
-
160
-    /**
161
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
-     * and next-level keys are capability names, and each's value is a
163
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
-     * they specify which context to use (ie, frontend, backend, edit or delete)
165
-     * and then each capability in the corresponding sub-array that they're missing
166
-     * adds the where conditions onto the query.
167
-     *
168
-     * @var array
169
-     */
170
-    protected $_cap_restrictions = array(
171
-        self::caps_read       => array(),
172
-        self::caps_read_admin => array(),
173
-        self::caps_edit       => array(),
174
-        self::caps_delete     => array(),
175
-    );
176
-
177
-    /**
178
-     * Array defining which cap restriction generators to use to create default
179
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
180
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
-     * automatically set this to false (not just null).
183
-     *
184
-     * @var EE_Restriction_Generator_Base[]
185
-     */
186
-    protected $_cap_restriction_generators = array();
187
-
188
-    /**
189
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
-     */
191
-    const caps_read       = 'read';
192
-
193
-    const caps_read_admin = 'read_admin';
194
-
195
-    const caps_edit       = 'edit';
196
-
197
-    const caps_delete     = 'delete';
198
-
199
-    /**
200
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
-     * maps to 'read' because when looking for relevant permissions we're going to use
203
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
204
-     *
205
-     * @var array
206
-     */
207
-    protected $_cap_contexts_to_cap_action_map = array(
208
-        self::caps_read       => 'read',
209
-        self::caps_read_admin => 'read',
210
-        self::caps_edit       => 'edit',
211
-        self::caps_delete     => 'delete',
212
-    );
213
-
214
-    /**
215
-     * Timezone
216
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
-     * EE_Datetime_Field data type will have access to it.
220
-     *
221
-     * @var string
222
-     */
223
-    protected $_timezone;
224
-
225
-
226
-    /**
227
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
-     * multisite.
229
-     *
230
-     * @var int
231
-     */
232
-    protected static $_model_query_blog_id;
233
-
234
-    /**
235
-     * A copy of _fields, except the array keys are the model names pointed to by
236
-     * the field
237
-     *
238
-     * @var EE_Model_Field_Base[]
239
-     */
240
-    private $_cache_foreign_key_to_fields = array();
241
-
242
-    /**
243
-     * Cached list of all the fields on the model, indexed by their name
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cached_fields = null;
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, except those that are
251
-     * marked as only pertinent to the database
252
-     *
253
-     * @var EE_Model_Field_Base[]
254
-     */
255
-    private $_cached_fields_non_db_only = null;
256
-
257
-    /**
258
-     * A cached reference to the primary key for quick lookup
259
-     *
260
-     * @var EE_Model_Field_Base
261
-     */
262
-    private $_primary_key_field = null;
263
-
264
-    /**
265
-     * Flag indicating whether this model has a primary key or not
266
-     *
267
-     * @var boolean
268
-     */
269
-    protected $_has_primary_key_field = null;
270
-
271
-    /**
272
-     * Whether or not this model is based off a table in WP core only (CPTs should set
273
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
-     *
275
-     * @var boolean
276
-     */
277
-    protected $_wp_core_model = false;
278
-
279
-    /**
280
-     *    List of valid operators that can be used for querying.
281
-     * The keys are all operators we'll accept, the values are the real SQL
282
-     * operators used
283
-     *
284
-     * @var array
285
-     */
286
-    protected $_valid_operators = array(
287
-        '='           => '=',
288
-        '<='          => '<=',
289
-        '<'           => '<',
290
-        '>='          => '>=',
291
-        '>'           => '>',
292
-        '!='          => '!=',
293
-        'LIKE'        => 'LIKE',
294
-        'like'        => 'LIKE',
295
-        'NOT_LIKE'    => 'NOT LIKE',
296
-        'not_like'    => 'NOT LIKE',
297
-        'NOT LIKE'    => 'NOT LIKE',
298
-        'not like'    => 'NOT LIKE',
299
-        'IN'          => 'IN',
300
-        'in'          => 'IN',
301
-        'NOT_IN'      => 'NOT IN',
302
-        'not_in'      => 'NOT IN',
303
-        'NOT IN'      => 'NOT IN',
304
-        'not in'      => 'NOT IN',
305
-        'between'     => 'BETWEEN',
306
-        'BETWEEN'     => 'BETWEEN',
307
-        'IS_NOT_NULL' => 'IS NOT NULL',
308
-        'is_not_null' => 'IS NOT NULL',
309
-        'IS NOT NULL' => 'IS NOT NULL',
310
-        'is not null' => 'IS NOT NULL',
311
-        'IS_NULL'     => 'IS NULL',
312
-        'is_null'     => 'IS NULL',
313
-        'IS NULL'     => 'IS NULL',
314
-        'is null'     => 'IS NULL',
315
-        'REGEXP'      => 'REGEXP',
316
-        'regexp'      => 'REGEXP',
317
-        'NOT_REGEXP'  => 'NOT REGEXP',
318
-        'not_regexp'  => 'NOT REGEXP',
319
-        'NOT REGEXP'  => 'NOT REGEXP',
320
-        'not regexp'  => 'NOT REGEXP',
321
-    );
322
-
323
-    /**
324
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
-     *
326
-     * @var array
327
-     */
328
-    protected $_in_style_operators = array('IN', 'NOT IN');
329
-
330
-    /**
331
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
-     * '12-31-2012'"
333
-     *
334
-     * @var array
335
-     */
336
-    protected $_between_style_operators = array('BETWEEN');
337
-
338
-    /**
339
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
-     * on a join table.
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
-
346
-    /**
347
-     * Allowed values for $query_params['order'] for ordering in queries
348
-     *
349
-     * @var array
350
-     */
351
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
-
353
-    /**
354
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
356
-     *
357
-     * @var array
358
-     */
359
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
-
361
-    /**
362
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
364
-     *
365
-     * @var array
366
-     */
367
-    private $_allowed_query_params = array(
368
-        0,
369
-        'limit',
370
-        'order_by',
371
-        'group_by',
372
-        'having',
373
-        'force_join',
374
-        'order',
375
-        'on_join_limit',
376
-        'default_where_conditions',
377
-        'caps',
378
-    );
379
-
380
-    /**
381
-     * All the data types that can be used in $wpdb->prepare statements.
382
-     *
383
-     * @var array
384
-     */
385
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
-
387
-    /**
388
-     *    EE_Registry Object
389
-     *
390
-     * @var    object
391
-     * @access    protected
392
-     */
393
-    protected $EE = null;
394
-
395
-
396
-    /**
397
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
-     *
399
-     * @var int
400
-     */
401
-    protected $_show_next_x_db_queries = 0;
402
-
403
-    /**
404
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
-     *
407
-     * @var array
408
-     */
409
-    protected $_custom_selections = array();
410
-
411
-    /**
412
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
-     * caches every model object we've fetched from the DB on this request
414
-     *
415
-     * @var array
416
-     */
417
-    protected $_entity_map;
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Generates the cap restrictions for the given context, or if they were
654
-     * already generated just gets what's cached
655
-     *
656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
657
-     * @return EE_Default_Where_Conditions[]
658
-     */
659
-    protected function _generate_cap_restrictions($context)
660
-    {
661
-        if (isset($this->_cap_restriction_generators[$context])
662
-            && $this->_cap_restriction_generators[$context]
663
-               instanceof
664
-               EE_Restriction_Generator_Base
665
-        ) {
666
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
-        } else {
668
-            return array();
669
-        }
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Used to set the $_model_query_blog_id static property.
676
-     *
677
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
-     *                      value for get_current_blog_id() will be used.
679
-     */
680
-    public static function set_model_query_blog_id($blog_id = 0)
681
-    {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     * Returns whatever is set as the internal $model_query_blog_id.
689
-     *
690
-     * @return int
691
-     */
692
-    public static function get_model_query_blog_id()
693
-    {
694
-        return EEM_Base::$_model_query_blog_id;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *        This function is a singleton method used to instantiate the Espresso_model object
701
-     *
702
-     * @access public
703
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
-     *                         timezone in the 'timezone_string' wp option)
707
-     * @return static (as in the concrete child class)
708
-     */
709
-    public static function instance($timezone = null)
710
-    {
711
-        // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
713
-            // instantiate Espresso_model
714
-            static::$_instance = new static($timezone);
715
-        }
716
-        //we might have a timezone set, let set_timezone decide what to do with it
717
-        static::$_instance->set_timezone($timezone);
718
-        // Espresso_model object
719
-        return static::$_instance;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * resets the model and returns it
726
-     *
727
-     * @param null | string $timezone
728
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
-     * all its properties reset; if it wasn't instantiated, returns null)
730
-     */
731
-    public static function reset($timezone = null)
732
-    {
733
-        if (static::$_instance instanceof EEM_Base) {
734
-            //let's try to NOT swap out the current instance for a new one
735
-            //because if someone has a reference to it, we can't remove their reference
736
-            //so it's best to keep using the same reference, but change the original object
737
-            //reset all its properties to their original values as defined in the class
738
-            $r = new ReflectionClass(get_class(static::$_instance));
739
-            $static_properties = $r->getStaticProperties();
740
-            foreach ($r->getDefaultProperties() as $property => $value) {
741
-                //don't set instance to null like it was originally,
742
-                //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
744
-                    static::$_instance->{$property} = $value;
745
-                }
746
-            }
747
-            //and then directly call its constructor again, like we would if we
748
-            //were creating a new one
749
-            static::$_instance->__construct($timezone);
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
-     *
760
-     * @param  boolean $translated return localized strings or JUST the array.
761
-     * @return array
762
-     * @throws EE_Error
763
-     */
764
-    public function status_array($translated = false)
765
-    {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
-            return array();
768
-        }
769
-        $model_name = $this->get_this_model_name();
770
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
-        $status_array = array();
773
-        foreach ($stati as $status) {
774
-            $status_array[$status->ID()] = $status->get('STS_code');
775
-        }
776
-        return $translated
777
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
-            : $status_array;
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
-     *
786
-     * @param array $query_params             {
787
-     * @var array $0 (where) array {
788
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
-     *                                        conditions based on related models (and even
792
-     *                                        models-related-to-related-models) prepend the model's name onto the field
793
-     *                                        name. Eg,
794
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
-     *                                        to Venues (even when each of those models actually consisted of two
802
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
803
-     *                                        just having
804
-     *                                        "Venue.VNU_ID", you could have
805
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
-     *                                        events are related to Registrations, which are related to Attendees). You
807
-     *                                        can take it even further with
808
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
-     *                                        (from the default of '='), change the value to an numerically-indexed
810
-     *                                        array, where the first item in the list is the operator. eg: array(
811
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
819
-     *                                        the value is a field, simply provide a third array item (true) to the
820
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
-     *                                        Note: you can also use related model field names like you would any other
823
-     *                                        field name. eg:
824
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
826
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
833
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
-     *                                        "stick" until you specify an AND. eg
835
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
840
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
-     *                                        too, eg:
843
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
848
-     *                                        the OFFSET, the 2nd is the LIMIT
849
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
-     *                                        following format array('on_join_limit'
852
-     *                                        => array( 'table_alias', array(1,2) ) ).
853
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
-     *                                        values are either 'ASC' or 'DESC'.
855
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
-     *                                        DESC..." respectively. Like the
858
-     *                                        'where' conditions, these fields can be on related models. Eg
859
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
861
-     *                                        Attendee, Price, Datetime, etc.)
862
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
864
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
-     *                                        order by the primary key. Eg,
867
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
-     *                                        //(will join with the Datetime model's table(s) and order by its field
869
-     *                                        DTT_EVT_start) or
870
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
-     *                                        'group_by'=>'VNU_ID', or
874
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
-     *                                        if no
876
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
877
-     *                                        model's primary key (or combined primary keys). This avoids some
878
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
879
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
-     *                                        results)
883
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
-     *                                        array where values are models to be joined in the query.Eg
885
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
887
-     *                                        probably only want to do this in hopes of increasing efficiency, as
888
-     *                                        related models which belongs to the current model
889
-     *                                        (ie, the current model has a foreign key to them, like how Registration
890
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
891
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
894
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
-     *                                        default where conditions set it to 'other_models_only'. If you only want
896
-     *                                        this model's default where conditions added to the query, use
897
-     *                                        'this_model_only'. If you want to use all default where conditions
898
-     *                                        (default), set to 'all'.
899
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
-     *                                        everything? Or should we only show the current user items they should be
902
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
-     *                                        }
905
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
-     *                                        array( array(
911
-     *                                        'OR'=>array(
912
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
-     *                                        )
915
-     *                                        ),
916
-     *                                        'limit'=>10,
917
-     *                                        'group_by'=>'TXN_ID'
918
-     *                                        ));
919
-     *                                        get all the answers to the question titled "shirt size" for event with id
920
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
-     *                                        'Question.QST_display_text'=>'shirt size',
922
-     *                                        'Registration.Event.EVT_ID'=>12
923
-     *                                        ),
924
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
925
-     *                                        ));
926
-     * @throws EE_Error
927
-     */
928
-    public function get_all($query_params = array())
929
-    {
930
-        if (isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Modifies the query parameters so we only get back model objects
942
-     * that "belong" to the current user
943
-     *
944
-     * @param array $query_params @see EEM_Base::get_all()
945
-     * @return array like EEM_Base::get_all
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = array())
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Returns the name of the field's name that points to the WP_User table
960
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
-     * foreign key to the WP_User table)
962
-     *
963
-     * @return string|boolean string on success, boolean false when there is no
964
-     * foreign key to the WP_User table
965
-     */
966
-    public function wp_user_field_name()
967
-    {
968
-        try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
970
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
-                $last_model_name = end($models_to_follow_to_wp_users);
972
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
-            } else {
975
-                $model_with_fk_to_wp_users = $this;
976
-                $model_chain_to_wp_user = '';
977
-            }
978
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
-        } catch (EE_Error $e) {
981
-            return false;
982
-        }
983
-    }
984
-
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
-     * like how registrations don't have a foreign key to wp_users, but the
1007
-     * events they are for are), or is unrelated to wp users.
1008
-     * generally available
1009
-     *
1010
-     * @return boolean
1011
-     */
1012
-    public function is_owned()
1013
-    {
1014
-        if ($this->model_chain_to_wp_user()) {
1015
-            return true;
1016
-        } else {
1017
-            try {
1018
-                $this->get_foreign_key_to('WP_User');
1019
-                return true;
1020
-            } catch (EE_Error $e) {
1021
-                return false;
1022
-            }
1023
-        }
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws EE_Error
1045
-     */
1046
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        // remember the custom selections, if any, and type cast as array
1049
-        // (unless $columns_to_select is an object, then just set as an empty array)
1050
-        // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions = $columns_to_select !== null
1054
-            ? $this->_construct_select_from_input($columns_to_select)
1055
-            : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1064
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
-     * take care of joins, field preparation etc.
1066
-     *
1067
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1071
-     *                                  override this and set the select to "*", or a specific column name, like
1072
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
-     *                                  the aliases used to refer to this selection, and values are to be
1075
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
-     * @throws EE_Error
1079
-     */
1080
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
-    {
1082
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * For creating a custom select statement
1089
-     *
1090
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
-     *                                 SQL, and 1=>is the datatype
1093
-     * @throws EE_Error
1094
-     * @return string
1095
-     */
1096
-    private function _construct_select_from_input($columns_to_select)
1097
-    {
1098
-        if (is_array($columns_to_select)) {
1099
-            $select_sql_array = array();
1100
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
-                    throw new EE_Error(
1103
-                        sprintf(
1104
-                            __(
1105
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
-                                "event_espresso"
1107
-                            ),
1108
-                            $selection_and_datatype,
1109
-                            $alias
1110
-                        )
1111
-                    );
1112
-                }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
-                    throw new EE_Error(
1115
-                        sprintf(
1116
-                            __(
1117
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
-                                "event_espresso"
1119
-                            ),
1120
-                            $selection_and_datatype[1],
1121
-                            $selection_and_datatype[0],
1122
-                            $alias,
1123
-                            implode(",", $this->_valid_wpdb_data_types)
1124
-                        )
1125
-                    );
1126
-                }
1127
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
-            }
1129
-            $columns_to_select_string = implode(", ", $select_sql_array);
1130
-        } else {
1131
-            $columns_to_select_string = $columns_to_select;
1132
-        }
1133
-        return $columns_to_select_string;
1134
-    }
1135
-
1136
-
1137
-
1138
-    /**
1139
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
-     *
1141
-     * @return string
1142
-     * @throws EE_Error
1143
-     */
1144
-    public function primary_key_name()
1145
-    {
1146
-        return $this->get_primary_key_field()->get_name();
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
-     * If there is no primary key on this model, $id is treated as primary key string
1154
-     *
1155
-     * @param mixed $id int or string, depending on the type of the model's primary key
1156
-     * @return EE_Base_Class
1157
-     */
1158
-    public function get_one_by_ID($id)
1159
-    {
1160
-        if ($this->get_from_entity_map($id)) {
1161
-            return $this->get_from_entity_map($id);
1162
-        }
1163
-        return $this->get_one(
1164
-            $this->alter_query_params_to_restrict_by_ID(
1165
-                $id,
1166
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
-            )
1168
-        );
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Alters query parameters to only get items with this ID are returned.
1175
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
-     * or could just be a simple primary key ID
1177
-     *
1178
-     * @param int   $id
1179
-     * @param array $query_params
1180
-     * @return array of normal query params, @see EEM_Base::get_all
1181
-     * @throws EE_Error
1182
-     */
1183
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
-    {
1185
-        if (! isset($query_params[0])) {
1186
-            $query_params[0] = array();
1187
-        }
1188
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1189
-        if ($conditions_from_id === null) {
1190
-            $query_params[0][$this->primary_key_name()] = $id;
1191
-        } else {
1192
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1193
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
-        }
1195
-        return $query_params;
1196
-    }
1197
-
1198
-
1199
-
1200
-    /**
1201
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
-     * array. If no item is found, null is returned.
1203
-     *
1204
-     * @param array $query_params like EEM_Base's $query_params variable.
1205
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
-     * @throws EE_Error
1207
-     */
1208
-    public function get_one($query_params = array())
1209
-    {
1210
-        if (! is_array($query_params)) {
1211
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
-                    gettype($query_params)), '4.6.0');
1214
-            $query_params = array();
1215
-        }
1216
-        $query_params['limit'] = 1;
1217
-        $items = $this->get_all($query_params);
1218
-        if (empty($items)) {
1219
-            return null;
1220
-        } else {
1221
-            return array_shift($items);
1222
-        }
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Returns the next x number of items in sequence from the given value as
1229
-     * found in the database matching the given query conditions.
1230
-     *
1231
-     * @param mixed $current_field_value    Value used for the reference point.
1232
-     * @param null  $field_to_order_by      What field is used for the
1233
-     *                                      reference point.
1234
-     * @param int   $limit                  How many to return.
1235
-     * @param array $query_params           Extra conditions on the query.
1236
-     * @param null  $columns_to_select      If left null, then an array of
1237
-     *                                      EE_Base_Class objects is returned,
1238
-     *                                      otherwise you can indicate just the
1239
-     *                                      columns you want returned.
1240
-     * @return EE_Base_Class[]|array
1241
-     * @throws EE_Error
1242
-     */
1243
-    public function next_x(
1244
-        $current_field_value,
1245
-        $field_to_order_by = null,
1246
-        $limit = 1,
1247
-        $query_params = array(),
1248
-        $columns_to_select = null
1249
-    ) {
1250
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
-            $columns_to_select);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the previous x number of items in sequence from the given value
1258
-     * as found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws EE_Error
1271
-     */
1272
-    public function previous_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = array(),
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
-            $columns_to_select);
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * Returns the next item in sequence from the given value as found in the
1287
-     * database matching the given query conditions.
1288
-     *
1289
-     * @param mixed $current_field_value    Value used for the reference point.
1290
-     * @param null  $field_to_order_by      What field is used for the
1291
-     *                                      reference point.
1292
-     * @param array $query_params           Extra conditions on the query.
1293
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
-     *                                      object is returned, otherwise you
1295
-     *                                      can indicate just the columns you
1296
-     *                                      want and a single array indexed by
1297
-     *                                      the columns will be returned.
1298
-     * @return EE_Base_Class|null|array()
1299
-     * @throws EE_Error
1300
-     */
1301
-    public function next(
1302
-        $current_field_value,
1303
-        $field_to_order_by = null,
1304
-        $query_params = array(),
1305
-        $columns_to_select = null
1306
-    ) {
1307
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
-            $columns_to_select);
1309
-        return empty($results) ? null : reset($results);
1310
-    }
1311
-
1312
-
1313
-
1314
-    /**
1315
-     * Returns the previous item in sequence from the given value as found in
1316
-     * the database matching the given query conditions.
1317
-     *
1318
-     * @param mixed $current_field_value    Value used for the reference point.
1319
-     * @param null  $field_to_order_by      What field is used for the
1320
-     *                                      reference point.
1321
-     * @param array $query_params           Extra conditions on the query.
1322
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
-     *                                      object is returned, otherwise you
1324
-     *                                      can indicate just the columns you
1325
-     *                                      want and a single array indexed by
1326
-     *                                      the columns will be returned.
1327
-     * @return EE_Base_Class|null|array()
1328
-     * @throws EE_Error
1329
-     */
1330
-    public function previous(
1331
-        $current_field_value,
1332
-        $field_to_order_by = null,
1333
-        $query_params = array(),
1334
-        $columns_to_select = null
1335
-    ) {
1336
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
-            $columns_to_select);
1338
-        return empty($results) ? null : reset($results);
1339
-    }
1340
-
1341
-
1342
-
1343
-    /**
1344
-     * Returns the a consecutive number of items in sequence from the given
1345
-     * value as found in the database matching the given query conditions.
1346
-     *
1347
-     * @param mixed  $current_field_value   Value used for the reference point.
1348
-     * @param string $operand               What operand is used for the sequence.
1349
-     * @param string $field_to_order_by     What field is used for the reference point.
1350
-     * @param int    $limit                 How many to return.
1351
-     * @param array  $query_params          Extra conditions on the query.
1352
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
-     *                                      otherwise you can indicate just the columns you want returned.
1354
-     * @return EE_Base_Class[]|array
1355
-     * @throws EE_Error
1356
-     */
1357
-    protected function _get_consecutive(
1358
-        $current_field_value,
1359
-        $operand = '>',
1360
-        $field_to_order_by = null,
1361
-        $limit = 1,
1362
-        $query_params = array(),
1363
-        $columns_to_select = null
1364
-    ) {
1365
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
-        if (empty($field_to_order_by)) {
1367
-            if ($this->has_primary_key_field()) {
1368
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1369
-            } else {
1370
-                if (WP_DEBUG) {
1371
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1372
-                        'event_espresso'));
1373
-                }
1374
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
-                return array();
1376
-            }
1377
-        }
1378
-        if (! is_array($query_params)) {
1379
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
-                    gettype($query_params)), '4.6.0');
1382
-            $query_params = array();
1383
-        }
1384
-        //let's add the where query param for consecutive look up.
1385
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
-        $query_params['limit'] = $limit;
1387
-        //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
-        $query_params['order_by'] = $operand === '>'
1390
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
-        if (empty($columns_to_select)) {
1394
-            return $this->get_all($query_params);
1395
-        } else {
1396
-            //getting just the fields
1397
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
-        }
1399
-    }
1400
-
1401
-
1402
-
1403
-    /**
1404
-     * This sets the _timezone property after model object has been instantiated.
1405
-     *
1406
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
-     */
1408
-    public function set_timezone($timezone)
1409
-    {
1410
-        if ($timezone !== null) {
1411
-            $this->_timezone = $timezone;
1412
-        }
1413
-        //note we need to loop through relations and set the timezone on those objects as well.
1414
-        foreach ($this->_model_relations as $relation) {
1415
-            $relation->set_timezone($timezone);
1416
-        }
1417
-        //and finally we do the same for any datetime fields
1418
-        foreach ($this->_fields as $field) {
1419
-            if ($field instanceof EE_Datetime_Field) {
1420
-                $field->set_timezone($timezone);
1421
-            }
1422
-        }
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     * This just returns whatever is set for the current timezone.
1429
-     *
1430
-     * @access public
1431
-     * @return string
1432
-     */
1433
-    public function get_timezone()
1434
-    {
1435
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
-        if (empty($this->_timezone)) {
1437
-            foreach ($this->_fields as $field) {
1438
-                if ($field instanceof EE_Datetime_Field) {
1439
-                    $this->set_timezone($field->get_timezone());
1440
-                    break;
1441
-                }
1442
-            }
1443
-        }
1444
-        //if timezone STILL empty then return the default timezone for the site.
1445
-        if (empty($this->_timezone)) {
1446
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
-        }
1448
-        return $this->_timezone;
1449
-    }
1450
-
1451
-
1452
-
1453
-    /**
1454
-     * This returns the date formats set for the given field name and also ensures that
1455
-     * $this->_timezone property is set correctly.
1456
-     *
1457
-     * @since 4.6.x
1458
-     * @param string $field_name The name of the field the formats are being retrieved for.
1459
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
-     */
1463
-    public function get_formats_for($field_name, $pretty = false)
1464
-    {
1465
-        $field_settings = $this->field_settings_for($field_name);
1466
-        //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469
-                'event_espresso'), $field_name));
1470
-        }
1471
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
-        //the field.
1473
-        $this->_timezone = $field_settings->get_timezone();
1474
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
-    }
1476
-
1477
-
1478
-
1479
-    /**
1480
-     * This returns the current time in a format setup for a query on this model.
1481
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
-     * it will return:
1483
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
-     *  NOW
1485
-     *  - or a unix timestamp (equivalent to time())
1486
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
-     * @since 4.6.x
1490
-     * @param string $field_name       The field the current time is needed for.
1491
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
-     *                                 formatted string matching the set format for the field in the set timezone will
1493
-     *                                 be returned.
1494
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
-     *                                 exception is triggered.
1498
-     */
1499
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
-    {
1501
-        $formats = $this->get_formats_for($field_name);
1502
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
-        if ($timestamp) {
1504
-            return $DateTime->format('U');
1505
-        }
1506
-        //not returning timestamp, so return formatted string in timezone.
1507
-        switch ($what) {
1508
-            case 'time' :
1509
-                return $DateTime->format($formats[1]);
1510
-                break;
1511
-            case 'date' :
1512
-                return $DateTime->format($formats[0]);
1513
-                break;
1514
-            default :
1515
-                return $DateTime->format(implode(' ', $formats));
1516
-                break;
1517
-        }
1518
-    }
1519
-
1520
-
1521
-
1522
-    /**
1523
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
-     * for the model are.  Returns a DateTime object.
1525
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
-     * ignored.
1528
-     *
1529
-     * @param string $field_name      The field being setup.
1530
-     * @param string $timestring      The date time string being used.
1531
-     * @param string $incoming_format The format for the time string.
1532
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
-     *                                format is
1535
-     *                                'U', this is ignored.
1536
-     * @return DateTime
1537
-     * @throws EE_Error
1538
-     */
1539
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
-    {
1541
-        //just using this to ensure the timezone is set correctly internally
1542
-        $this->get_formats_for($field_name);
1543
-        //load EEH_DTT_Helper
1544
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
-    }
1548
-
1549
-
1550
-
1551
-    /**
1552
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
-     *
1554
-     * @return EE_Table_Base[]
1555
-     */
1556
-    public function get_tables()
1557
-    {
1558
-        return $this->_tables;
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
-     * model object with EVT_ID = 1
1570
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
-     * are not specified)
1575
-     *
1576
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1581
-     *                                         ID=34, we'd use this method as follows:
1582
-     *                                         EEM_Transaction::instance()->update(
1583
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
-     *                                         array(array('TXN_ID'=>34)));
1585
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
-     *                                         in client code into what's expected to be stored on each field. Eg,
1587
-     *                                         consider updating Question's QST_admin_label field is of type
1588
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
-     *                                         TRUE, it is assumed that you've already called
1593
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
-     *                                         malicious javascript. However, if
1595
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
-     *                                         and every other field, before insertion. We provide this parameter
1598
-     *                                         because model objects perform their prepare_for_set function on all
1599
-     *                                         their values, and so don't need to be called again (and in many cases,
1600
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
-     *                                         prepare_for_set method...)
1602
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
-     *                                         in this model's entity map according to $fields_n_values that match
1604
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1605
-     *                                         by setting this to FALSE, but be aware that model objects being used
1606
-     *                                         could get out-of-sync with the database
1607
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
-     *                                         bad)
1610
-     * @throws EE_Error
1611
-     */
1612
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
-    {
1614
-        if (! is_array($query_params)) {
1615
-            EE_Error::doing_it_wrong('EEM_Base::update',
1616
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
-                    gettype($query_params)), '4.6.0');
1618
-            $query_params = array();
1619
-        }
1620
-        /**
1621
-         * Action called before a model update call has been made.
1622
-         *
1623
-         * @param EEM_Base $model
1624
-         * @param array    $fields_n_values the updated fields and their new values
1625
-         * @param array    $query_params    @see EEM_Base::get_all()
1626
-         */
1627
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
-        /**
1629
-         * Filters the fields about to be updated given the query parameters. You can provide the
1630
-         * $query_params to $this->get_all() to find exactly which records will be updated
1631
-         *
1632
-         * @param array    $fields_n_values fields and their new values
1633
-         * @param EEM_Base $model           the model being queried
1634
-         * @param array    $query_params    see EEM_Base::get_all()
1635
-         */
1636
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
-            $query_params);
1638
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
-        //to do that, for each table, verify that it's PK isn't null.
1640
-        $tables = $this->get_tables();
1641
-        //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1642
-        //NOTE: we should make this code more efficient by NOT querying twice
1643
-        //before the real update, but that needs to first go through ALPHA testing
1644
-        //as it's dangerous. says Mike August 8 2014
1645
-        //we want to make sure the default_where strategy is ignored
1646
-        $this->_ignore_where_strategy = true;
1647
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
-        foreach ($wpdb_select_results as $wpdb_result) {
1649
-            // type cast stdClass as array
1650
-            $wpdb_result = (array)$wpdb_result;
1651
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
-            if ($this->has_primary_key_field()) {
1653
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
-            } else {
1655
-                //if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1656
-                $main_table_pk_value = null;
1657
-            }
1658
-            //if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1659
-            //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1660
-            if (count($tables) > 1) {
1661
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
-                //in that table, and so we'll want to insert one
1663
-                foreach ($tables as $table_obj) {
1664
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
-                    //if there is no private key for this table on the results, it means there's no entry
1666
-                    //in this table, right? so insert a row in the current table, using any fields available
1667
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
-                           && $wpdb_result[$this_table_pk_column])
1669
-                    ) {
1670
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
-                            $main_table_pk_value);
1672
-                        //if we died here, report the error
1673
-                        if (! $success) {
1674
-                            return false;
1675
-                        }
1676
-                    }
1677
-                }
1678
-            }
1679
-            //				//and now check that if we have cached any models by that ID on the model, that
1680
-            //				//they also get updated properly
1681
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
-            //				if( $model_object ){
1683
-            //					foreach( $fields_n_values as $field => $value ){
1684
-            //						$model_object->set($field, $value);
1685
-            //let's make sure default_where strategy is followed now
1686
-            $this->_ignore_where_strategy = false;
1687
-        }
1688
-        //if we want to keep model objects in sync, AND
1689
-        //if this wasn't called from a model object (to update itself)
1690
-        //then we want to make sure we keep all the existing
1691
-        //model objects in sync with the db
1692
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
-            if ($this->has_primary_key_field()) {
1694
-                $model_objs_affected_ids = $this->get_col($query_params);
1695
-            } else {
1696
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
-                $model_objs_affected_ids = array();
1699
-                foreach ($models_affected_key_columns as $row) {
1700
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1701
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
-                }
1703
-            }
1704
-            if (! $model_objs_affected_ids) {
1705
-                //wait wait wait- if nothing was affected let's stop here
1706
-                return 0;
1707
-            }
1708
-            foreach ($model_objs_affected_ids as $id) {
1709
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
-                if ($model_obj_in_entity_map) {
1711
-                    foreach ($fields_n_values as $field => $new_value) {
1712
-                        $model_obj_in_entity_map->set($field, $new_value);
1713
-                    }
1714
-                }
1715
-            }
1716
-            //if there is a primary key on this model, we can now do a slight optimization
1717
-            if ($this->has_primary_key_field()) {
1718
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
-                $query_params = array(
1720
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
-                    'limit'                    => count($model_objs_affected_ids),
1722
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
-                );
1724
-            }
1725
-        }
1726
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
-        $SQL = "UPDATE "
1728
-               . $model_query_info->get_full_join_sql()
1729
-               . " SET "
1730
-               . $this->_construct_update_sql($fields_n_values)
1731
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
-        /**
1734
-         * Action called after a model update call has been made.
1735
-         *
1736
-         * @param EEM_Base $model
1737
-         * @param array    $fields_n_values the updated fields and their new values
1738
-         * @param array    $query_params    @see EEM_Base::get_all()
1739
-         * @param int      $rows_affected
1740
-         */
1741
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
-        return $rows_affected;//how many supposedly got updated
1743
-    }
1744
-
1745
-
1746
-
1747
-    /**
1748
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
-     * are teh values of the field specified (or by default the primary key field)
1750
-     * that matched the query params. Note that you should pass the name of the
1751
-     * model FIELD, not the database table's column name.
1752
-     *
1753
-     * @param array  $query_params @see EEM_Base::get_all()
1754
-     * @param string $field_to_select
1755
-     * @return array just like $wpdb->get_col()
1756
-     * @throws EE_Error
1757
-     */
1758
-    public function get_col($query_params = array(), $field_to_select = null)
1759
-    {
1760
-        if ($field_to_select) {
1761
-            $field = $this->field_settings_for($field_to_select);
1762
-        } elseif ($this->has_primary_key_field()) {
1763
-            $field = $this->get_primary_key_field();
1764
-        } else {
1765
-            //no primary key, just grab the first column
1766
-            $field = reset($this->field_settings());
1767
-        }
1768
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
-        $select_expressions = $field->get_qualified_column();
1770
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
-        return $this->_do_wpdb_query('get_col', array($SQL));
1772
-    }
1773
-
1774
-
1775
-
1776
-    /**
1777
-     * Returns a single column value for a single row from the database
1778
-     *
1779
-     * @param array  $query_params    @see EEM_Base::get_all()
1780
-     * @param string $field_to_select @see EEM_Base::get_col()
1781
-     * @return string
1782
-     * @throws EE_Error
1783
-     */
1784
-    public function get_var($query_params = array(), $field_to_select = null)
1785
-    {
1786
-        $query_params['limit'] = 1;
1787
-        $col = $this->get_col($query_params, $field_to_select);
1788
-        if (! empty($col)) {
1789
-            return reset($col);
1790
-        } else {
1791
-            return null;
1792
-        }
1793
-    }
1794
-
1795
-
1796
-
1797
-    /**
1798
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
-     * injection, but currently no further filtering is done
1801
-     *
1802
-     * @global      $wpdb
1803
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
-     *                               be updated to in the DB
1805
-     * @return string of SQL
1806
-     * @throws EE_Error
1807
-     */
1808
-    public function _construct_update_sql($fields_n_values)
1809
-    {
1810
-        /** @type WPDB $wpdb */
1811
-        global $wpdb;
1812
-        $cols_n_values = array();
1813
-        foreach ($fields_n_values as $field_name => $value) {
1814
-            $field_obj = $this->field_settings_for($field_name);
1815
-            //if the value is NULL, we want to assign the value to that.
1816
-            //wpdb->prepare doesn't really handle that properly
1817
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
-            $value_sql = $prepared_value === null ? 'NULL'
1819
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
-        }
1822
-        return implode(",", $cols_n_values);
1823
-    }
1824
-
1825
-
1826
-
1827
-    /**
1828
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
-     * Performs a HARD delete, meaning the database row should always be removed,
1830
-     * not just have a flag field on it switched
1831
-     * Wrapper for EEM_Base::delete_permanently()
1832
-     *
1833
-     * @param mixed $id
1834
-     * @return boolean whether the row got deleted or not
1835
-     * @throws EE_Error
1836
-     */
1837
-    public function delete_permanently_by_ID($id)
1838
-    {
1839
-        return $this->delete_permanently(
1840
-            array(
1841
-                array($this->get_primary_key_field()->get_name() => $id),
1842
-                'limit' => 1,
1843
-            )
1844
-        );
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
-     * Wrapper for EEM_Base::delete()
1852
-     *
1853
-     * @param mixed $id
1854
-     * @return boolean whether the row got deleted or not
1855
-     * @throws EE_Error
1856
-     */
1857
-    public function delete_by_ID($id)
1858
-    {
1859
-        return $this->delete(
1860
-            array(
1861
-                array($this->get_primary_key_field()->get_name() => $id),
1862
-                'limit' => 1,
1863
-            )
1864
-        );
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1871
-     * meaning if the model has a field that indicates its been "trashed" or
1872
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1873
-     *
1874
-     * @see EEM_Base::delete_permanently
1875
-     * @param array   $query_params
1876
-     * @param boolean $allow_blocking
1877
-     * @return int how many rows got deleted
1878
-     * @throws EE_Error
1879
-     */
1880
-    public function delete($query_params, $allow_blocking = true)
1881
-    {
1882
-        return $this->delete_permanently($query_params, $allow_blocking);
1883
-    }
1884
-
1885
-
1886
-
1887
-    /**
1888
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1889
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
-     * as archived, not actually deleted
1891
-     *
1892
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
-     *                                deletes regardless of other objects which may depend on it. Its generally
1896
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
-     *                                DB
1898
-     * @return int how many rows got deleted
1899
-     * @throws EE_Error
1900
-     */
1901
-    public function delete_permanently($query_params, $allow_blocking = true)
1902
-    {
1903
-        /**
1904
-         * Action called just before performing a real deletion query. You can use the
1905
-         * model and its $query_params to find exactly which items will be deleted
1906
-         *
1907
-         * @param EEM_Base $model
1908
-         * @param array    $query_params   @see EEM_Base::get_all()
1909
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1910
-         *                                 to block (prevent) this deletion
1911
-         */
1912
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
-        //some MySQL databases may be running safe mode, which may restrict
1914
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
-        //to delete them
1917
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1919
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1920
-            $columns_and_ids_for_deleting
1921
-        );
1922
-        /**
1923
-         * Allows client code to act on the items being deleted before the query is actually executed.
1924
-         *
1925
-         * @param EEM_Base $this  The model instance being acted on.
1926
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1927
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1928
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1929
-         *                                                  derived from the incoming query parameters.
1930
-         *                                                  @see details on the structure of this array in the phpdocs
1931
-         *                                                  for the `_get_ids_for_delete_method`
1932
-         *
1933
-         */
1934
-        do_action('AHEE__EEM_Base__delete__before_query',
1935
-            $this,
1936
-            $query_params,
1937
-            $allow_blocking,
1938
-            $columns_and_ids_for_deleting
1939
-        );
1940
-        if ($deletion_where_query_part) {
1941
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1942
-            $table_aliases = array_keys($this->_tables);
1943
-            $SQL = "DELETE "
1944
-                   . implode(", ", $table_aliases)
1945
-                   . " FROM "
1946
-                   . $model_query_info->get_full_join_sql()
1947
-                   . " WHERE "
1948
-                   . $deletion_where_query_part;
1949
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1950
-        } else {
1951
-            $rows_deleted = 0;
1952
-        }
1953
-
1954
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1955
-        //there was no error with the delete query.
1956
-        if ($this->has_primary_key_field()
1957
-            && $rows_deleted !== false
1958
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1959
-        ) {
1960
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1961
-            foreach ($ids_for_removal as $id) {
1962
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1963
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1964
-                }
1965
-            }
1966
-
1967
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1968
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1969
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1970
-            // (although it is possible).
1971
-            //Note this can be skipped by using the provided filter and returning false.
1972
-            if (apply_filters(
1973
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1974
-                ! $this instanceof EEM_Extra_Meta,
1975
-                $this
1976
-            )) {
1977
-                EEM_Extra_Meta::instance()->delete_permanently(array(
1978
-                    0 => array(
1979
-                        'EXM_type' => $this->get_this_model_name(),
1980
-                        'OBJ_ID'   => array(
1981
-                            'IN',
1982
-                            $ids_for_removal
1983
-                        )
1984
-                    )
1985
-                ));
1986
-            }
1987
-        }
1988
-
1989
-        /**
1990
-         * Action called just after performing a real deletion query. Although at this point the
1991
-         * items should have been deleted
1992
-         *
1993
-         * @param EEM_Base $model
1994
-         * @param array    $query_params @see EEM_Base::get_all()
1995
-         * @param int      $rows_deleted
1996
-         */
1997
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1998
-        return $rows_deleted;//how many supposedly got deleted
1999
-    }
2000
-
2001
-
2002
-
2003
-    /**
2004
-     * Checks all the relations that throw error messages when there are blocking related objects
2005
-     * for related model objects. If there are any related model objects on those relations,
2006
-     * adds an EE_Error, and return true
2007
-     *
2008
-     * @param EE_Base_Class|int $this_model_obj_or_id
2009
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2010
-     *                                                 should be ignored when determining whether there are related
2011
-     *                                                 model objects which block this model object's deletion. Useful
2012
-     *                                                 if you know A is related to B and are considering deleting A,
2013
-     *                                                 but want to see if A has any other objects blocking its deletion
2014
-     *                                                 before removing the relation between A and B
2015
-     * @return boolean
2016
-     * @throws EE_Error
2017
-     */
2018
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2019
-    {
2020
-        //first, if $ignore_this_model_obj was supplied, get its model
2021
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2022
-            $ignored_model = $ignore_this_model_obj->get_model();
2023
-        } else {
2024
-            $ignored_model = null;
2025
-        }
2026
-        //now check all the relations of $this_model_obj_or_id and see if there
2027
-        //are any related model objects blocking it?
2028
-        $is_blocked = false;
2029
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2030
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2031
-                //if $ignore_this_model_obj was supplied, then for the query
2032
-                //on that model needs to be told to ignore $ignore_this_model_obj
2033
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2034
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2035
-                        array(
2036
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2037
-                                '!=',
2038
-                                $ignore_this_model_obj->ID(),
2039
-                            ),
2040
-                        ),
2041
-                    ));
2042
-                } else {
2043
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2044
-                }
2045
-                if ($related_model_objects) {
2046
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2047
-                    $is_blocked = true;
2048
-                }
2049
-            }
2050
-        }
2051
-        return $is_blocked;
2052
-    }
2053
-
2054
-
2055
-    /**
2056
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2057
-     * @param array $row_results_for_deleting
2058
-     * @param bool  $allow_blocking
2059
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2060
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2061
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2062
-     *                 deleted. Example:
2063
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2064
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2065
-     *                 where each element is a group of columns and values that get deleted. Example:
2066
-     *                      array(
2067
-     *                          0 => array(
2068
-     *                              'Term_Relationship.object_id' => 1
2069
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2070
-     *                          ),
2071
-     *                          1 => array(
2072
-     *                              'Term_Relationship.object_id' => 1
2073
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2074
-     *                          )
2075
-     *                      )
2076
-     * @throws EE_Error
2077
-     */
2078
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2079
-    {
2080
-        $ids_to_delete_indexed_by_column = array();
2081
-        if ($this->has_primary_key_field()) {
2082
-            $primary_table = $this->_get_main_table();
2083
-            $other_tables = $this->_get_other_tables();
2084
-            $ids_to_delete_indexed_by_column = $query = array();
2085
-            foreach ($row_results_for_deleting as $item_to_delete) {
2086
-                //before we mark this item for deletion,
2087
-                //make sure there's no related entities blocking its deletion (if we're checking)
2088
-                if (
2089
-                    $allow_blocking
2090
-                    && $this->delete_is_blocked_by_related_models(
2091
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2092
-                    )
2093
-                ) {
2094
-                    continue;
2095
-                }
2096
-                //primary table deletes
2097
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2098
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2099
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2100
-                }
2101
-            }
2102
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2103
-            $fields = $this->get_combined_primary_key_fields();
2104
-            foreach ($row_results_for_deleting as $item_to_delete) {
2105
-                $ids_to_delete_indexed_by_column_for_row = array();
2106
-                foreach ($fields as $cpk_field) {
2107
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2108
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2109
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2110
-                    }
2111
-                }
2112
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2113
-            }
2114
-        } else {
2115
-            //so there's no primary key and no combined key...
2116
-            //sorry, can't help you
2117
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2118
-                "event_espresso"), get_class($this)));
2119
-        }
2120
-        return $ids_to_delete_indexed_by_column;
2121
-    }
2122
-
2123
-
2124
-    /**
2125
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2126
-     * the corresponding query_part for the query performing the delete.
2127
-     *
2128
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2129
-     * @return string
2130
-     * @throws EE_Error
2131
-     */
2132
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2133
-        $query_part = '';
2134
-        if (empty($ids_to_delete_indexed_by_column)) {
2135
-            return $query_part;
2136
-        } elseif ($this->has_primary_key_field()) {
2137
-            $query = array();
2138
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2139
-                //make sure we have unique $ids
2140
-                $ids = array_unique($ids);
2141
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2142
-            }
2143
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2144
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2145
-            $ways_to_identify_a_row = array();
2146
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2147
-                $values_for_each_combined_primary_key_for_a_row = array();
2148
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2149
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2150
-                }
2151
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2152
-            }
2153
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2154
-        }
2155
-        return $query_part;
2156
-    }
31
+	//admin posty
32
+	//basic -> grants access to mine -> if they don't have it, select none
33
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
+	//*_published -> grants access to published -> if they dont have it, select non-published
36
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
38
+	//frontend posty
39
+	//by default has access to published
40
+	//basic -> grants access to mine that aren't published, and all published
41
+	//*_others ->grants access to others that aren't private, all mine
42
+	//*_private -> grants full access
43
+	//frontend non-posty
44
+	//like admin posty
45
+	//category-y
46
+	//assign -> grants access to join-table
47
+	//(delete, edit)
48
+	//payment-method-y
49
+	//for each registered payment method,
50
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
+	/**
52
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
55
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
+	 *
57
+	 * @var boolean
58
+	 */
59
+	private $_values_already_prepared_by_model_object = 0;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the data is just like form input that needs to have the model fields'
64
+	 * prepare_for_set and prepare_for_use_in_db called on it
65
+	 */
66
+	const not_prepared_by_model_object = 0;
67
+
68
+	/**
69
+	 * when $_values_already_prepared_by_model_object equals this, we
70
+	 * assume this value is coming from a model object and doesn't need to have
71
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
72
+	 */
73
+	const prepared_by_model_object = 1;
74
+
75
+	/**
76
+	 * when $_values_already_prepared_by_model_object equals this, we assume
77
+	 * the values are already to be used in the database (ie no processing is done
78
+	 * on them by the model's fields)
79
+	 */
80
+	const prepared_for_use_in_db = 2;
81
+
82
+
83
+	protected $singular_item = 'Item';
84
+
85
+	protected $plural_item   = 'Items';
86
+
87
+	/**
88
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
+	 */
90
+	protected $_tables;
91
+
92
+	/**
93
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
+	 *
97
+	 * @var \EE_Model_Field_Base[] $_fields
98
+	 */
99
+	protected $_fields;
100
+
101
+	/**
102
+	 * array of different kinds of relations
103
+	 *
104
+	 * @var \EE_Model_Relation_Base[] $_model_relations
105
+	 */
106
+	protected $_model_relations;
107
+
108
+	/**
109
+	 * @var \EE_Index[] $_indexes
110
+	 */
111
+	protected $_indexes = array();
112
+
113
+	/**
114
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
115
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
+	 * by setting the same columns as used in these queries in the query yourself.
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_default_where_conditions_strategy;
121
+
122
+	/**
123
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
+	 * This is particularly useful when you want something between 'none' and 'default'
125
+	 *
126
+	 * @var EE_Default_Where_Conditions
127
+	 */
128
+	protected $_minimum_where_conditions_strategy;
129
+
130
+	/**
131
+	 * String describing how to find the "owner" of this model's objects.
132
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
+	 * But when there isn't, this indicates which related model, or transiently-related model,
134
+	 * has the foreign key to the wp_users table.
135
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
+	 * related to events, and events have a foreign key to wp_users.
137
+	 * On EEM_Transaction, this would be 'Transaction.Event'
138
+	 *
139
+	 * @var string
140
+	 */
141
+	protected $_model_chain_to_wp_user = '';
142
+
143
+	/**
144
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
+	 * don't need it (particularly CPT models)
146
+	 *
147
+	 * @var bool
148
+	 */
149
+	protected $_ignore_where_strategy = false;
150
+
151
+	/**
152
+	 * String used in caps relating to this model. Eg, if the caps relating to this
153
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
+	 *
155
+	 * @var string. If null it hasn't been initialized yet. If false then we
156
+	 * have indicated capabilities don't apply to this
157
+	 */
158
+	protected $_caps_slug = null;
159
+
160
+	/**
161
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
+	 * and next-level keys are capability names, and each's value is a
163
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
165
+	 * and then each capability in the corresponding sub-array that they're missing
166
+	 * adds the where conditions onto the query.
167
+	 *
168
+	 * @var array
169
+	 */
170
+	protected $_cap_restrictions = array(
171
+		self::caps_read       => array(),
172
+		self::caps_read_admin => array(),
173
+		self::caps_edit       => array(),
174
+		self::caps_delete     => array(),
175
+	);
176
+
177
+	/**
178
+	 * Array defining which cap restriction generators to use to create default
179
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
180
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
+	 * automatically set this to false (not just null).
183
+	 *
184
+	 * @var EE_Restriction_Generator_Base[]
185
+	 */
186
+	protected $_cap_restriction_generators = array();
187
+
188
+	/**
189
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
+	 */
191
+	const caps_read       = 'read';
192
+
193
+	const caps_read_admin = 'read_admin';
194
+
195
+	const caps_edit       = 'edit';
196
+
197
+	const caps_delete     = 'delete';
198
+
199
+	/**
200
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
+	 * maps to 'read' because when looking for relevant permissions we're going to use
203
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
204
+	 *
205
+	 * @var array
206
+	 */
207
+	protected $_cap_contexts_to_cap_action_map = array(
208
+		self::caps_read       => 'read',
209
+		self::caps_read_admin => 'read',
210
+		self::caps_edit       => 'edit',
211
+		self::caps_delete     => 'delete',
212
+	);
213
+
214
+	/**
215
+	 * Timezone
216
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
+	 * EE_Datetime_Field data type will have access to it.
220
+	 *
221
+	 * @var string
222
+	 */
223
+	protected $_timezone;
224
+
225
+
226
+	/**
227
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
+	 * multisite.
229
+	 *
230
+	 * @var int
231
+	 */
232
+	protected static $_model_query_blog_id;
233
+
234
+	/**
235
+	 * A copy of _fields, except the array keys are the model names pointed to by
236
+	 * the field
237
+	 *
238
+	 * @var EE_Model_Field_Base[]
239
+	 */
240
+	private $_cache_foreign_key_to_fields = array();
241
+
242
+	/**
243
+	 * Cached list of all the fields on the model, indexed by their name
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cached_fields = null;
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, except those that are
251
+	 * marked as only pertinent to the database
252
+	 *
253
+	 * @var EE_Model_Field_Base[]
254
+	 */
255
+	private $_cached_fields_non_db_only = null;
256
+
257
+	/**
258
+	 * A cached reference to the primary key for quick lookup
259
+	 *
260
+	 * @var EE_Model_Field_Base
261
+	 */
262
+	private $_primary_key_field = null;
263
+
264
+	/**
265
+	 * Flag indicating whether this model has a primary key or not
266
+	 *
267
+	 * @var boolean
268
+	 */
269
+	protected $_has_primary_key_field = null;
270
+
271
+	/**
272
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
273
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
+	 *
275
+	 * @var boolean
276
+	 */
277
+	protected $_wp_core_model = false;
278
+
279
+	/**
280
+	 *    List of valid operators that can be used for querying.
281
+	 * The keys are all operators we'll accept, the values are the real SQL
282
+	 * operators used
283
+	 *
284
+	 * @var array
285
+	 */
286
+	protected $_valid_operators = array(
287
+		'='           => '=',
288
+		'<='          => '<=',
289
+		'<'           => '<',
290
+		'>='          => '>=',
291
+		'>'           => '>',
292
+		'!='          => '!=',
293
+		'LIKE'        => 'LIKE',
294
+		'like'        => 'LIKE',
295
+		'NOT_LIKE'    => 'NOT LIKE',
296
+		'not_like'    => 'NOT LIKE',
297
+		'NOT LIKE'    => 'NOT LIKE',
298
+		'not like'    => 'NOT LIKE',
299
+		'IN'          => 'IN',
300
+		'in'          => 'IN',
301
+		'NOT_IN'      => 'NOT IN',
302
+		'not_in'      => 'NOT IN',
303
+		'NOT IN'      => 'NOT IN',
304
+		'not in'      => 'NOT IN',
305
+		'between'     => 'BETWEEN',
306
+		'BETWEEN'     => 'BETWEEN',
307
+		'IS_NOT_NULL' => 'IS NOT NULL',
308
+		'is_not_null' => 'IS NOT NULL',
309
+		'IS NOT NULL' => 'IS NOT NULL',
310
+		'is not null' => 'IS NOT NULL',
311
+		'IS_NULL'     => 'IS NULL',
312
+		'is_null'     => 'IS NULL',
313
+		'IS NULL'     => 'IS NULL',
314
+		'is null'     => 'IS NULL',
315
+		'REGEXP'      => 'REGEXP',
316
+		'regexp'      => 'REGEXP',
317
+		'NOT_REGEXP'  => 'NOT REGEXP',
318
+		'not_regexp'  => 'NOT REGEXP',
319
+		'NOT REGEXP'  => 'NOT REGEXP',
320
+		'not regexp'  => 'NOT REGEXP',
321
+	);
322
+
323
+	/**
324
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
+	 *
326
+	 * @var array
327
+	 */
328
+	protected $_in_style_operators = array('IN', 'NOT IN');
329
+
330
+	/**
331
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
+	 * '12-31-2012'"
333
+	 *
334
+	 * @var array
335
+	 */
336
+	protected $_between_style_operators = array('BETWEEN');
337
+
338
+	/**
339
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
+	 * on a join table.
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
+
346
+	/**
347
+	 * Allowed values for $query_params['order'] for ordering in queries
348
+	 *
349
+	 * @var array
350
+	 */
351
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
+
353
+	/**
354
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
356
+	 *
357
+	 * @var array
358
+	 */
359
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
+
361
+	/**
362
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
364
+	 *
365
+	 * @var array
366
+	 */
367
+	private $_allowed_query_params = array(
368
+		0,
369
+		'limit',
370
+		'order_by',
371
+		'group_by',
372
+		'having',
373
+		'force_join',
374
+		'order',
375
+		'on_join_limit',
376
+		'default_where_conditions',
377
+		'caps',
378
+	);
379
+
380
+	/**
381
+	 * All the data types that can be used in $wpdb->prepare statements.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
+
387
+	/**
388
+	 *    EE_Registry Object
389
+	 *
390
+	 * @var    object
391
+	 * @access    protected
392
+	 */
393
+	protected $EE = null;
394
+
395
+
396
+	/**
397
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
+	 *
399
+	 * @var int
400
+	 */
401
+	protected $_show_next_x_db_queries = 0;
402
+
403
+	/**
404
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
+	 *
407
+	 * @var array
408
+	 */
409
+	protected $_custom_selections = array();
410
+
411
+	/**
412
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
+	 * caches every model object we've fetched from the DB on this request
414
+	 *
415
+	 * @var array
416
+	 */
417
+	protected $_entity_map;
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Generates the cap restrictions for the given context, or if they were
654
+	 * already generated just gets what's cached
655
+	 *
656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
657
+	 * @return EE_Default_Where_Conditions[]
658
+	 */
659
+	protected function _generate_cap_restrictions($context)
660
+	{
661
+		if (isset($this->_cap_restriction_generators[$context])
662
+			&& $this->_cap_restriction_generators[$context]
663
+			   instanceof
664
+			   EE_Restriction_Generator_Base
665
+		) {
666
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
+		} else {
668
+			return array();
669
+		}
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Used to set the $_model_query_blog_id static property.
676
+	 *
677
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
+	 *                      value for get_current_blog_id() will be used.
679
+	 */
680
+	public static function set_model_query_blog_id($blog_id = 0)
681
+	{
682
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 * Returns whatever is set as the internal $model_query_blog_id.
689
+	 *
690
+	 * @return int
691
+	 */
692
+	public static function get_model_query_blog_id()
693
+	{
694
+		return EEM_Base::$_model_query_blog_id;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *        This function is a singleton method used to instantiate the Espresso_model object
701
+	 *
702
+	 * @access public
703
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
+	 *                         timezone in the 'timezone_string' wp option)
707
+	 * @return static (as in the concrete child class)
708
+	 */
709
+	public static function instance($timezone = null)
710
+	{
711
+		// check if instance of Espresso_model already exists
712
+		if (! static::$_instance instanceof static) {
713
+			// instantiate Espresso_model
714
+			static::$_instance = new static($timezone);
715
+		}
716
+		//we might have a timezone set, let set_timezone decide what to do with it
717
+		static::$_instance->set_timezone($timezone);
718
+		// Espresso_model object
719
+		return static::$_instance;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * resets the model and returns it
726
+	 *
727
+	 * @param null | string $timezone
728
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
+	 * all its properties reset; if it wasn't instantiated, returns null)
730
+	 */
731
+	public static function reset($timezone = null)
732
+	{
733
+		if (static::$_instance instanceof EEM_Base) {
734
+			//let's try to NOT swap out the current instance for a new one
735
+			//because if someone has a reference to it, we can't remove their reference
736
+			//so it's best to keep using the same reference, but change the original object
737
+			//reset all its properties to their original values as defined in the class
738
+			$r = new ReflectionClass(get_class(static::$_instance));
739
+			$static_properties = $r->getStaticProperties();
740
+			foreach ($r->getDefaultProperties() as $property => $value) {
741
+				//don't set instance to null like it was originally,
742
+				//but it's static anyways, and we're ignoring static properties (for now at least)
743
+				if (! isset($static_properties[$property])) {
744
+					static::$_instance->{$property} = $value;
745
+				}
746
+			}
747
+			//and then directly call its constructor again, like we would if we
748
+			//were creating a new one
749
+			static::$_instance->__construct($timezone);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
+	 *
760
+	 * @param  boolean $translated return localized strings or JUST the array.
761
+	 * @return array
762
+	 * @throws EE_Error
763
+	 */
764
+	public function status_array($translated = false)
765
+	{
766
+		if (! array_key_exists('Status', $this->_model_relations)) {
767
+			return array();
768
+		}
769
+		$model_name = $this->get_this_model_name();
770
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
+		$status_array = array();
773
+		foreach ($stati as $status) {
774
+			$status_array[$status->ID()] = $status->get('STS_code');
775
+		}
776
+		return $translated
777
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
+			: $status_array;
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
+	 *
786
+	 * @param array $query_params             {
787
+	 * @var array $0 (where) array {
788
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
+	 *                                        conditions based on related models (and even
792
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
793
+	 *                                        name. Eg,
794
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
+	 *                                        to Venues (even when each of those models actually consisted of two
802
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
803
+	 *                                        just having
804
+	 *                                        "Venue.VNU_ID", you could have
805
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
+	 *                                        events are related to Registrations, which are related to Attendees). You
807
+	 *                                        can take it even further with
808
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
+	 *                                        (from the default of '='), change the value to an numerically-indexed
810
+	 *                                        array, where the first item in the list is the operator. eg: array(
811
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
819
+	 *                                        the value is a field, simply provide a third array item (true) to the
820
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
+	 *                                        Note: you can also use related model field names like you would any other
823
+	 *                                        field name. eg:
824
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
826
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
833
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
+	 *                                        "stick" until you specify an AND. eg
835
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
840
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
+	 *                                        too, eg:
843
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
848
+	 *                                        the OFFSET, the 2nd is the LIMIT
849
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
+	 *                                        following format array('on_join_limit'
852
+	 *                                        => array( 'table_alias', array(1,2) ) ).
853
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
+	 *                                        values are either 'ASC' or 'DESC'.
855
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
+	 *                                        DESC..." respectively. Like the
858
+	 *                                        'where' conditions, these fields can be on related models. Eg
859
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
861
+	 *                                        Attendee, Price, Datetime, etc.)
862
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
864
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
+	 *                                        order by the primary key. Eg,
867
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
869
+	 *                                        DTT_EVT_start) or
870
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
+	 *                                        'group_by'=>'VNU_ID', or
874
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
+	 *                                        if no
876
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
877
+	 *                                        model's primary key (or combined primary keys). This avoids some
878
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
879
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
+	 *                                        results)
883
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
+	 *                                        array where values are models to be joined in the query.Eg
885
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
887
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
888
+	 *                                        related models which belongs to the current model
889
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
890
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
891
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
894
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
896
+	 *                                        this model's default where conditions added to the query, use
897
+	 *                                        'this_model_only'. If you want to use all default where conditions
898
+	 *                                        (default), set to 'all'.
899
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
+	 *                                        everything? Or should we only show the current user items they should be
902
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
+	 *                                        }
905
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
+	 *                                        array( array(
911
+	 *                                        'OR'=>array(
912
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
+	 *                                        )
915
+	 *                                        ),
916
+	 *                                        'limit'=>10,
917
+	 *                                        'group_by'=>'TXN_ID'
918
+	 *                                        ));
919
+	 *                                        get all the answers to the question titled "shirt size" for event with id
920
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
+	 *                                        'Question.QST_display_text'=>'shirt size',
922
+	 *                                        'Registration.Event.EVT_ID'=>12
923
+	 *                                        ),
924
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
925
+	 *                                        ));
926
+	 * @throws EE_Error
927
+	 */
928
+	public function get_all($query_params = array())
929
+	{
930
+		if (isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Modifies the query parameters so we only get back model objects
942
+	 * that "belong" to the current user
943
+	 *
944
+	 * @param array $query_params @see EEM_Base::get_all()
945
+	 * @return array like EEM_Base::get_all
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = array())
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Returns the name of the field's name that points to the WP_User table
960
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
+	 * foreign key to the WP_User table)
962
+	 *
963
+	 * @return string|boolean string on success, boolean false when there is no
964
+	 * foreign key to the WP_User table
965
+	 */
966
+	public function wp_user_field_name()
967
+	{
968
+		try {
969
+			if (! empty($this->_model_chain_to_wp_user)) {
970
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
+				$last_model_name = end($models_to_follow_to_wp_users);
972
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+			} else {
975
+				$model_with_fk_to_wp_users = $this;
976
+				$model_chain_to_wp_user = '';
977
+			}
978
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+		} catch (EE_Error $e) {
981
+			return false;
982
+		}
983
+	}
984
+
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
+	 * like how registrations don't have a foreign key to wp_users, but the
1007
+	 * events they are for are), or is unrelated to wp users.
1008
+	 * generally available
1009
+	 *
1010
+	 * @return boolean
1011
+	 */
1012
+	public function is_owned()
1013
+	{
1014
+		if ($this->model_chain_to_wp_user()) {
1015
+			return true;
1016
+		} else {
1017
+			try {
1018
+				$this->get_foreign_key_to('WP_User');
1019
+				return true;
1020
+			} catch (EE_Error $e) {
1021
+				return false;
1022
+			}
1023
+		}
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		// remember the custom selections, if any, and type cast as array
1049
+		// (unless $columns_to_select is an object, then just set as an empty array)
1050
+		// Note: (array) 'some string' === array( 'some string' )
1051
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions = $columns_to_select !== null
1054
+			? $this->_construct_select_from_input($columns_to_select)
1055
+			: $this->_construct_default_select_sql($model_query_info);
1056
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1064
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
+	 * take care of joins, field preparation etc.
1066
+	 *
1067
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1071
+	 *                                  override this and set the select to "*", or a specific column name, like
1072
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
+	 *                                  the aliases used to refer to this selection, and values are to be
1075
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
+	 * @throws EE_Error
1079
+	 */
1080
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
+	{
1082
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * For creating a custom select statement
1089
+	 *
1090
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
+	 *                                 SQL, and 1=>is the datatype
1093
+	 * @throws EE_Error
1094
+	 * @return string
1095
+	 */
1096
+	private function _construct_select_from_input($columns_to_select)
1097
+	{
1098
+		if (is_array($columns_to_select)) {
1099
+			$select_sql_array = array();
1100
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+					throw new EE_Error(
1103
+						sprintf(
1104
+							__(
1105
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
+								"event_espresso"
1107
+							),
1108
+							$selection_and_datatype,
1109
+							$alias
1110
+						)
1111
+					);
1112
+				}
1113
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+					throw new EE_Error(
1115
+						sprintf(
1116
+							__(
1117
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
+								"event_espresso"
1119
+							),
1120
+							$selection_and_datatype[1],
1121
+							$selection_and_datatype[0],
1122
+							$alias,
1123
+							implode(",", $this->_valid_wpdb_data_types)
1124
+						)
1125
+					);
1126
+				}
1127
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
+			}
1129
+			$columns_to_select_string = implode(", ", $select_sql_array);
1130
+		} else {
1131
+			$columns_to_select_string = $columns_to_select;
1132
+		}
1133
+		return $columns_to_select_string;
1134
+	}
1135
+
1136
+
1137
+
1138
+	/**
1139
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
+	 *
1141
+	 * @return string
1142
+	 * @throws EE_Error
1143
+	 */
1144
+	public function primary_key_name()
1145
+	{
1146
+		return $this->get_primary_key_field()->get_name();
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
+	 * If there is no primary key on this model, $id is treated as primary key string
1154
+	 *
1155
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1156
+	 * @return EE_Base_Class
1157
+	 */
1158
+	public function get_one_by_ID($id)
1159
+	{
1160
+		if ($this->get_from_entity_map($id)) {
1161
+			return $this->get_from_entity_map($id);
1162
+		}
1163
+		return $this->get_one(
1164
+			$this->alter_query_params_to_restrict_by_ID(
1165
+				$id,
1166
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
+			)
1168
+		);
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Alters query parameters to only get items with this ID are returned.
1175
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
+	 * or could just be a simple primary key ID
1177
+	 *
1178
+	 * @param int   $id
1179
+	 * @param array $query_params
1180
+	 * @return array of normal query params, @see EEM_Base::get_all
1181
+	 * @throws EE_Error
1182
+	 */
1183
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
+	{
1185
+		if (! isset($query_params[0])) {
1186
+			$query_params[0] = array();
1187
+		}
1188
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1189
+		if ($conditions_from_id === null) {
1190
+			$query_params[0][$this->primary_key_name()] = $id;
1191
+		} else {
1192
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1193
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
+		}
1195
+		return $query_params;
1196
+	}
1197
+
1198
+
1199
+
1200
+	/**
1201
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
+	 * array. If no item is found, null is returned.
1203
+	 *
1204
+	 * @param array $query_params like EEM_Base's $query_params variable.
1205
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
+	 * @throws EE_Error
1207
+	 */
1208
+	public function get_one($query_params = array())
1209
+	{
1210
+		if (! is_array($query_params)) {
1211
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
+					gettype($query_params)), '4.6.0');
1214
+			$query_params = array();
1215
+		}
1216
+		$query_params['limit'] = 1;
1217
+		$items = $this->get_all($query_params);
1218
+		if (empty($items)) {
1219
+			return null;
1220
+		} else {
1221
+			return array_shift($items);
1222
+		}
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Returns the next x number of items in sequence from the given value as
1229
+	 * found in the database matching the given query conditions.
1230
+	 *
1231
+	 * @param mixed $current_field_value    Value used for the reference point.
1232
+	 * @param null  $field_to_order_by      What field is used for the
1233
+	 *                                      reference point.
1234
+	 * @param int   $limit                  How many to return.
1235
+	 * @param array $query_params           Extra conditions on the query.
1236
+	 * @param null  $columns_to_select      If left null, then an array of
1237
+	 *                                      EE_Base_Class objects is returned,
1238
+	 *                                      otherwise you can indicate just the
1239
+	 *                                      columns you want returned.
1240
+	 * @return EE_Base_Class[]|array
1241
+	 * @throws EE_Error
1242
+	 */
1243
+	public function next_x(
1244
+		$current_field_value,
1245
+		$field_to_order_by = null,
1246
+		$limit = 1,
1247
+		$query_params = array(),
1248
+		$columns_to_select = null
1249
+	) {
1250
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
+			$columns_to_select);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the previous x number of items in sequence from the given value
1258
+	 * as found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws EE_Error
1271
+	 */
1272
+	public function previous_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = array(),
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
+			$columns_to_select);
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * Returns the next item in sequence from the given value as found in the
1287
+	 * database matching the given query conditions.
1288
+	 *
1289
+	 * @param mixed $current_field_value    Value used for the reference point.
1290
+	 * @param null  $field_to_order_by      What field is used for the
1291
+	 *                                      reference point.
1292
+	 * @param array $query_params           Extra conditions on the query.
1293
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
+	 *                                      object is returned, otherwise you
1295
+	 *                                      can indicate just the columns you
1296
+	 *                                      want and a single array indexed by
1297
+	 *                                      the columns will be returned.
1298
+	 * @return EE_Base_Class|null|array()
1299
+	 * @throws EE_Error
1300
+	 */
1301
+	public function next(
1302
+		$current_field_value,
1303
+		$field_to_order_by = null,
1304
+		$query_params = array(),
1305
+		$columns_to_select = null
1306
+	) {
1307
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
+			$columns_to_select);
1309
+		return empty($results) ? null : reset($results);
1310
+	}
1311
+
1312
+
1313
+
1314
+	/**
1315
+	 * Returns the previous item in sequence from the given value as found in
1316
+	 * the database matching the given query conditions.
1317
+	 *
1318
+	 * @param mixed $current_field_value    Value used for the reference point.
1319
+	 * @param null  $field_to_order_by      What field is used for the
1320
+	 *                                      reference point.
1321
+	 * @param array $query_params           Extra conditions on the query.
1322
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
+	 *                                      object is returned, otherwise you
1324
+	 *                                      can indicate just the columns you
1325
+	 *                                      want and a single array indexed by
1326
+	 *                                      the columns will be returned.
1327
+	 * @return EE_Base_Class|null|array()
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	public function previous(
1331
+		$current_field_value,
1332
+		$field_to_order_by = null,
1333
+		$query_params = array(),
1334
+		$columns_to_select = null
1335
+	) {
1336
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
+			$columns_to_select);
1338
+		return empty($results) ? null : reset($results);
1339
+	}
1340
+
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the a consecutive number of items in sequence from the given
1345
+	 * value as found in the database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed  $current_field_value   Value used for the reference point.
1348
+	 * @param string $operand               What operand is used for the sequence.
1349
+	 * @param string $field_to_order_by     What field is used for the reference point.
1350
+	 * @param int    $limit                 How many to return.
1351
+	 * @param array  $query_params          Extra conditions on the query.
1352
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
+	 *                                      otherwise you can indicate just the columns you want returned.
1354
+	 * @return EE_Base_Class[]|array
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	protected function _get_consecutive(
1358
+		$current_field_value,
1359
+		$operand = '>',
1360
+		$field_to_order_by = null,
1361
+		$limit = 1,
1362
+		$query_params = array(),
1363
+		$columns_to_select = null
1364
+	) {
1365
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
+		if (empty($field_to_order_by)) {
1367
+			if ($this->has_primary_key_field()) {
1368
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1369
+			} else {
1370
+				if (WP_DEBUG) {
1371
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1372
+						'event_espresso'));
1373
+				}
1374
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
+				return array();
1376
+			}
1377
+		}
1378
+		if (! is_array($query_params)) {
1379
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
+					gettype($query_params)), '4.6.0');
1382
+			$query_params = array();
1383
+		}
1384
+		//let's add the where query param for consecutive look up.
1385
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
+		$query_params['limit'] = $limit;
1387
+		//set direction
1388
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+		$query_params['order_by'] = $operand === '>'
1390
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
+		if (empty($columns_to_select)) {
1394
+			return $this->get_all($query_params);
1395
+		} else {
1396
+			//getting just the fields
1397
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
+		}
1399
+	}
1400
+
1401
+
1402
+
1403
+	/**
1404
+	 * This sets the _timezone property after model object has been instantiated.
1405
+	 *
1406
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+	 */
1408
+	public function set_timezone($timezone)
1409
+	{
1410
+		if ($timezone !== null) {
1411
+			$this->_timezone = $timezone;
1412
+		}
1413
+		//note we need to loop through relations and set the timezone on those objects as well.
1414
+		foreach ($this->_model_relations as $relation) {
1415
+			$relation->set_timezone($timezone);
1416
+		}
1417
+		//and finally we do the same for any datetime fields
1418
+		foreach ($this->_fields as $field) {
1419
+			if ($field instanceof EE_Datetime_Field) {
1420
+				$field->set_timezone($timezone);
1421
+			}
1422
+		}
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 * This just returns whatever is set for the current timezone.
1429
+	 *
1430
+	 * @access public
1431
+	 * @return string
1432
+	 */
1433
+	public function get_timezone()
1434
+	{
1435
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
+		if (empty($this->_timezone)) {
1437
+			foreach ($this->_fields as $field) {
1438
+				if ($field instanceof EE_Datetime_Field) {
1439
+					$this->set_timezone($field->get_timezone());
1440
+					break;
1441
+				}
1442
+			}
1443
+		}
1444
+		//if timezone STILL empty then return the default timezone for the site.
1445
+		if (empty($this->_timezone)) {
1446
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
+		}
1448
+		return $this->_timezone;
1449
+	}
1450
+
1451
+
1452
+
1453
+	/**
1454
+	 * This returns the date formats set for the given field name and also ensures that
1455
+	 * $this->_timezone property is set correctly.
1456
+	 *
1457
+	 * @since 4.6.x
1458
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1459
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
+	 * @return array formats in an array with the date format first, and the time format last.
1462
+	 */
1463
+	public function get_formats_for($field_name, $pretty = false)
1464
+	{
1465
+		$field_settings = $this->field_settings_for($field_name);
1466
+		//if not a valid EE_Datetime_Field then throw error
1467
+		if (! $field_settings instanceof EE_Datetime_Field) {
1468
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469
+				'event_espresso'), $field_name));
1470
+		}
1471
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
+		//the field.
1473
+		$this->_timezone = $field_settings->get_timezone();
1474
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
+	}
1476
+
1477
+
1478
+
1479
+	/**
1480
+	 * This returns the current time in a format setup for a query on this model.
1481
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
+	 * it will return:
1483
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
+	 *  NOW
1485
+	 *  - or a unix timestamp (equivalent to time())
1486
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
+	 * @since 4.6.x
1490
+	 * @param string $field_name       The field the current time is needed for.
1491
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
+	 *                                 formatted string matching the set format for the field in the set timezone will
1493
+	 *                                 be returned.
1494
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
+	 *                                 exception is triggered.
1498
+	 */
1499
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
+	{
1501
+		$formats = $this->get_formats_for($field_name);
1502
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
+		if ($timestamp) {
1504
+			return $DateTime->format('U');
1505
+		}
1506
+		//not returning timestamp, so return formatted string in timezone.
1507
+		switch ($what) {
1508
+			case 'time' :
1509
+				return $DateTime->format($formats[1]);
1510
+				break;
1511
+			case 'date' :
1512
+				return $DateTime->format($formats[0]);
1513
+				break;
1514
+			default :
1515
+				return $DateTime->format(implode(' ', $formats));
1516
+				break;
1517
+		}
1518
+	}
1519
+
1520
+
1521
+
1522
+	/**
1523
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
+	 * for the model are.  Returns a DateTime object.
1525
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
+	 * ignored.
1528
+	 *
1529
+	 * @param string $field_name      The field being setup.
1530
+	 * @param string $timestring      The date time string being used.
1531
+	 * @param string $incoming_format The format for the time string.
1532
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
+	 *                                format is
1535
+	 *                                'U', this is ignored.
1536
+	 * @return DateTime
1537
+	 * @throws EE_Error
1538
+	 */
1539
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
+	{
1541
+		//just using this to ensure the timezone is set correctly internally
1542
+		$this->get_formats_for($field_name);
1543
+		//load EEH_DTT_Helper
1544
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
+	}
1548
+
1549
+
1550
+
1551
+	/**
1552
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
+	 *
1554
+	 * @return EE_Table_Base[]
1555
+	 */
1556
+	public function get_tables()
1557
+	{
1558
+		return $this->_tables;
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
+	 * model object with EVT_ID = 1
1570
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
+	 * are not specified)
1575
+	 *
1576
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1581
+	 *                                         ID=34, we'd use this method as follows:
1582
+	 *                                         EEM_Transaction::instance()->update(
1583
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
+	 *                                         array(array('TXN_ID'=>34)));
1585
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1587
+	 *                                         consider updating Question's QST_admin_label field is of type
1588
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
+	 *                                         TRUE, it is assumed that you've already called
1593
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
+	 *                                         malicious javascript. However, if
1595
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
+	 *                                         and every other field, before insertion. We provide this parameter
1598
+	 *                                         because model objects perform their prepare_for_set function on all
1599
+	 *                                         their values, and so don't need to be called again (and in many cases,
1600
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
+	 *                                         prepare_for_set method...)
1602
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
+	 *                                         in this model's entity map according to $fields_n_values that match
1604
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1605
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1606
+	 *                                         could get out-of-sync with the database
1607
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
+	 *                                         bad)
1610
+	 * @throws EE_Error
1611
+	 */
1612
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
+	{
1614
+		if (! is_array($query_params)) {
1615
+			EE_Error::doing_it_wrong('EEM_Base::update',
1616
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
+					gettype($query_params)), '4.6.0');
1618
+			$query_params = array();
1619
+		}
1620
+		/**
1621
+		 * Action called before a model update call has been made.
1622
+		 *
1623
+		 * @param EEM_Base $model
1624
+		 * @param array    $fields_n_values the updated fields and their new values
1625
+		 * @param array    $query_params    @see EEM_Base::get_all()
1626
+		 */
1627
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
+		/**
1629
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1630
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1631
+		 *
1632
+		 * @param array    $fields_n_values fields and their new values
1633
+		 * @param EEM_Base $model           the model being queried
1634
+		 * @param array    $query_params    see EEM_Base::get_all()
1635
+		 */
1636
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
+			$query_params);
1638
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
+		//to do that, for each table, verify that it's PK isn't null.
1640
+		$tables = $this->get_tables();
1641
+		//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1642
+		//NOTE: we should make this code more efficient by NOT querying twice
1643
+		//before the real update, but that needs to first go through ALPHA testing
1644
+		//as it's dangerous. says Mike August 8 2014
1645
+		//we want to make sure the default_where strategy is ignored
1646
+		$this->_ignore_where_strategy = true;
1647
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
+		foreach ($wpdb_select_results as $wpdb_result) {
1649
+			// type cast stdClass as array
1650
+			$wpdb_result = (array)$wpdb_result;
1651
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
+			if ($this->has_primary_key_field()) {
1653
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
+			} else {
1655
+				//if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1656
+				$main_table_pk_value = null;
1657
+			}
1658
+			//if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1659
+			//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1660
+			if (count($tables) > 1) {
1661
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
+				//in that table, and so we'll want to insert one
1663
+				foreach ($tables as $table_obj) {
1664
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
+					//if there is no private key for this table on the results, it means there's no entry
1666
+					//in this table, right? so insert a row in the current table, using any fields available
1667
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
+						   && $wpdb_result[$this_table_pk_column])
1669
+					) {
1670
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
+							$main_table_pk_value);
1672
+						//if we died here, report the error
1673
+						if (! $success) {
1674
+							return false;
1675
+						}
1676
+					}
1677
+				}
1678
+			}
1679
+			//				//and now check that if we have cached any models by that ID on the model, that
1680
+			//				//they also get updated properly
1681
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
+			//				if( $model_object ){
1683
+			//					foreach( $fields_n_values as $field => $value ){
1684
+			//						$model_object->set($field, $value);
1685
+			//let's make sure default_where strategy is followed now
1686
+			$this->_ignore_where_strategy = false;
1687
+		}
1688
+		//if we want to keep model objects in sync, AND
1689
+		//if this wasn't called from a model object (to update itself)
1690
+		//then we want to make sure we keep all the existing
1691
+		//model objects in sync with the db
1692
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
+			if ($this->has_primary_key_field()) {
1694
+				$model_objs_affected_ids = $this->get_col($query_params);
1695
+			} else {
1696
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
+				$model_objs_affected_ids = array();
1699
+				foreach ($models_affected_key_columns as $row) {
1700
+					$combined_index_key = $this->get_index_primary_key_string($row);
1701
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
+				}
1703
+			}
1704
+			if (! $model_objs_affected_ids) {
1705
+				//wait wait wait- if nothing was affected let's stop here
1706
+				return 0;
1707
+			}
1708
+			foreach ($model_objs_affected_ids as $id) {
1709
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
+				if ($model_obj_in_entity_map) {
1711
+					foreach ($fields_n_values as $field => $new_value) {
1712
+						$model_obj_in_entity_map->set($field, $new_value);
1713
+					}
1714
+				}
1715
+			}
1716
+			//if there is a primary key on this model, we can now do a slight optimization
1717
+			if ($this->has_primary_key_field()) {
1718
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
+				$query_params = array(
1720
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
+					'limit'                    => count($model_objs_affected_ids),
1722
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
+				);
1724
+			}
1725
+		}
1726
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
+		$SQL = "UPDATE "
1728
+			   . $model_query_info->get_full_join_sql()
1729
+			   . " SET "
1730
+			   . $this->_construct_update_sql($fields_n_values)
1731
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
+		/**
1734
+		 * Action called after a model update call has been made.
1735
+		 *
1736
+		 * @param EEM_Base $model
1737
+		 * @param array    $fields_n_values the updated fields and their new values
1738
+		 * @param array    $query_params    @see EEM_Base::get_all()
1739
+		 * @param int      $rows_affected
1740
+		 */
1741
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
+		return $rows_affected;//how many supposedly got updated
1743
+	}
1744
+
1745
+
1746
+
1747
+	/**
1748
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
+	 * are teh values of the field specified (or by default the primary key field)
1750
+	 * that matched the query params. Note that you should pass the name of the
1751
+	 * model FIELD, not the database table's column name.
1752
+	 *
1753
+	 * @param array  $query_params @see EEM_Base::get_all()
1754
+	 * @param string $field_to_select
1755
+	 * @return array just like $wpdb->get_col()
1756
+	 * @throws EE_Error
1757
+	 */
1758
+	public function get_col($query_params = array(), $field_to_select = null)
1759
+	{
1760
+		if ($field_to_select) {
1761
+			$field = $this->field_settings_for($field_to_select);
1762
+		} elseif ($this->has_primary_key_field()) {
1763
+			$field = $this->get_primary_key_field();
1764
+		} else {
1765
+			//no primary key, just grab the first column
1766
+			$field = reset($this->field_settings());
1767
+		}
1768
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
+		$select_expressions = $field->get_qualified_column();
1770
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
+		return $this->_do_wpdb_query('get_col', array($SQL));
1772
+	}
1773
+
1774
+
1775
+
1776
+	/**
1777
+	 * Returns a single column value for a single row from the database
1778
+	 *
1779
+	 * @param array  $query_params    @see EEM_Base::get_all()
1780
+	 * @param string $field_to_select @see EEM_Base::get_col()
1781
+	 * @return string
1782
+	 * @throws EE_Error
1783
+	 */
1784
+	public function get_var($query_params = array(), $field_to_select = null)
1785
+	{
1786
+		$query_params['limit'] = 1;
1787
+		$col = $this->get_col($query_params, $field_to_select);
1788
+		if (! empty($col)) {
1789
+			return reset($col);
1790
+		} else {
1791
+			return null;
1792
+		}
1793
+	}
1794
+
1795
+
1796
+
1797
+	/**
1798
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
+	 * injection, but currently no further filtering is done
1801
+	 *
1802
+	 * @global      $wpdb
1803
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
+	 *                               be updated to in the DB
1805
+	 * @return string of SQL
1806
+	 * @throws EE_Error
1807
+	 */
1808
+	public function _construct_update_sql($fields_n_values)
1809
+	{
1810
+		/** @type WPDB $wpdb */
1811
+		global $wpdb;
1812
+		$cols_n_values = array();
1813
+		foreach ($fields_n_values as $field_name => $value) {
1814
+			$field_obj = $this->field_settings_for($field_name);
1815
+			//if the value is NULL, we want to assign the value to that.
1816
+			//wpdb->prepare doesn't really handle that properly
1817
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
+			$value_sql = $prepared_value === null ? 'NULL'
1819
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
+		}
1822
+		return implode(",", $cols_n_values);
1823
+	}
1824
+
1825
+
1826
+
1827
+	/**
1828
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
+	 * Performs a HARD delete, meaning the database row should always be removed,
1830
+	 * not just have a flag field on it switched
1831
+	 * Wrapper for EEM_Base::delete_permanently()
1832
+	 *
1833
+	 * @param mixed $id
1834
+	 * @return boolean whether the row got deleted or not
1835
+	 * @throws EE_Error
1836
+	 */
1837
+	public function delete_permanently_by_ID($id)
1838
+	{
1839
+		return $this->delete_permanently(
1840
+			array(
1841
+				array($this->get_primary_key_field()->get_name() => $id),
1842
+				'limit' => 1,
1843
+			)
1844
+		);
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
+	 * Wrapper for EEM_Base::delete()
1852
+	 *
1853
+	 * @param mixed $id
1854
+	 * @return boolean whether the row got deleted or not
1855
+	 * @throws EE_Error
1856
+	 */
1857
+	public function delete_by_ID($id)
1858
+	{
1859
+		return $this->delete(
1860
+			array(
1861
+				array($this->get_primary_key_field()->get_name() => $id),
1862
+				'limit' => 1,
1863
+			)
1864
+		);
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1871
+	 * meaning if the model has a field that indicates its been "trashed" or
1872
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1873
+	 *
1874
+	 * @see EEM_Base::delete_permanently
1875
+	 * @param array   $query_params
1876
+	 * @param boolean $allow_blocking
1877
+	 * @return int how many rows got deleted
1878
+	 * @throws EE_Error
1879
+	 */
1880
+	public function delete($query_params, $allow_blocking = true)
1881
+	{
1882
+		return $this->delete_permanently($query_params, $allow_blocking);
1883
+	}
1884
+
1885
+
1886
+
1887
+	/**
1888
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1889
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
+	 * as archived, not actually deleted
1891
+	 *
1892
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1896
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
+	 *                                DB
1898
+	 * @return int how many rows got deleted
1899
+	 * @throws EE_Error
1900
+	 */
1901
+	public function delete_permanently($query_params, $allow_blocking = true)
1902
+	{
1903
+		/**
1904
+		 * Action called just before performing a real deletion query. You can use the
1905
+		 * model and its $query_params to find exactly which items will be deleted
1906
+		 *
1907
+		 * @param EEM_Base $model
1908
+		 * @param array    $query_params   @see EEM_Base::get_all()
1909
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1910
+		 *                                 to block (prevent) this deletion
1911
+		 */
1912
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
+		//some MySQL databases may be running safe mode, which may restrict
1914
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
+		//to delete them
1917
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1919
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1920
+			$columns_and_ids_for_deleting
1921
+		);
1922
+		/**
1923
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1924
+		 *
1925
+		 * @param EEM_Base $this  The model instance being acted on.
1926
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1927
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1928
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1929
+		 *                                                  derived from the incoming query parameters.
1930
+		 *                                                  @see details on the structure of this array in the phpdocs
1931
+		 *                                                  for the `_get_ids_for_delete_method`
1932
+		 *
1933
+		 */
1934
+		do_action('AHEE__EEM_Base__delete__before_query',
1935
+			$this,
1936
+			$query_params,
1937
+			$allow_blocking,
1938
+			$columns_and_ids_for_deleting
1939
+		);
1940
+		if ($deletion_where_query_part) {
1941
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1942
+			$table_aliases = array_keys($this->_tables);
1943
+			$SQL = "DELETE "
1944
+				   . implode(", ", $table_aliases)
1945
+				   . " FROM "
1946
+				   . $model_query_info->get_full_join_sql()
1947
+				   . " WHERE "
1948
+				   . $deletion_where_query_part;
1949
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1950
+		} else {
1951
+			$rows_deleted = 0;
1952
+		}
1953
+
1954
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1955
+		//there was no error with the delete query.
1956
+		if ($this->has_primary_key_field()
1957
+			&& $rows_deleted !== false
1958
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1959
+		) {
1960
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1961
+			foreach ($ids_for_removal as $id) {
1962
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1963
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1964
+				}
1965
+			}
1966
+
1967
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1968
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1969
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1970
+			// (although it is possible).
1971
+			//Note this can be skipped by using the provided filter and returning false.
1972
+			if (apply_filters(
1973
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1974
+				! $this instanceof EEM_Extra_Meta,
1975
+				$this
1976
+			)) {
1977
+				EEM_Extra_Meta::instance()->delete_permanently(array(
1978
+					0 => array(
1979
+						'EXM_type' => $this->get_this_model_name(),
1980
+						'OBJ_ID'   => array(
1981
+							'IN',
1982
+							$ids_for_removal
1983
+						)
1984
+					)
1985
+				));
1986
+			}
1987
+		}
1988
+
1989
+		/**
1990
+		 * Action called just after performing a real deletion query. Although at this point the
1991
+		 * items should have been deleted
1992
+		 *
1993
+		 * @param EEM_Base $model
1994
+		 * @param array    $query_params @see EEM_Base::get_all()
1995
+		 * @param int      $rows_deleted
1996
+		 */
1997
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1998
+		return $rows_deleted;//how many supposedly got deleted
1999
+	}
2000
+
2001
+
2002
+
2003
+	/**
2004
+	 * Checks all the relations that throw error messages when there are blocking related objects
2005
+	 * for related model objects. If there are any related model objects on those relations,
2006
+	 * adds an EE_Error, and return true
2007
+	 *
2008
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2009
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2010
+	 *                                                 should be ignored when determining whether there are related
2011
+	 *                                                 model objects which block this model object's deletion. Useful
2012
+	 *                                                 if you know A is related to B and are considering deleting A,
2013
+	 *                                                 but want to see if A has any other objects blocking its deletion
2014
+	 *                                                 before removing the relation between A and B
2015
+	 * @return boolean
2016
+	 * @throws EE_Error
2017
+	 */
2018
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2019
+	{
2020
+		//first, if $ignore_this_model_obj was supplied, get its model
2021
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2022
+			$ignored_model = $ignore_this_model_obj->get_model();
2023
+		} else {
2024
+			$ignored_model = null;
2025
+		}
2026
+		//now check all the relations of $this_model_obj_or_id and see if there
2027
+		//are any related model objects blocking it?
2028
+		$is_blocked = false;
2029
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2030
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2031
+				//if $ignore_this_model_obj was supplied, then for the query
2032
+				//on that model needs to be told to ignore $ignore_this_model_obj
2033
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2034
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2035
+						array(
2036
+							$ignored_model->get_primary_key_field()->get_name() => array(
2037
+								'!=',
2038
+								$ignore_this_model_obj->ID(),
2039
+							),
2040
+						),
2041
+					));
2042
+				} else {
2043
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2044
+				}
2045
+				if ($related_model_objects) {
2046
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2047
+					$is_blocked = true;
2048
+				}
2049
+			}
2050
+		}
2051
+		return $is_blocked;
2052
+	}
2053
+
2054
+
2055
+	/**
2056
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2057
+	 * @param array $row_results_for_deleting
2058
+	 * @param bool  $allow_blocking
2059
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2060
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2061
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2062
+	 *                 deleted. Example:
2063
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2064
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2065
+	 *                 where each element is a group of columns and values that get deleted. Example:
2066
+	 *                      array(
2067
+	 *                          0 => array(
2068
+	 *                              'Term_Relationship.object_id' => 1
2069
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2070
+	 *                          ),
2071
+	 *                          1 => array(
2072
+	 *                              'Term_Relationship.object_id' => 1
2073
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2074
+	 *                          )
2075
+	 *                      )
2076
+	 * @throws EE_Error
2077
+	 */
2078
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2079
+	{
2080
+		$ids_to_delete_indexed_by_column = array();
2081
+		if ($this->has_primary_key_field()) {
2082
+			$primary_table = $this->_get_main_table();
2083
+			$other_tables = $this->_get_other_tables();
2084
+			$ids_to_delete_indexed_by_column = $query = array();
2085
+			foreach ($row_results_for_deleting as $item_to_delete) {
2086
+				//before we mark this item for deletion,
2087
+				//make sure there's no related entities blocking its deletion (if we're checking)
2088
+				if (
2089
+					$allow_blocking
2090
+					&& $this->delete_is_blocked_by_related_models(
2091
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2092
+					)
2093
+				) {
2094
+					continue;
2095
+				}
2096
+				//primary table deletes
2097
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2098
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2099
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2100
+				}
2101
+			}
2102
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2103
+			$fields = $this->get_combined_primary_key_fields();
2104
+			foreach ($row_results_for_deleting as $item_to_delete) {
2105
+				$ids_to_delete_indexed_by_column_for_row = array();
2106
+				foreach ($fields as $cpk_field) {
2107
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2108
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2109
+							$item_to_delete[$cpk_field->get_qualified_column()];
2110
+					}
2111
+				}
2112
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2113
+			}
2114
+		} else {
2115
+			//so there's no primary key and no combined key...
2116
+			//sorry, can't help you
2117
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2118
+				"event_espresso"), get_class($this)));
2119
+		}
2120
+		return $ids_to_delete_indexed_by_column;
2121
+	}
2122
+
2123
+
2124
+	/**
2125
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2126
+	 * the corresponding query_part for the query performing the delete.
2127
+	 *
2128
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2129
+	 * @return string
2130
+	 * @throws EE_Error
2131
+	 */
2132
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2133
+		$query_part = '';
2134
+		if (empty($ids_to_delete_indexed_by_column)) {
2135
+			return $query_part;
2136
+		} elseif ($this->has_primary_key_field()) {
2137
+			$query = array();
2138
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2139
+				//make sure we have unique $ids
2140
+				$ids = array_unique($ids);
2141
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2142
+			}
2143
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2144
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2145
+			$ways_to_identify_a_row = array();
2146
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2147
+				$values_for_each_combined_primary_key_for_a_row = array();
2148
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2149
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2150
+				}
2151
+				$ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2152
+			}
2153
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2154
+		}
2155
+		return $query_part;
2156
+	}
2157 2157
     
2158 2158
 
2159 2159
 
2160 2160
 
2161
-    /**
2162
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2163
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2164
-     * column
2165
-     *
2166
-     * @param array  $query_params   like EEM_Base::get_all's
2167
-     * @param string $field_to_count field on model to count by (not column name)
2168
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2169
-     *                               that by the setting $distinct to TRUE;
2170
-     * @return int
2171
-     * @throws EE_Error
2172
-     */
2173
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2174
-    {
2175
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2176
-        if ($field_to_count) {
2177
-            $field_obj = $this->field_settings_for($field_to_count);
2178
-            $column_to_count = $field_obj->get_qualified_column();
2179
-        } elseif ($this->has_primary_key_field()) {
2180
-            $pk_field_obj = $this->get_primary_key_field();
2181
-            $column_to_count = $pk_field_obj->get_qualified_column();
2182
-        } else {
2183
-            //there's no primary key
2184
-            //if we're counting distinct items, and there's no primary key,
2185
-            //we need to list out the columns for distinction;
2186
-            //otherwise we can just use star
2187
-            if ($distinct) {
2188
-                $columns_to_use = array();
2189
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2190
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2191
-                }
2192
-                $column_to_count = implode(',', $columns_to_use);
2193
-            } else {
2194
-                $column_to_count = '*';
2195
-            }
2196
-        }
2197
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2198
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2199
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2200
-    }
2201
-
2202
-
2203
-
2204
-    /**
2205
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2206
-     *
2207
-     * @param array  $query_params like EEM_Base::get_all
2208
-     * @param string $field_to_sum name of field (array key in $_fields array)
2209
-     * @return float
2210
-     * @throws EE_Error
2211
-     */
2212
-    public function sum($query_params, $field_to_sum = null)
2213
-    {
2214
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2215
-        if ($field_to_sum) {
2216
-            $field_obj = $this->field_settings_for($field_to_sum);
2217
-        } else {
2218
-            $field_obj = $this->get_primary_key_field();
2219
-        }
2220
-        $column_to_count = $field_obj->get_qualified_column();
2221
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2222
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2223
-        $data_type = $field_obj->get_wpdb_data_type();
2224
-        if ($data_type === '%d' || $data_type === '%s') {
2225
-            return (float)$return_value;
2226
-        } else {//must be %f
2227
-            return (float)$return_value;
2228
-        }
2229
-    }
2230
-
2231
-
2232
-
2233
-    /**
2234
-     * Just calls the specified method on $wpdb with the given arguments
2235
-     * Consolidates a little extra error handling code
2236
-     *
2237
-     * @param string $wpdb_method
2238
-     * @param array  $arguments_to_provide
2239
-     * @throws EE_Error
2240
-     * @global wpdb  $wpdb
2241
-     * @return mixed
2242
-     */
2243
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2244
-    {
2245
-        //if we're in maintenance mode level 2, DON'T run any queries
2246
-        //because level 2 indicates the database needs updating and
2247
-        //is probably out of sync with the code
2248
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2249
-            throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2250
-                "event_espresso")));
2251
-        }
2252
-        /** @type WPDB $wpdb */
2253
-        global $wpdb;
2254
-        if (! method_exists($wpdb, $wpdb_method)) {
2255
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2256
-                'event_espresso'), $wpdb_method));
2257
-        }
2258
-        if (WP_DEBUG) {
2259
-            $old_show_errors_value = $wpdb->show_errors;
2260
-            $wpdb->show_errors(false);
2261
-        }
2262
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2263
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2264
-        if (WP_DEBUG) {
2265
-            $wpdb->show_errors($old_show_errors_value);
2266
-            if (! empty($wpdb->last_error)) {
2267
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2268
-            } elseif ($result === false) {
2269
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2270
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2271
-            }
2272
-        } elseif ($result === false) {
2273
-            EE_Error::add_error(
2274
-                sprintf(
2275
-                    __('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2276
-                        'event_espresso'),
2277
-                    $wpdb_method,
2278
-                    var_export($arguments_to_provide, true),
2279
-                    $wpdb->last_error
2280
-                ),
2281
-                __FILE__,
2282
-                __FUNCTION__,
2283
-                __LINE__
2284
-            );
2285
-        }
2286
-        return $result;
2287
-    }
2288
-
2289
-
2290
-
2291
-    /**
2292
-     * Attempts to run the indicated WPDB method with the provided arguments,
2293
-     * and if there's an error tries to verify the DB is correct. Uses
2294
-     * the static property EEM_Base::$_db_verification_level to determine whether
2295
-     * we should try to fix the EE core db, the addons, or just give up
2296
-     *
2297
-     * @param string $wpdb_method
2298
-     * @param array  $arguments_to_provide
2299
-     * @return mixed
2300
-     */
2301
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2302
-    {
2303
-        /** @type WPDB $wpdb */
2304
-        global $wpdb;
2305
-        $wpdb->last_error = null;
2306
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2307
-        // was there an error running the query? but we don't care on new activations
2308
-        // (we're going to setup the DB anyway on new activations)
2309
-        if (($result === false || ! empty($wpdb->last_error))
2310
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2311
-        ) {
2312
-            switch (EEM_Base::$_db_verification_level) {
2313
-                case EEM_Base::db_verified_none :
2314
-                    // let's double-check core's DB
2315
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2316
-                    break;
2317
-                case EEM_Base::db_verified_core :
2318
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2319
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2320
-                    break;
2321
-                case EEM_Base::db_verified_addons :
2322
-                    // ummmm... you in trouble
2323
-                    return $result;
2324
-                    break;
2325
-            }
2326
-            if (! empty($error_message)) {
2327
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2328
-                trigger_error($error_message);
2329
-            }
2330
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
-        }
2332
-        return $result;
2333
-    }
2334
-
2335
-
2336
-
2337
-    /**
2338
-     * Verifies the EE core database is up-to-date and records that we've done it on
2339
-     * EEM_Base::$_db_verification_level
2340
-     *
2341
-     * @param string $wpdb_method
2342
-     * @param array  $arguments_to_provide
2343
-     * @return string
2344
-     */
2345
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2346
-    {
2347
-        /** @type WPDB $wpdb */
2348
-        global $wpdb;
2349
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2350
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2351
-        $error_message = sprintf(
2352
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2353
-                'event_espresso'),
2354
-            $wpdb->last_error,
2355
-            $wpdb_method,
2356
-            wp_json_encode($arguments_to_provide)
2357
-        );
2358
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2359
-        return $error_message;
2360
-    }
2361
-
2362
-
2363
-
2364
-    /**
2365
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2366
-     * EEM_Base::$_db_verification_level
2367
-     *
2368
-     * @param $wpdb_method
2369
-     * @param $arguments_to_provide
2370
-     * @return string
2371
-     */
2372
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2373
-    {
2374
-        /** @type WPDB $wpdb */
2375
-        global $wpdb;
2376
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2377
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2378
-        $error_message = sprintf(
2379
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2380
-                'event_espresso'),
2381
-            $wpdb->last_error,
2382
-            $wpdb_method,
2383
-            wp_json_encode($arguments_to_provide)
2384
-        );
2385
-        EE_System::instance()->initialize_addons();
2386
-        return $error_message;
2387
-    }
2388
-
2389
-
2390
-
2391
-    /**
2392
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2393
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2394
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2395
-     * ..."
2396
-     *
2397
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2398
-     * @return string
2399
-     */
2400
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2401
-    {
2402
-        return " FROM " . $model_query_info->get_full_join_sql() .
2403
-               $model_query_info->get_where_sql() .
2404
-               $model_query_info->get_group_by_sql() .
2405
-               $model_query_info->get_having_sql() .
2406
-               $model_query_info->get_order_by_sql() .
2407
-               $model_query_info->get_limit_sql();
2408
-    }
2409
-
2410
-
2411
-
2412
-    /**
2413
-     * Set to easily debug the next X queries ran from this model.
2414
-     *
2415
-     * @param int $count
2416
-     */
2417
-    public function show_next_x_db_queries($count = 1)
2418
-    {
2419
-        $this->_show_next_x_db_queries = $count;
2420
-    }
2421
-
2422
-
2423
-
2424
-    /**
2425
-     * @param $sql_query
2426
-     */
2427
-    public function show_db_query_if_previously_requested($sql_query)
2428
-    {
2429
-        if ($this->_show_next_x_db_queries > 0) {
2430
-            echo $sql_query;
2431
-            $this->_show_next_x_db_queries--;
2432
-        }
2433
-    }
2434
-
2435
-
2436
-
2437
-    /**
2438
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2439
-     * There are the 3 cases:
2440
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2441
-     * $otherModelObject has no ID, it is first saved.
2442
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2443
-     * has no ID, it is first saved.
2444
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2445
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2446
-     * join table
2447
-     *
2448
-     * @param        EE_Base_Class                     /int $thisModelObject
2449
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2450
-     * @param string $relationName                     , key in EEM_Base::_relations
2451
-     *                                                 an attendee to a group, you also want to specify which role they
2452
-     *                                                 will have in that group. So you would use this parameter to
2453
-     *                                                 specify array('role-column-name'=>'role-id')
2454
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2455
-     *                                                 to for relation to methods that allow you to further specify
2456
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2457
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2458
-     *                                                 because these will be inserted in any new rows created as well.
2459
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2460
-     * @throws EE_Error
2461
-     */
2462
-    public function add_relationship_to(
2463
-        $id_or_obj,
2464
-        $other_model_id_or_obj,
2465
-        $relationName,
2466
-        $extra_join_model_fields_n_values = array()
2467
-    ) {
2468
-        $relation_obj = $this->related_settings_for($relationName);
2469
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2470
-    }
2471
-
2472
-
2473
-
2474
-    /**
2475
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2476
-     * There are the 3 cases:
2477
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2478
-     * error
2479
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2480
-     * an error
2481
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2482
-     *
2483
-     * @param        EE_Base_Class /int $id_or_obj
2484
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2485
-     * @param string $relationName key in EEM_Base::_relations
2486
-     * @return boolean of success
2487
-     * @throws EE_Error
2488
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2489
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2490
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2491
-     *                             because these will be inserted in any new rows created as well.
2492
-     */
2493
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2494
-    {
2495
-        $relation_obj = $this->related_settings_for($relationName);
2496
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2497
-    }
2498
-
2499
-
2500
-
2501
-    /**
2502
-     * @param mixed           $id_or_obj
2503
-     * @param string          $relationName
2504
-     * @param array           $where_query_params
2505
-     * @param EE_Base_Class[] objects to which relations were removed
2506
-     * @return \EE_Base_Class[]
2507
-     * @throws EE_Error
2508
-     */
2509
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2510
-    {
2511
-        $relation_obj = $this->related_settings_for($relationName);
2512
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2513
-    }
2514
-
2515
-
2516
-
2517
-    /**
2518
-     * Gets all the related items of the specified $model_name, using $query_params.
2519
-     * Note: by default, we remove the "default query params"
2520
-     * because we want to get even deleted items etc.
2521
-     *
2522
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2523
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2524
-     * @param array  $query_params like EEM_Base::get_all
2525
-     * @return EE_Base_Class[]
2526
-     * @throws EE_Error
2527
-     */
2528
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2529
-    {
2530
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2531
-        $relation_settings = $this->related_settings_for($model_name);
2532
-        return $relation_settings->get_all_related($model_obj, $query_params);
2533
-    }
2534
-
2535
-
2536
-
2537
-    /**
2538
-     * Deletes all the model objects across the relation indicated by $model_name
2539
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2540
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2541
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2542
-     *
2543
-     * @param EE_Base_Class|int|string $id_or_obj
2544
-     * @param string                   $model_name
2545
-     * @param array                    $query_params
2546
-     * @return int how many deleted
2547
-     * @throws EE_Error
2548
-     */
2549
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2550
-    {
2551
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2552
-        $relation_settings = $this->related_settings_for($model_name);
2553
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2554
-    }
2555
-
2556
-
2557
-
2558
-    /**
2559
-     * Hard deletes all the model objects across the relation indicated by $model_name
2560
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2561
-     * the model objects can't be hard deleted because of blocking related model objects,
2562
-     * just does a soft-delete on them instead.
2563
-     *
2564
-     * @param EE_Base_Class|int|string $id_or_obj
2565
-     * @param string                   $model_name
2566
-     * @param array                    $query_params
2567
-     * @return int how many deleted
2568
-     * @throws EE_Error
2569
-     */
2570
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2571
-    {
2572
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2573
-        $relation_settings = $this->related_settings_for($model_name);
2574
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2575
-    }
2576
-
2577
-
2578
-
2579
-    /**
2580
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2581
-     * unless otherwise specified in the $query_params
2582
-     *
2583
-     * @param        int             /EE_Base_Class $id_or_obj
2584
-     * @param string $model_name     like 'Event', or 'Registration'
2585
-     * @param array  $query_params   like EEM_Base::get_all's
2586
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2587
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2588
-     *                               that by the setting $distinct to TRUE;
2589
-     * @return int
2590
-     * @throws EE_Error
2591
-     */
2592
-    public function count_related(
2593
-        $id_or_obj,
2594
-        $model_name,
2595
-        $query_params = array(),
2596
-        $field_to_count = null,
2597
-        $distinct = false
2598
-    ) {
2599
-        $related_model = $this->get_related_model_obj($model_name);
2600
-        //we're just going to use the query params on the related model's normal get_all query,
2601
-        //except add a condition to say to match the current mod
2602
-        if (! isset($query_params['default_where_conditions'])) {
2603
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2604
-        }
2605
-        $this_model_name = $this->get_this_model_name();
2606
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2607
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2608
-        return $related_model->count($query_params, $field_to_count, $distinct);
2609
-    }
2610
-
2611
-
2612
-
2613
-    /**
2614
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2615
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2616
-     *
2617
-     * @param        int           /EE_Base_Class $id_or_obj
2618
-     * @param string $model_name   like 'Event', or 'Registration'
2619
-     * @param array  $query_params like EEM_Base::get_all's
2620
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2621
-     * @return float
2622
-     * @throws EE_Error
2623
-     */
2624
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2625
-    {
2626
-        $related_model = $this->get_related_model_obj($model_name);
2627
-        if (! is_array($query_params)) {
2628
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2629
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2630
-                    gettype($query_params)), '4.6.0');
2631
-            $query_params = array();
2632
-        }
2633
-        //we're just going to use the query params on the related model's normal get_all query,
2634
-        //except add a condition to say to match the current mod
2635
-        if (! isset($query_params['default_where_conditions'])) {
2636
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2637
-        }
2638
-        $this_model_name = $this->get_this_model_name();
2639
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2640
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2641
-        return $related_model->sum($query_params, $field_to_sum);
2642
-    }
2643
-
2644
-
2645
-
2646
-    /**
2647
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2648
-     * $modelObject
2649
-     *
2650
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2651
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2652
-     * @param array               $query_params     like EEM_Base::get_all's
2653
-     * @return EE_Base_Class
2654
-     * @throws EE_Error
2655
-     */
2656
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2657
-    {
2658
-        $query_params['limit'] = 1;
2659
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2660
-        if ($results) {
2661
-            return array_shift($results);
2662
-        } else {
2663
-            return null;
2664
-        }
2665
-    }
2666
-
2667
-
2668
-
2669
-    /**
2670
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2671
-     *
2672
-     * @return string
2673
-     */
2674
-    public function get_this_model_name()
2675
-    {
2676
-        return str_replace("EEM_", "", get_class($this));
2677
-    }
2678
-
2679
-
2680
-
2681
-    /**
2682
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2683
-     *
2684
-     * @return EE_Any_Foreign_Model_Name_Field
2685
-     * @throws EE_Error
2686
-     */
2687
-    public function get_field_containing_related_model_name()
2688
-    {
2689
-        foreach ($this->field_settings(true) as $field) {
2690
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2691
-                $field_with_model_name = $field;
2692
-            }
2693
-        }
2694
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2695
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2696
-                $this->get_this_model_name()));
2697
-        }
2698
-        return $field_with_model_name;
2699
-    }
2700
-
2701
-
2702
-
2703
-    /**
2704
-     * Inserts a new entry into the database, for each table.
2705
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2706
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2707
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2708
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2709
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2710
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2711
-     *
2712
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2713
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2714
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2715
-     *                              of EEM_Base)
2716
-     * @return int new primary key on main table that got inserted
2717
-     * @throws EE_Error
2718
-     */
2719
-    public function insert($field_n_values)
2720
-    {
2721
-        /**
2722
-         * Filters the fields and their values before inserting an item using the models
2723
-         *
2724
-         * @param array    $fields_n_values keys are the fields and values are their new values
2725
-         * @param EEM_Base $model           the model used
2726
-         */
2727
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2728
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2729
-            $main_table = $this->_get_main_table();
2730
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2731
-            if ($new_id !== false) {
2732
-                foreach ($this->_get_other_tables() as $other_table) {
2733
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2734
-                }
2735
-            }
2736
-            /**
2737
-             * Done just after attempting to insert a new model object
2738
-             *
2739
-             * @param EEM_Base   $model           used
2740
-             * @param array      $fields_n_values fields and their values
2741
-             * @param int|string the              ID of the newly-inserted model object
2742
-             */
2743
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2744
-            return $new_id;
2745
-        } else {
2746
-            return false;
2747
-        }
2748
-    }
2749
-
2750
-
2751
-
2752
-    /**
2753
-     * Checks that the result would satisfy the unique indexes on this model
2754
-     *
2755
-     * @param array  $field_n_values
2756
-     * @param string $action
2757
-     * @return boolean
2758
-     * @throws EE_Error
2759
-     */
2760
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2761
-    {
2762
-        foreach ($this->unique_indexes() as $index_name => $index) {
2763
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2764
-            if ($this->exists(array($uniqueness_where_params))) {
2765
-                EE_Error::add_error(
2766
-                    sprintf(
2767
-                        __(
2768
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2769
-                            "event_espresso"
2770
-                        ),
2771
-                        $action,
2772
-                        $this->_get_class_name(),
2773
-                        $index_name,
2774
-                        implode(",", $index->field_names()),
2775
-                        http_build_query($uniqueness_where_params)
2776
-                    ),
2777
-                    __FILE__,
2778
-                    __FUNCTION__,
2779
-                    __LINE__
2780
-                );
2781
-                return false;
2782
-            }
2783
-        }
2784
-        return true;
2785
-    }
2786
-
2787
-
2788
-
2789
-    /**
2790
-     * Checks the database for an item that conflicts (ie, if this item were
2791
-     * saved to the DB would break some uniqueness requirement, like a primary key
2792
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2793
-     * can be either an EE_Base_Class or an array of fields n values
2794
-     *
2795
-     * @param EE_Base_Class|array $obj_or_fields_array
2796
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2797
-     *                                                 when looking for conflicts
2798
-     *                                                 (ie, if false, we ignore the model object's primary key
2799
-     *                                                 when finding "conflicts". If true, it's also considered).
2800
-     *                                                 Only works for INT primary key,
2801
-     *                                                 STRING primary keys cannot be ignored
2802
-     * @throws EE_Error
2803
-     * @return EE_Base_Class|array
2804
-     */
2805
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2806
-    {
2807
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2808
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2809
-        } elseif (is_array($obj_or_fields_array)) {
2810
-            $fields_n_values = $obj_or_fields_array;
2811
-        } else {
2812
-            throw new EE_Error(
2813
-                sprintf(
2814
-                    __(
2815
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2816
-                        "event_espresso"
2817
-                    ),
2818
-                    get_class($this),
2819
-                    $obj_or_fields_array
2820
-                )
2821
-            );
2822
-        }
2823
-        $query_params = array();
2824
-        if ($this->has_primary_key_field()
2825
-            && ($include_primary_key
2826
-                || $this->get_primary_key_field()
2827
-                   instanceof
2828
-                   EE_Primary_Key_String_Field)
2829
-            && isset($fields_n_values[$this->primary_key_name()])
2830
-        ) {
2831
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2832
-        }
2833
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2834
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2835
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2836
-        }
2837
-        //if there is nothing to base this search on, then we shouldn't find anything
2838
-        if (empty($query_params)) {
2839
-            return array();
2840
-        } else {
2841
-            return $this->get_one($query_params);
2842
-        }
2843
-    }
2844
-
2845
-
2846
-
2847
-    /**
2848
-     * Like count, but is optimized and returns a boolean instead of an int
2849
-     *
2850
-     * @param array $query_params
2851
-     * @return boolean
2852
-     * @throws EE_Error
2853
-     */
2854
-    public function exists($query_params)
2855
-    {
2856
-        $query_params['limit'] = 1;
2857
-        return $this->count($query_params) > 0;
2858
-    }
2859
-
2860
-
2861
-
2862
-    /**
2863
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2864
-     *
2865
-     * @param int|string $id
2866
-     * @return boolean
2867
-     * @throws EE_Error
2868
-     */
2869
-    public function exists_by_ID($id)
2870
-    {
2871
-        return $this->exists(
2872
-            array(
2873
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2874
-                array(
2875
-                    $this->primary_key_name() => $id,
2876
-                ),
2877
-            )
2878
-        );
2879
-    }
2880
-
2881
-
2882
-
2883
-    /**
2884
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2885
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2886
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2887
-     * on the main table)
2888
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2889
-     * cases where we want to call it directly rather than via insert().
2890
-     *
2891
-     * @access   protected
2892
-     * @param EE_Table_Base $table
2893
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2894
-     *                                       float
2895
-     * @param int           $new_id          for now we assume only int keys
2896
-     * @throws EE_Error
2897
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2898
-     * @return int ID of new row inserted, or FALSE on failure
2899
-     */
2900
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2901
-    {
2902
-        global $wpdb;
2903
-        $insertion_col_n_values = array();
2904
-        $format_for_insertion = array();
2905
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2906
-        foreach ($fields_on_table as $field_name => $field_obj) {
2907
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2908
-            if ($field_obj->is_auto_increment()) {
2909
-                continue;
2910
-            }
2911
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2912
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2913
-            if ($prepared_value !== null) {
2914
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2915
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2916
-            }
2917
-        }
2918
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2919
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2920
-            //so add the fk to the main table as a column
2921
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2922
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2923
-        }
2924
-        //insert the new entry
2925
-        $result = $this->_do_wpdb_query('insert',
2926
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2927
-        if ($result === false) {
2928
-            return false;
2929
-        }
2930
-        //ok, now what do we return for the ID of the newly-inserted thing?
2931
-        if ($this->has_primary_key_field()) {
2932
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2933
-                return $wpdb->insert_id;
2934
-            } else {
2935
-                //it's not an auto-increment primary key, so
2936
-                //it must have been supplied
2937
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2938
-            }
2939
-        } else {
2940
-            //we can't return a  primary key because there is none. instead return
2941
-            //a unique string indicating this model
2942
-            return $this->get_index_primary_key_string($fields_n_values);
2943
-        }
2944
-    }
2945
-
2946
-
2947
-
2948
-    /**
2949
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2950
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2951
-     * and there is no default, we pass it along. WPDB will take care of it)
2952
-     *
2953
-     * @param EE_Model_Field_Base $field_obj
2954
-     * @param array               $fields_n_values
2955
-     * @return mixed string|int|float depending on what the table column will be expecting
2956
-     * @throws EE_Error
2957
-     */
2958
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2959
-    {
2960
-        //if this field doesn't allow nullable, don't allow it
2961
-        if (
2962
-            ! $field_obj->is_nullable()
2963
-            && (
2964
-                ! isset($fields_n_values[$field_obj->get_name()])
2965
-                || $fields_n_values[$field_obj->get_name()] === null
2966
-            )
2967
-        ) {
2968
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2969
-        }
2970
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2971
-            ? $fields_n_values[$field_obj->get_name()]
2972
-            : null;
2973
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2974
-    }
2975
-
2976
-
2977
-
2978
-    /**
2979
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2980
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2981
-     * the field's prepare_for_set() method.
2982
-     *
2983
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2984
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2985
-     *                                   top of file)
2986
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2987
-     *                                   $value is a custom selection
2988
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2989
-     */
2990
-    private function _prepare_value_for_use_in_db($value, $field)
2991
-    {
2992
-        if ($field && $field instanceof EE_Model_Field_Base) {
2993
-            switch ($this->_values_already_prepared_by_model_object) {
2994
-                /** @noinspection PhpMissingBreakStatementInspection */
2995
-                case self::not_prepared_by_model_object:
2996
-                    $value = $field->prepare_for_set($value);
2997
-                //purposefully left out "return"
2998
-                case self::prepared_by_model_object:
2999
-                    $value = $field->prepare_for_use_in_db($value);
3000
-                case self::prepared_for_use_in_db:
3001
-                    //leave the value alone
3002
-            }
3003
-            return $value;
3004
-        } else {
3005
-            return $value;
3006
-        }
3007
-    }
3008
-
3009
-
3010
-
3011
-    /**
3012
-     * Returns the main table on this model
3013
-     *
3014
-     * @return EE_Primary_Table
3015
-     * @throws EE_Error
3016
-     */
3017
-    protected function _get_main_table()
3018
-    {
3019
-        foreach ($this->_tables as $table) {
3020
-            if ($table instanceof EE_Primary_Table) {
3021
-                return $table;
3022
-            }
3023
-        }
3024
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3025
-            'event_espresso'), get_class($this)));
3026
-    }
3027
-
3028
-
3029
-
3030
-    /**
3031
-     * table
3032
-     * returns EE_Primary_Table table name
3033
-     *
3034
-     * @return string
3035
-     * @throws EE_Error
3036
-     */
3037
-    public function table()
3038
-    {
3039
-        return $this->_get_main_table()->get_table_name();
3040
-    }
3041
-
3042
-
3043
-
3044
-    /**
3045
-     * table
3046
-     * returns first EE_Secondary_Table table name
3047
-     *
3048
-     * @return string
3049
-     */
3050
-    public function second_table()
3051
-    {
3052
-        // grab second table from tables array
3053
-        $second_table = end($this->_tables);
3054
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3055
-    }
3056
-
3057
-
3058
-
3059
-    /**
3060
-     * get_table_obj_by_alias
3061
-     * returns table name given it's alias
3062
-     *
3063
-     * @param string $table_alias
3064
-     * @return EE_Primary_Table | EE_Secondary_Table
3065
-     */
3066
-    public function get_table_obj_by_alias($table_alias = '')
3067
-    {
3068
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3069
-    }
3070
-
3071
-
3072
-
3073
-    /**
3074
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3075
-     *
3076
-     * @return EE_Secondary_Table[]
3077
-     */
3078
-    protected function _get_other_tables()
3079
-    {
3080
-        $other_tables = array();
3081
-        foreach ($this->_tables as $table_alias => $table) {
3082
-            if ($table instanceof EE_Secondary_Table) {
3083
-                $other_tables[$table_alias] = $table;
3084
-            }
3085
-        }
3086
-        return $other_tables;
3087
-    }
3088
-
3089
-
3090
-
3091
-    /**
3092
-     * Finds all the fields that correspond to the given table
3093
-     *
3094
-     * @param string $table_alias , array key in EEM_Base::_tables
3095
-     * @return EE_Model_Field_Base[]
3096
-     */
3097
-    public function _get_fields_for_table($table_alias)
3098
-    {
3099
-        return $this->_fields[$table_alias];
3100
-    }
3101
-
3102
-
3103
-
3104
-    /**
3105
-     * Recurses through all the where parameters, and finds all the related models we'll need
3106
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3107
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3108
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3109
-     * related Registration, Transaction, and Payment models.
3110
-     *
3111
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3112
-     * @return EE_Model_Query_Info_Carrier
3113
-     * @throws EE_Error
3114
-     */
3115
-    public function _extract_related_models_from_query($query_params)
3116
-    {
3117
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3118
-        if (array_key_exists(0, $query_params)) {
3119
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3120
-        }
3121
-        if (array_key_exists('group_by', $query_params)) {
3122
-            if (is_array($query_params['group_by'])) {
3123
-                $this->_extract_related_models_from_sub_params_array_values(
3124
-                    $query_params['group_by'],
3125
-                    $query_info_carrier,
3126
-                    'group_by'
3127
-                );
3128
-            } elseif (! empty ($query_params['group_by'])) {
3129
-                $this->_extract_related_model_info_from_query_param(
3130
-                    $query_params['group_by'],
3131
-                    $query_info_carrier,
3132
-                    'group_by'
3133
-                );
3134
-            }
3135
-        }
3136
-        if (array_key_exists('having', $query_params)) {
3137
-            $this->_extract_related_models_from_sub_params_array_keys(
3138
-                $query_params[0],
3139
-                $query_info_carrier,
3140
-                'having'
3141
-            );
3142
-        }
3143
-        if (array_key_exists('order_by', $query_params)) {
3144
-            if (is_array($query_params['order_by'])) {
3145
-                $this->_extract_related_models_from_sub_params_array_keys(
3146
-                    $query_params['order_by'],
3147
-                    $query_info_carrier,
3148
-                    'order_by'
3149
-                );
3150
-            } elseif (! empty($query_params['order_by'])) {
3151
-                $this->_extract_related_model_info_from_query_param(
3152
-                    $query_params['order_by'],
3153
-                    $query_info_carrier,
3154
-                    'order_by'
3155
-                );
3156
-            }
3157
-        }
3158
-        if (array_key_exists('force_join', $query_params)) {
3159
-            $this->_extract_related_models_from_sub_params_array_values(
3160
-                $query_params['force_join'],
3161
-                $query_info_carrier,
3162
-                'force_join'
3163
-            );
3164
-        }
3165
-        return $query_info_carrier;
3166
-    }
3167
-
3168
-
3169
-
3170
-    /**
3171
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3172
-     *
3173
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3174
-     *                                                      $query_params['having']
3175
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3176
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3177
-     * @throws EE_Error
3178
-     * @return \EE_Model_Query_Info_Carrier
3179
-     */
3180
-    private function _extract_related_models_from_sub_params_array_keys(
3181
-        $sub_query_params,
3182
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3183
-        $query_param_type
3184
-    ) {
3185
-        if (! empty($sub_query_params)) {
3186
-            $sub_query_params = (array)$sub_query_params;
3187
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3188
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3189
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3190
-                    $query_param_type);
3191
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3192
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3193
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3194
-                //of array('Registration.TXN_ID'=>23)
3195
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3196
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3197
-                    if (! is_array($possibly_array_of_params)) {
3198
-                        throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3199
-                            "event_espresso"),
3200
-                            $param, $possibly_array_of_params));
3201
-                    } else {
3202
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3203
-                            $model_query_info_carrier, $query_param_type);
3204
-                    }
3205
-                } elseif ($query_param_type === 0 //ie WHERE
3206
-                          && is_array($possibly_array_of_params)
3207
-                          && isset($possibly_array_of_params[2])
3208
-                          && $possibly_array_of_params[2] == true
3209
-                ) {
3210
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3211
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3212
-                    //from which we should extract query parameters!
3213
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3214
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3215
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3216
-                    }
3217
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3218
-                        $model_query_info_carrier, $query_param_type);
3219
-                }
3220
-            }
3221
-        }
3222
-        return $model_query_info_carrier;
3223
-    }
3224
-
3225
-
3226
-
3227
-    /**
3228
-     * For extracting related models from forced_joins, where the array values contain the info about what
3229
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3230
-     *
3231
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3232
-     *                                                      $query_params['having']
3233
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3234
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3235
-     * @throws EE_Error
3236
-     * @return \EE_Model_Query_Info_Carrier
3237
-     */
3238
-    private function _extract_related_models_from_sub_params_array_values(
3239
-        $sub_query_params,
3240
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3241
-        $query_param_type
3242
-    ) {
3243
-        if (! empty($sub_query_params)) {
3244
-            if (! is_array($sub_query_params)) {
3245
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3246
-                    $sub_query_params));
3247
-            }
3248
-            foreach ($sub_query_params as $param) {
3249
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3250
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3251
-                    $query_param_type);
3252
-            }
3253
-        }
3254
-        return $model_query_info_carrier;
3255
-    }
3256
-
3257
-
3258
-
3259
-    /**
3260
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3261
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3262
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3263
-     * but use them in a different order. Eg, we need to know what models we are querying
3264
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3265
-     * other models before we can finalize the where clause SQL.
3266
-     *
3267
-     * @param array $query_params
3268
-     * @throws EE_Error
3269
-     * @return EE_Model_Query_Info_Carrier
3270
-     */
3271
-    public function _create_model_query_info_carrier($query_params)
3272
-    {
3273
-        if (! is_array($query_params)) {
3274
-            EE_Error::doing_it_wrong(
3275
-                'EEM_Base::_create_model_query_info_carrier',
3276
-                sprintf(
3277
-                    __(
3278
-                        '$query_params should be an array, you passed a variable of type %s',
3279
-                        'event_espresso'
3280
-                    ),
3281
-                    gettype($query_params)
3282
-                ),
3283
-                '4.6.0'
3284
-            );
3285
-            $query_params = array();
3286
-        }
3287
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3288
-        //first check if we should alter the query to account for caps or not
3289
-        //because the caps might require us to do extra joins
3290
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3291
-            $query_params[0] = $where_query_params = array_replace_recursive(
3292
-                $where_query_params,
3293
-                $this->caps_where_conditions(
3294
-                    $query_params['caps']
3295
-                )
3296
-            );
3297
-        }
3298
-        $query_object = $this->_extract_related_models_from_query($query_params);
3299
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3300
-        foreach ($where_query_params as $key => $value) {
3301
-            if (is_int($key)) {
3302
-                throw new EE_Error(
3303
-                    sprintf(
3304
-                        __(
3305
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3306
-                            "event_espresso"
3307
-                        ),
3308
-                        $key,
3309
-                        var_export($value, true),
3310
-                        var_export($query_params, true),
3311
-                        get_class($this)
3312
-                    )
3313
-                );
3314
-            }
3315
-        }
3316
-        if (
3317
-            array_key_exists('default_where_conditions', $query_params)
3318
-            && ! empty($query_params['default_where_conditions'])
3319
-        ) {
3320
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3321
-        } else {
3322
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3323
-        }
3324
-        $where_query_params = array_merge(
3325
-            $this->_get_default_where_conditions_for_models_in_query(
3326
-                $query_object,
3327
-                $use_default_where_conditions,
3328
-                $where_query_params
3329
-            ),
3330
-            $where_query_params
3331
-        );
3332
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3333
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3334
-        // So we need to setup a subquery and use that for the main join.
3335
-        // Note for now this only works on the primary table for the model.
3336
-        // So for instance, you could set the limit array like this:
3337
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3338
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3339
-            $query_object->set_main_model_join_sql(
3340
-                $this->_construct_limit_join_select(
3341
-                    $query_params['on_join_limit'][0],
3342
-                    $query_params['on_join_limit'][1]
3343
-                )
3344
-            );
3345
-        }
3346
-        //set limit
3347
-        if (array_key_exists('limit', $query_params)) {
3348
-            if (is_array($query_params['limit'])) {
3349
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3350
-                    $e = sprintf(
3351
-                        __(
3352
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3353
-                            "event_espresso"
3354
-                        ),
3355
-                        http_build_query($query_params['limit'])
3356
-                    );
3357
-                    throw new EE_Error($e . "|" . $e);
3358
-                }
3359
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3360
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3361
-            } elseif (! empty ($query_params['limit'])) {
3362
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3363
-            }
3364
-        }
3365
-        //set order by
3366
-        if (array_key_exists('order_by', $query_params)) {
3367
-            if (is_array($query_params['order_by'])) {
3368
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3369
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3370
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3371
-                if (array_key_exists('order', $query_params)) {
3372
-                    throw new EE_Error(
3373
-                        sprintf(
3374
-                            __(
3375
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3376
-                                "event_espresso"
3377
-                            ),
3378
-                            get_class($this),
3379
-                            implode(", ", array_keys($query_params['order_by'])),
3380
-                            implode(", ", $query_params['order_by']),
3381
-                            $query_params['order']
3382
-                        )
3383
-                    );
3384
-                }
3385
-                $this->_extract_related_models_from_sub_params_array_keys(
3386
-                    $query_params['order_by'],
3387
-                    $query_object,
3388
-                    'order_by'
3389
-                );
3390
-                //assume it's an array of fields to order by
3391
-                $order_array = array();
3392
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3393
-                    $order = $this->_extract_order($order);
3394
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3395
-                }
3396
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3397
-            } elseif (! empty ($query_params['order_by'])) {
3398
-                $this->_extract_related_model_info_from_query_param(
3399
-                    $query_params['order_by'],
3400
-                    $query_object,
3401
-                    'order',
3402
-                    $query_params['order_by']
3403
-                );
3404
-                $order = isset($query_params['order'])
3405
-                    ? $this->_extract_order($query_params['order'])
3406
-                    : 'DESC';
3407
-                $query_object->set_order_by_sql(
3408
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3409
-                );
3410
-            }
3411
-        }
3412
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3413
-        if (! array_key_exists('order_by', $query_params)
3414
-            && array_key_exists('order', $query_params)
3415
-            && ! empty($query_params['order'])
3416
-        ) {
3417
-            $pk_field = $this->get_primary_key_field();
3418
-            $order = $this->_extract_order($query_params['order']);
3419
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3420
-        }
3421
-        //set group by
3422
-        if (array_key_exists('group_by', $query_params)) {
3423
-            if (is_array($query_params['group_by'])) {
3424
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3425
-                $group_by_array = array();
3426
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3427
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3428
-                }
3429
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3430
-            } elseif (! empty ($query_params['group_by'])) {
3431
-                $query_object->set_group_by_sql(
3432
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3433
-                );
3434
-            }
3435
-        }
3436
-        //set having
3437
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3438
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3439
-        }
3440
-        //now, just verify they didn't pass anything wack
3441
-        foreach ($query_params as $query_key => $query_value) {
3442
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3443
-                throw new EE_Error(
3444
-                    sprintf(
3445
-                        __(
3446
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3447
-                            'event_espresso'
3448
-                        ),
3449
-                        $query_key,
3450
-                        get_class($this),
3451
-                        //						print_r( $this->_allowed_query_params, TRUE )
3452
-                        implode(',', $this->_allowed_query_params)
3453
-                    )
3454
-                );
3455
-            }
3456
-        }
3457
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3458
-        if (empty($main_model_join_sql)) {
3459
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3460
-        }
3461
-        return $query_object;
3462
-    }
3463
-
3464
-
3465
-
3466
-    /**
3467
-     * Gets the where conditions that should be imposed on the query based on the
3468
-     * context (eg reading frontend, backend, edit or delete).
3469
-     *
3470
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3471
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3472
-     * @throws EE_Error
3473
-     */
3474
-    public function caps_where_conditions($context = self::caps_read)
3475
-    {
3476
-        EEM_Base::verify_is_valid_cap_context($context);
3477
-        $cap_where_conditions = array();
3478
-        $cap_restrictions = $this->caps_missing($context);
3479
-        /**
3480
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3481
-         */
3482
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3483
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3484
-                $restriction_if_no_cap->get_default_where_conditions());
3485
-        }
3486
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3487
-            $cap_restrictions);
3488
-    }
3489
-
3490
-
3491
-
3492
-    /**
3493
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3494
-     * otherwise throws an exception
3495
-     *
3496
-     * @param string $should_be_order_string
3497
-     * @return string either ASC, asc, DESC or desc
3498
-     * @throws EE_Error
3499
-     */
3500
-    private function _extract_order($should_be_order_string)
3501
-    {
3502
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3503
-            return $should_be_order_string;
3504
-        } else {
3505
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3506
-                "event_espresso"), get_class($this), $should_be_order_string));
3507
-        }
3508
-    }
3509
-
3510
-
3511
-
3512
-    /**
3513
-     * Looks at all the models which are included in this query, and asks each
3514
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3515
-     * so they can be merged
3516
-     *
3517
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3518
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3519
-     *                                                                  'none' means NO default where conditions will
3520
-     *                                                                  be used AT ALL during this query.
3521
-     *                                                                  'other_models_only' means default where
3522
-     *                                                                  conditions from other models will be used, but
3523
-     *                                                                  not for this primary model. 'all', the default,
3524
-     *                                                                  means default where conditions will apply as
3525
-     *                                                                  normal
3526
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3527
-     * @throws EE_Error
3528
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3529
-     */
3530
-    private function _get_default_where_conditions_for_models_in_query(
3531
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3532
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3533
-        $where_query_params = array()
3534
-    ) {
3535
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3536
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3537
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3538
-                "event_espresso"), $use_default_where_conditions,
3539
-                implode(", ", $allowed_used_default_where_conditions_values)));
3540
-        }
3541
-        $universal_query_params = array();
3542
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3543
-            $universal_query_params = $this->_get_default_where_conditions();
3544
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3545
-            $universal_query_params = $this->_get_minimum_where_conditions();
3546
-        }
3547
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3548
-            $related_model = $this->get_related_model_obj($model_name);
3549
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3550
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3551
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3552
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3553
-            } else {
3554
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3555
-                continue;
3556
-            }
3557
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3558
-                $related_model_universal_where_params,
3559
-                $where_query_params,
3560
-                $related_model,
3561
-                $model_relation_path
3562
-            );
3563
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3564
-                $universal_query_params,
3565
-                $overrides
3566
-            );
3567
-        }
3568
-        return $universal_query_params;
3569
-    }
3570
-
3571
-
3572
-
3573
-    /**
3574
-     * Determines whether or not we should use default where conditions for the model in question
3575
-     * (this model, or other related models).
3576
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3577
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3578
-     * We should use default where conditions on related models when they requested to use default where conditions
3579
-     * on all models, or specifically just on other related models
3580
-     * @param      $default_where_conditions_value
3581
-     * @param bool $for_this_model false means this is for OTHER related models
3582
-     * @return bool
3583
-     */
3584
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3585
-    {
3586
-        return (
3587
-                   $for_this_model
3588
-                   && in_array(
3589
-                       $default_where_conditions_value,
3590
-                       array(
3591
-                           EEM_Base::default_where_conditions_all,
3592
-                           EEM_Base::default_where_conditions_this_only,
3593
-                           EEM_Base::default_where_conditions_minimum_others,
3594
-                       ),
3595
-                       true
3596
-                   )
3597
-               )
3598
-               || (
3599
-                   ! $for_this_model
3600
-                   && in_array(
3601
-                       $default_where_conditions_value,
3602
-                       array(
3603
-                           EEM_Base::default_where_conditions_all,
3604
-                           EEM_Base::default_where_conditions_others_only,
3605
-                       ),
3606
-                       true
3607
-                   )
3608
-               );
3609
-    }
3610
-
3611
-    /**
3612
-     * Determines whether or not we should use default minimum conditions for the model in question
3613
-     * (this model, or other related models).
3614
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3615
-     * where conditions.
3616
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3617
-     * on this model or others
3618
-     * @param      $default_where_conditions_value
3619
-     * @param bool $for_this_model false means this is for OTHER related models
3620
-     * @return bool
3621
-     */
3622
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3623
-    {
3624
-        return (
3625
-                   $for_this_model
3626
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3627
-               )
3628
-               || (
3629
-                   ! $for_this_model
3630
-                   && in_array(
3631
-                       $default_where_conditions_value,
3632
-                       array(
3633
-                           EEM_Base::default_where_conditions_minimum_others,
3634
-                           EEM_Base::default_where_conditions_minimum_all,
3635
-                       ),
3636
-                       true
3637
-                   )
3638
-               );
3639
-    }
3640
-
3641
-
3642
-    /**
3643
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3644
-     * then we also add a special where condition which allows for that model's primary key
3645
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3646
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3647
-     *
3648
-     * @param array    $default_where_conditions
3649
-     * @param array    $provided_where_conditions
3650
-     * @param EEM_Base $model
3651
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3652
-     * @return array like EEM_Base::get_all's $query_params[0]
3653
-     * @throws EE_Error
3654
-     */
3655
-    private function _override_defaults_or_make_null_friendly(
3656
-        $default_where_conditions,
3657
-        $provided_where_conditions,
3658
-        $model,
3659
-        $model_relation_path
3660
-    ) {
3661
-        $null_friendly_where_conditions = array();
3662
-        $none_overridden = true;
3663
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3664
-        foreach ($default_where_conditions as $key => $val) {
3665
-            if (isset($provided_where_conditions[$key])) {
3666
-                $none_overridden = false;
3667
-            } else {
3668
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3669
-            }
3670
-        }
3671
-        if ($none_overridden && $default_where_conditions) {
3672
-            if ($model->has_primary_key_field()) {
3673
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3674
-                                                                                . "."
3675
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3676
-            }/*else{
2161
+	/**
2162
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2163
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2164
+	 * column
2165
+	 *
2166
+	 * @param array  $query_params   like EEM_Base::get_all's
2167
+	 * @param string $field_to_count field on model to count by (not column name)
2168
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2169
+	 *                               that by the setting $distinct to TRUE;
2170
+	 * @return int
2171
+	 * @throws EE_Error
2172
+	 */
2173
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2174
+	{
2175
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2176
+		if ($field_to_count) {
2177
+			$field_obj = $this->field_settings_for($field_to_count);
2178
+			$column_to_count = $field_obj->get_qualified_column();
2179
+		} elseif ($this->has_primary_key_field()) {
2180
+			$pk_field_obj = $this->get_primary_key_field();
2181
+			$column_to_count = $pk_field_obj->get_qualified_column();
2182
+		} else {
2183
+			//there's no primary key
2184
+			//if we're counting distinct items, and there's no primary key,
2185
+			//we need to list out the columns for distinction;
2186
+			//otherwise we can just use star
2187
+			if ($distinct) {
2188
+				$columns_to_use = array();
2189
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2190
+					$columns_to_use[] = $field_obj->get_qualified_column();
2191
+				}
2192
+				$column_to_count = implode(',', $columns_to_use);
2193
+			} else {
2194
+				$column_to_count = '*';
2195
+			}
2196
+		}
2197
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2198
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2199
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2200
+	}
2201
+
2202
+
2203
+
2204
+	/**
2205
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2206
+	 *
2207
+	 * @param array  $query_params like EEM_Base::get_all
2208
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2209
+	 * @return float
2210
+	 * @throws EE_Error
2211
+	 */
2212
+	public function sum($query_params, $field_to_sum = null)
2213
+	{
2214
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2215
+		if ($field_to_sum) {
2216
+			$field_obj = $this->field_settings_for($field_to_sum);
2217
+		} else {
2218
+			$field_obj = $this->get_primary_key_field();
2219
+		}
2220
+		$column_to_count = $field_obj->get_qualified_column();
2221
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2222
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2223
+		$data_type = $field_obj->get_wpdb_data_type();
2224
+		if ($data_type === '%d' || $data_type === '%s') {
2225
+			return (float)$return_value;
2226
+		} else {//must be %f
2227
+			return (float)$return_value;
2228
+		}
2229
+	}
2230
+
2231
+
2232
+
2233
+	/**
2234
+	 * Just calls the specified method on $wpdb with the given arguments
2235
+	 * Consolidates a little extra error handling code
2236
+	 *
2237
+	 * @param string $wpdb_method
2238
+	 * @param array  $arguments_to_provide
2239
+	 * @throws EE_Error
2240
+	 * @global wpdb  $wpdb
2241
+	 * @return mixed
2242
+	 */
2243
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2244
+	{
2245
+		//if we're in maintenance mode level 2, DON'T run any queries
2246
+		//because level 2 indicates the database needs updating and
2247
+		//is probably out of sync with the code
2248
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2249
+			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2250
+				"event_espresso")));
2251
+		}
2252
+		/** @type WPDB $wpdb */
2253
+		global $wpdb;
2254
+		if (! method_exists($wpdb, $wpdb_method)) {
2255
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2256
+				'event_espresso'), $wpdb_method));
2257
+		}
2258
+		if (WP_DEBUG) {
2259
+			$old_show_errors_value = $wpdb->show_errors;
2260
+			$wpdb->show_errors(false);
2261
+		}
2262
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2263
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2264
+		if (WP_DEBUG) {
2265
+			$wpdb->show_errors($old_show_errors_value);
2266
+			if (! empty($wpdb->last_error)) {
2267
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2268
+			} elseif ($result === false) {
2269
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2270
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2271
+			}
2272
+		} elseif ($result === false) {
2273
+			EE_Error::add_error(
2274
+				sprintf(
2275
+					__('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2276
+						'event_espresso'),
2277
+					$wpdb_method,
2278
+					var_export($arguments_to_provide, true),
2279
+					$wpdb->last_error
2280
+				),
2281
+				__FILE__,
2282
+				__FUNCTION__,
2283
+				__LINE__
2284
+			);
2285
+		}
2286
+		return $result;
2287
+	}
2288
+
2289
+
2290
+
2291
+	/**
2292
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2293
+	 * and if there's an error tries to verify the DB is correct. Uses
2294
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2295
+	 * we should try to fix the EE core db, the addons, or just give up
2296
+	 *
2297
+	 * @param string $wpdb_method
2298
+	 * @param array  $arguments_to_provide
2299
+	 * @return mixed
2300
+	 */
2301
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2302
+	{
2303
+		/** @type WPDB $wpdb */
2304
+		global $wpdb;
2305
+		$wpdb->last_error = null;
2306
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2307
+		// was there an error running the query? but we don't care on new activations
2308
+		// (we're going to setup the DB anyway on new activations)
2309
+		if (($result === false || ! empty($wpdb->last_error))
2310
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2311
+		) {
2312
+			switch (EEM_Base::$_db_verification_level) {
2313
+				case EEM_Base::db_verified_none :
2314
+					// let's double-check core's DB
2315
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2316
+					break;
2317
+				case EEM_Base::db_verified_core :
2318
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2319
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2320
+					break;
2321
+				case EEM_Base::db_verified_addons :
2322
+					// ummmm... you in trouble
2323
+					return $result;
2324
+					break;
2325
+			}
2326
+			if (! empty($error_message)) {
2327
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2328
+				trigger_error($error_message);
2329
+			}
2330
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
+		}
2332
+		return $result;
2333
+	}
2334
+
2335
+
2336
+
2337
+	/**
2338
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2339
+	 * EEM_Base::$_db_verification_level
2340
+	 *
2341
+	 * @param string $wpdb_method
2342
+	 * @param array  $arguments_to_provide
2343
+	 * @return string
2344
+	 */
2345
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2346
+	{
2347
+		/** @type WPDB $wpdb */
2348
+		global $wpdb;
2349
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2350
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2351
+		$error_message = sprintf(
2352
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2353
+				'event_espresso'),
2354
+			$wpdb->last_error,
2355
+			$wpdb_method,
2356
+			wp_json_encode($arguments_to_provide)
2357
+		);
2358
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2359
+		return $error_message;
2360
+	}
2361
+
2362
+
2363
+
2364
+	/**
2365
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2366
+	 * EEM_Base::$_db_verification_level
2367
+	 *
2368
+	 * @param $wpdb_method
2369
+	 * @param $arguments_to_provide
2370
+	 * @return string
2371
+	 */
2372
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2373
+	{
2374
+		/** @type WPDB $wpdb */
2375
+		global $wpdb;
2376
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2377
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2378
+		$error_message = sprintf(
2379
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2380
+				'event_espresso'),
2381
+			$wpdb->last_error,
2382
+			$wpdb_method,
2383
+			wp_json_encode($arguments_to_provide)
2384
+		);
2385
+		EE_System::instance()->initialize_addons();
2386
+		return $error_message;
2387
+	}
2388
+
2389
+
2390
+
2391
+	/**
2392
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2393
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2394
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2395
+	 * ..."
2396
+	 *
2397
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2398
+	 * @return string
2399
+	 */
2400
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2401
+	{
2402
+		return " FROM " . $model_query_info->get_full_join_sql() .
2403
+			   $model_query_info->get_where_sql() .
2404
+			   $model_query_info->get_group_by_sql() .
2405
+			   $model_query_info->get_having_sql() .
2406
+			   $model_query_info->get_order_by_sql() .
2407
+			   $model_query_info->get_limit_sql();
2408
+	}
2409
+
2410
+
2411
+
2412
+	/**
2413
+	 * Set to easily debug the next X queries ran from this model.
2414
+	 *
2415
+	 * @param int $count
2416
+	 */
2417
+	public function show_next_x_db_queries($count = 1)
2418
+	{
2419
+		$this->_show_next_x_db_queries = $count;
2420
+	}
2421
+
2422
+
2423
+
2424
+	/**
2425
+	 * @param $sql_query
2426
+	 */
2427
+	public function show_db_query_if_previously_requested($sql_query)
2428
+	{
2429
+		if ($this->_show_next_x_db_queries > 0) {
2430
+			echo $sql_query;
2431
+			$this->_show_next_x_db_queries--;
2432
+		}
2433
+	}
2434
+
2435
+
2436
+
2437
+	/**
2438
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2439
+	 * There are the 3 cases:
2440
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2441
+	 * $otherModelObject has no ID, it is first saved.
2442
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2443
+	 * has no ID, it is first saved.
2444
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2445
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2446
+	 * join table
2447
+	 *
2448
+	 * @param        EE_Base_Class                     /int $thisModelObject
2449
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2450
+	 * @param string $relationName                     , key in EEM_Base::_relations
2451
+	 *                                                 an attendee to a group, you also want to specify which role they
2452
+	 *                                                 will have in that group. So you would use this parameter to
2453
+	 *                                                 specify array('role-column-name'=>'role-id')
2454
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2455
+	 *                                                 to for relation to methods that allow you to further specify
2456
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2457
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2458
+	 *                                                 because these will be inserted in any new rows created as well.
2459
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2460
+	 * @throws EE_Error
2461
+	 */
2462
+	public function add_relationship_to(
2463
+		$id_or_obj,
2464
+		$other_model_id_or_obj,
2465
+		$relationName,
2466
+		$extra_join_model_fields_n_values = array()
2467
+	) {
2468
+		$relation_obj = $this->related_settings_for($relationName);
2469
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2470
+	}
2471
+
2472
+
2473
+
2474
+	/**
2475
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2476
+	 * There are the 3 cases:
2477
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2478
+	 * error
2479
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2480
+	 * an error
2481
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2482
+	 *
2483
+	 * @param        EE_Base_Class /int $id_or_obj
2484
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2485
+	 * @param string $relationName key in EEM_Base::_relations
2486
+	 * @return boolean of success
2487
+	 * @throws EE_Error
2488
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2489
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2490
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2491
+	 *                             because these will be inserted in any new rows created as well.
2492
+	 */
2493
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2494
+	{
2495
+		$relation_obj = $this->related_settings_for($relationName);
2496
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2497
+	}
2498
+
2499
+
2500
+
2501
+	/**
2502
+	 * @param mixed           $id_or_obj
2503
+	 * @param string          $relationName
2504
+	 * @param array           $where_query_params
2505
+	 * @param EE_Base_Class[] objects to which relations were removed
2506
+	 * @return \EE_Base_Class[]
2507
+	 * @throws EE_Error
2508
+	 */
2509
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2510
+	{
2511
+		$relation_obj = $this->related_settings_for($relationName);
2512
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2513
+	}
2514
+
2515
+
2516
+
2517
+	/**
2518
+	 * Gets all the related items of the specified $model_name, using $query_params.
2519
+	 * Note: by default, we remove the "default query params"
2520
+	 * because we want to get even deleted items etc.
2521
+	 *
2522
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2523
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2524
+	 * @param array  $query_params like EEM_Base::get_all
2525
+	 * @return EE_Base_Class[]
2526
+	 * @throws EE_Error
2527
+	 */
2528
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2529
+	{
2530
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2531
+		$relation_settings = $this->related_settings_for($model_name);
2532
+		return $relation_settings->get_all_related($model_obj, $query_params);
2533
+	}
2534
+
2535
+
2536
+
2537
+	/**
2538
+	 * Deletes all the model objects across the relation indicated by $model_name
2539
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2540
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2541
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2542
+	 *
2543
+	 * @param EE_Base_Class|int|string $id_or_obj
2544
+	 * @param string                   $model_name
2545
+	 * @param array                    $query_params
2546
+	 * @return int how many deleted
2547
+	 * @throws EE_Error
2548
+	 */
2549
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2550
+	{
2551
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2552
+		$relation_settings = $this->related_settings_for($model_name);
2553
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2554
+	}
2555
+
2556
+
2557
+
2558
+	/**
2559
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2560
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2561
+	 * the model objects can't be hard deleted because of blocking related model objects,
2562
+	 * just does a soft-delete on them instead.
2563
+	 *
2564
+	 * @param EE_Base_Class|int|string $id_or_obj
2565
+	 * @param string                   $model_name
2566
+	 * @param array                    $query_params
2567
+	 * @return int how many deleted
2568
+	 * @throws EE_Error
2569
+	 */
2570
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2571
+	{
2572
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2573
+		$relation_settings = $this->related_settings_for($model_name);
2574
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2575
+	}
2576
+
2577
+
2578
+
2579
+	/**
2580
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2581
+	 * unless otherwise specified in the $query_params
2582
+	 *
2583
+	 * @param        int             /EE_Base_Class $id_or_obj
2584
+	 * @param string $model_name     like 'Event', or 'Registration'
2585
+	 * @param array  $query_params   like EEM_Base::get_all's
2586
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2587
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2588
+	 *                               that by the setting $distinct to TRUE;
2589
+	 * @return int
2590
+	 * @throws EE_Error
2591
+	 */
2592
+	public function count_related(
2593
+		$id_or_obj,
2594
+		$model_name,
2595
+		$query_params = array(),
2596
+		$field_to_count = null,
2597
+		$distinct = false
2598
+	) {
2599
+		$related_model = $this->get_related_model_obj($model_name);
2600
+		//we're just going to use the query params on the related model's normal get_all query,
2601
+		//except add a condition to say to match the current mod
2602
+		if (! isset($query_params['default_where_conditions'])) {
2603
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2604
+		}
2605
+		$this_model_name = $this->get_this_model_name();
2606
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2607
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2608
+		return $related_model->count($query_params, $field_to_count, $distinct);
2609
+	}
2610
+
2611
+
2612
+
2613
+	/**
2614
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2615
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2616
+	 *
2617
+	 * @param        int           /EE_Base_Class $id_or_obj
2618
+	 * @param string $model_name   like 'Event', or 'Registration'
2619
+	 * @param array  $query_params like EEM_Base::get_all's
2620
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2621
+	 * @return float
2622
+	 * @throws EE_Error
2623
+	 */
2624
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2625
+	{
2626
+		$related_model = $this->get_related_model_obj($model_name);
2627
+		if (! is_array($query_params)) {
2628
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2629
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2630
+					gettype($query_params)), '4.6.0');
2631
+			$query_params = array();
2632
+		}
2633
+		//we're just going to use the query params on the related model's normal get_all query,
2634
+		//except add a condition to say to match the current mod
2635
+		if (! isset($query_params['default_where_conditions'])) {
2636
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2637
+		}
2638
+		$this_model_name = $this->get_this_model_name();
2639
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2640
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2641
+		return $related_model->sum($query_params, $field_to_sum);
2642
+	}
2643
+
2644
+
2645
+
2646
+	/**
2647
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2648
+	 * $modelObject
2649
+	 *
2650
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2651
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2652
+	 * @param array               $query_params     like EEM_Base::get_all's
2653
+	 * @return EE_Base_Class
2654
+	 * @throws EE_Error
2655
+	 */
2656
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2657
+	{
2658
+		$query_params['limit'] = 1;
2659
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2660
+		if ($results) {
2661
+			return array_shift($results);
2662
+		} else {
2663
+			return null;
2664
+		}
2665
+	}
2666
+
2667
+
2668
+
2669
+	/**
2670
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2671
+	 *
2672
+	 * @return string
2673
+	 */
2674
+	public function get_this_model_name()
2675
+	{
2676
+		return str_replace("EEM_", "", get_class($this));
2677
+	}
2678
+
2679
+
2680
+
2681
+	/**
2682
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2683
+	 *
2684
+	 * @return EE_Any_Foreign_Model_Name_Field
2685
+	 * @throws EE_Error
2686
+	 */
2687
+	public function get_field_containing_related_model_name()
2688
+	{
2689
+		foreach ($this->field_settings(true) as $field) {
2690
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2691
+				$field_with_model_name = $field;
2692
+			}
2693
+		}
2694
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2695
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2696
+				$this->get_this_model_name()));
2697
+		}
2698
+		return $field_with_model_name;
2699
+	}
2700
+
2701
+
2702
+
2703
+	/**
2704
+	 * Inserts a new entry into the database, for each table.
2705
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2706
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2707
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2708
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2709
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2710
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2711
+	 *
2712
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2713
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2714
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2715
+	 *                              of EEM_Base)
2716
+	 * @return int new primary key on main table that got inserted
2717
+	 * @throws EE_Error
2718
+	 */
2719
+	public function insert($field_n_values)
2720
+	{
2721
+		/**
2722
+		 * Filters the fields and their values before inserting an item using the models
2723
+		 *
2724
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2725
+		 * @param EEM_Base $model           the model used
2726
+		 */
2727
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2728
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2729
+			$main_table = $this->_get_main_table();
2730
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2731
+			if ($new_id !== false) {
2732
+				foreach ($this->_get_other_tables() as $other_table) {
2733
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2734
+				}
2735
+			}
2736
+			/**
2737
+			 * Done just after attempting to insert a new model object
2738
+			 *
2739
+			 * @param EEM_Base   $model           used
2740
+			 * @param array      $fields_n_values fields and their values
2741
+			 * @param int|string the              ID of the newly-inserted model object
2742
+			 */
2743
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2744
+			return $new_id;
2745
+		} else {
2746
+			return false;
2747
+		}
2748
+	}
2749
+
2750
+
2751
+
2752
+	/**
2753
+	 * Checks that the result would satisfy the unique indexes on this model
2754
+	 *
2755
+	 * @param array  $field_n_values
2756
+	 * @param string $action
2757
+	 * @return boolean
2758
+	 * @throws EE_Error
2759
+	 */
2760
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2761
+	{
2762
+		foreach ($this->unique_indexes() as $index_name => $index) {
2763
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2764
+			if ($this->exists(array($uniqueness_where_params))) {
2765
+				EE_Error::add_error(
2766
+					sprintf(
2767
+						__(
2768
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2769
+							"event_espresso"
2770
+						),
2771
+						$action,
2772
+						$this->_get_class_name(),
2773
+						$index_name,
2774
+						implode(",", $index->field_names()),
2775
+						http_build_query($uniqueness_where_params)
2776
+					),
2777
+					__FILE__,
2778
+					__FUNCTION__,
2779
+					__LINE__
2780
+				);
2781
+				return false;
2782
+			}
2783
+		}
2784
+		return true;
2785
+	}
2786
+
2787
+
2788
+
2789
+	/**
2790
+	 * Checks the database for an item that conflicts (ie, if this item were
2791
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2792
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2793
+	 * can be either an EE_Base_Class or an array of fields n values
2794
+	 *
2795
+	 * @param EE_Base_Class|array $obj_or_fields_array
2796
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2797
+	 *                                                 when looking for conflicts
2798
+	 *                                                 (ie, if false, we ignore the model object's primary key
2799
+	 *                                                 when finding "conflicts". If true, it's also considered).
2800
+	 *                                                 Only works for INT primary key,
2801
+	 *                                                 STRING primary keys cannot be ignored
2802
+	 * @throws EE_Error
2803
+	 * @return EE_Base_Class|array
2804
+	 */
2805
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2806
+	{
2807
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2808
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2809
+		} elseif (is_array($obj_or_fields_array)) {
2810
+			$fields_n_values = $obj_or_fields_array;
2811
+		} else {
2812
+			throw new EE_Error(
2813
+				sprintf(
2814
+					__(
2815
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2816
+						"event_espresso"
2817
+					),
2818
+					get_class($this),
2819
+					$obj_or_fields_array
2820
+				)
2821
+			);
2822
+		}
2823
+		$query_params = array();
2824
+		if ($this->has_primary_key_field()
2825
+			&& ($include_primary_key
2826
+				|| $this->get_primary_key_field()
2827
+				   instanceof
2828
+				   EE_Primary_Key_String_Field)
2829
+			&& isset($fields_n_values[$this->primary_key_name()])
2830
+		) {
2831
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2832
+		}
2833
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2834
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2835
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2836
+		}
2837
+		//if there is nothing to base this search on, then we shouldn't find anything
2838
+		if (empty($query_params)) {
2839
+			return array();
2840
+		} else {
2841
+			return $this->get_one($query_params);
2842
+		}
2843
+	}
2844
+
2845
+
2846
+
2847
+	/**
2848
+	 * Like count, but is optimized and returns a boolean instead of an int
2849
+	 *
2850
+	 * @param array $query_params
2851
+	 * @return boolean
2852
+	 * @throws EE_Error
2853
+	 */
2854
+	public function exists($query_params)
2855
+	{
2856
+		$query_params['limit'] = 1;
2857
+		return $this->count($query_params) > 0;
2858
+	}
2859
+
2860
+
2861
+
2862
+	/**
2863
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2864
+	 *
2865
+	 * @param int|string $id
2866
+	 * @return boolean
2867
+	 * @throws EE_Error
2868
+	 */
2869
+	public function exists_by_ID($id)
2870
+	{
2871
+		return $this->exists(
2872
+			array(
2873
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2874
+				array(
2875
+					$this->primary_key_name() => $id,
2876
+				),
2877
+			)
2878
+		);
2879
+	}
2880
+
2881
+
2882
+
2883
+	/**
2884
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2885
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2886
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2887
+	 * on the main table)
2888
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2889
+	 * cases where we want to call it directly rather than via insert().
2890
+	 *
2891
+	 * @access   protected
2892
+	 * @param EE_Table_Base $table
2893
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2894
+	 *                                       float
2895
+	 * @param int           $new_id          for now we assume only int keys
2896
+	 * @throws EE_Error
2897
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2898
+	 * @return int ID of new row inserted, or FALSE on failure
2899
+	 */
2900
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2901
+	{
2902
+		global $wpdb;
2903
+		$insertion_col_n_values = array();
2904
+		$format_for_insertion = array();
2905
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2906
+		foreach ($fields_on_table as $field_name => $field_obj) {
2907
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2908
+			if ($field_obj->is_auto_increment()) {
2909
+				continue;
2910
+			}
2911
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2912
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2913
+			if ($prepared_value !== null) {
2914
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2915
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2916
+			}
2917
+		}
2918
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2919
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2920
+			//so add the fk to the main table as a column
2921
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2922
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2923
+		}
2924
+		//insert the new entry
2925
+		$result = $this->_do_wpdb_query('insert',
2926
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2927
+		if ($result === false) {
2928
+			return false;
2929
+		}
2930
+		//ok, now what do we return for the ID of the newly-inserted thing?
2931
+		if ($this->has_primary_key_field()) {
2932
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2933
+				return $wpdb->insert_id;
2934
+			} else {
2935
+				//it's not an auto-increment primary key, so
2936
+				//it must have been supplied
2937
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2938
+			}
2939
+		} else {
2940
+			//we can't return a  primary key because there is none. instead return
2941
+			//a unique string indicating this model
2942
+			return $this->get_index_primary_key_string($fields_n_values);
2943
+		}
2944
+	}
2945
+
2946
+
2947
+
2948
+	/**
2949
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2950
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2951
+	 * and there is no default, we pass it along. WPDB will take care of it)
2952
+	 *
2953
+	 * @param EE_Model_Field_Base $field_obj
2954
+	 * @param array               $fields_n_values
2955
+	 * @return mixed string|int|float depending on what the table column will be expecting
2956
+	 * @throws EE_Error
2957
+	 */
2958
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2959
+	{
2960
+		//if this field doesn't allow nullable, don't allow it
2961
+		if (
2962
+			! $field_obj->is_nullable()
2963
+			&& (
2964
+				! isset($fields_n_values[$field_obj->get_name()])
2965
+				|| $fields_n_values[$field_obj->get_name()] === null
2966
+			)
2967
+		) {
2968
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2969
+		}
2970
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2971
+			? $fields_n_values[$field_obj->get_name()]
2972
+			: null;
2973
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2974
+	}
2975
+
2976
+
2977
+
2978
+	/**
2979
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2980
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2981
+	 * the field's prepare_for_set() method.
2982
+	 *
2983
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2984
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2985
+	 *                                   top of file)
2986
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2987
+	 *                                   $value is a custom selection
2988
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2989
+	 */
2990
+	private function _prepare_value_for_use_in_db($value, $field)
2991
+	{
2992
+		if ($field && $field instanceof EE_Model_Field_Base) {
2993
+			switch ($this->_values_already_prepared_by_model_object) {
2994
+				/** @noinspection PhpMissingBreakStatementInspection */
2995
+				case self::not_prepared_by_model_object:
2996
+					$value = $field->prepare_for_set($value);
2997
+				//purposefully left out "return"
2998
+				case self::prepared_by_model_object:
2999
+					$value = $field->prepare_for_use_in_db($value);
3000
+				case self::prepared_for_use_in_db:
3001
+					//leave the value alone
3002
+			}
3003
+			return $value;
3004
+		} else {
3005
+			return $value;
3006
+		}
3007
+	}
3008
+
3009
+
3010
+
3011
+	/**
3012
+	 * Returns the main table on this model
3013
+	 *
3014
+	 * @return EE_Primary_Table
3015
+	 * @throws EE_Error
3016
+	 */
3017
+	protected function _get_main_table()
3018
+	{
3019
+		foreach ($this->_tables as $table) {
3020
+			if ($table instanceof EE_Primary_Table) {
3021
+				return $table;
3022
+			}
3023
+		}
3024
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3025
+			'event_espresso'), get_class($this)));
3026
+	}
3027
+
3028
+
3029
+
3030
+	/**
3031
+	 * table
3032
+	 * returns EE_Primary_Table table name
3033
+	 *
3034
+	 * @return string
3035
+	 * @throws EE_Error
3036
+	 */
3037
+	public function table()
3038
+	{
3039
+		return $this->_get_main_table()->get_table_name();
3040
+	}
3041
+
3042
+
3043
+
3044
+	/**
3045
+	 * table
3046
+	 * returns first EE_Secondary_Table table name
3047
+	 *
3048
+	 * @return string
3049
+	 */
3050
+	public function second_table()
3051
+	{
3052
+		// grab second table from tables array
3053
+		$second_table = end($this->_tables);
3054
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3055
+	}
3056
+
3057
+
3058
+
3059
+	/**
3060
+	 * get_table_obj_by_alias
3061
+	 * returns table name given it's alias
3062
+	 *
3063
+	 * @param string $table_alias
3064
+	 * @return EE_Primary_Table | EE_Secondary_Table
3065
+	 */
3066
+	public function get_table_obj_by_alias($table_alias = '')
3067
+	{
3068
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3069
+	}
3070
+
3071
+
3072
+
3073
+	/**
3074
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3075
+	 *
3076
+	 * @return EE_Secondary_Table[]
3077
+	 */
3078
+	protected function _get_other_tables()
3079
+	{
3080
+		$other_tables = array();
3081
+		foreach ($this->_tables as $table_alias => $table) {
3082
+			if ($table instanceof EE_Secondary_Table) {
3083
+				$other_tables[$table_alias] = $table;
3084
+			}
3085
+		}
3086
+		return $other_tables;
3087
+	}
3088
+
3089
+
3090
+
3091
+	/**
3092
+	 * Finds all the fields that correspond to the given table
3093
+	 *
3094
+	 * @param string $table_alias , array key in EEM_Base::_tables
3095
+	 * @return EE_Model_Field_Base[]
3096
+	 */
3097
+	public function _get_fields_for_table($table_alias)
3098
+	{
3099
+		return $this->_fields[$table_alias];
3100
+	}
3101
+
3102
+
3103
+
3104
+	/**
3105
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3106
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3107
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3108
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3109
+	 * related Registration, Transaction, and Payment models.
3110
+	 *
3111
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3112
+	 * @return EE_Model_Query_Info_Carrier
3113
+	 * @throws EE_Error
3114
+	 */
3115
+	public function _extract_related_models_from_query($query_params)
3116
+	{
3117
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3118
+		if (array_key_exists(0, $query_params)) {
3119
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3120
+		}
3121
+		if (array_key_exists('group_by', $query_params)) {
3122
+			if (is_array($query_params['group_by'])) {
3123
+				$this->_extract_related_models_from_sub_params_array_values(
3124
+					$query_params['group_by'],
3125
+					$query_info_carrier,
3126
+					'group_by'
3127
+				);
3128
+			} elseif (! empty ($query_params['group_by'])) {
3129
+				$this->_extract_related_model_info_from_query_param(
3130
+					$query_params['group_by'],
3131
+					$query_info_carrier,
3132
+					'group_by'
3133
+				);
3134
+			}
3135
+		}
3136
+		if (array_key_exists('having', $query_params)) {
3137
+			$this->_extract_related_models_from_sub_params_array_keys(
3138
+				$query_params[0],
3139
+				$query_info_carrier,
3140
+				'having'
3141
+			);
3142
+		}
3143
+		if (array_key_exists('order_by', $query_params)) {
3144
+			if (is_array($query_params['order_by'])) {
3145
+				$this->_extract_related_models_from_sub_params_array_keys(
3146
+					$query_params['order_by'],
3147
+					$query_info_carrier,
3148
+					'order_by'
3149
+				);
3150
+			} elseif (! empty($query_params['order_by'])) {
3151
+				$this->_extract_related_model_info_from_query_param(
3152
+					$query_params['order_by'],
3153
+					$query_info_carrier,
3154
+					'order_by'
3155
+				);
3156
+			}
3157
+		}
3158
+		if (array_key_exists('force_join', $query_params)) {
3159
+			$this->_extract_related_models_from_sub_params_array_values(
3160
+				$query_params['force_join'],
3161
+				$query_info_carrier,
3162
+				'force_join'
3163
+			);
3164
+		}
3165
+		return $query_info_carrier;
3166
+	}
3167
+
3168
+
3169
+
3170
+	/**
3171
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3172
+	 *
3173
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3174
+	 *                                                      $query_params['having']
3175
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3176
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3177
+	 * @throws EE_Error
3178
+	 * @return \EE_Model_Query_Info_Carrier
3179
+	 */
3180
+	private function _extract_related_models_from_sub_params_array_keys(
3181
+		$sub_query_params,
3182
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3183
+		$query_param_type
3184
+	) {
3185
+		if (! empty($sub_query_params)) {
3186
+			$sub_query_params = (array)$sub_query_params;
3187
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3188
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3189
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3190
+					$query_param_type);
3191
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3192
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3193
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3194
+				//of array('Registration.TXN_ID'=>23)
3195
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3196
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3197
+					if (! is_array($possibly_array_of_params)) {
3198
+						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3199
+							"event_espresso"),
3200
+							$param, $possibly_array_of_params));
3201
+					} else {
3202
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3203
+							$model_query_info_carrier, $query_param_type);
3204
+					}
3205
+				} elseif ($query_param_type === 0 //ie WHERE
3206
+						  && is_array($possibly_array_of_params)
3207
+						  && isset($possibly_array_of_params[2])
3208
+						  && $possibly_array_of_params[2] == true
3209
+				) {
3210
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3211
+					//indicating that $possible_array_of_params[1] is actually a field name,
3212
+					//from which we should extract query parameters!
3213
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3214
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3215
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3216
+					}
3217
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3218
+						$model_query_info_carrier, $query_param_type);
3219
+				}
3220
+			}
3221
+		}
3222
+		return $model_query_info_carrier;
3223
+	}
3224
+
3225
+
3226
+
3227
+	/**
3228
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3229
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3230
+	 *
3231
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3232
+	 *                                                      $query_params['having']
3233
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3234
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3235
+	 * @throws EE_Error
3236
+	 * @return \EE_Model_Query_Info_Carrier
3237
+	 */
3238
+	private function _extract_related_models_from_sub_params_array_values(
3239
+		$sub_query_params,
3240
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3241
+		$query_param_type
3242
+	) {
3243
+		if (! empty($sub_query_params)) {
3244
+			if (! is_array($sub_query_params)) {
3245
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3246
+					$sub_query_params));
3247
+			}
3248
+			foreach ($sub_query_params as $param) {
3249
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3250
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3251
+					$query_param_type);
3252
+			}
3253
+		}
3254
+		return $model_query_info_carrier;
3255
+	}
3256
+
3257
+
3258
+
3259
+	/**
3260
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3261
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3262
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3263
+	 * but use them in a different order. Eg, we need to know what models we are querying
3264
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3265
+	 * other models before we can finalize the where clause SQL.
3266
+	 *
3267
+	 * @param array $query_params
3268
+	 * @throws EE_Error
3269
+	 * @return EE_Model_Query_Info_Carrier
3270
+	 */
3271
+	public function _create_model_query_info_carrier($query_params)
3272
+	{
3273
+		if (! is_array($query_params)) {
3274
+			EE_Error::doing_it_wrong(
3275
+				'EEM_Base::_create_model_query_info_carrier',
3276
+				sprintf(
3277
+					__(
3278
+						'$query_params should be an array, you passed a variable of type %s',
3279
+						'event_espresso'
3280
+					),
3281
+					gettype($query_params)
3282
+				),
3283
+				'4.6.0'
3284
+			);
3285
+			$query_params = array();
3286
+		}
3287
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3288
+		//first check if we should alter the query to account for caps or not
3289
+		//because the caps might require us to do extra joins
3290
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3291
+			$query_params[0] = $where_query_params = array_replace_recursive(
3292
+				$where_query_params,
3293
+				$this->caps_where_conditions(
3294
+					$query_params['caps']
3295
+				)
3296
+			);
3297
+		}
3298
+		$query_object = $this->_extract_related_models_from_query($query_params);
3299
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3300
+		foreach ($where_query_params as $key => $value) {
3301
+			if (is_int($key)) {
3302
+				throw new EE_Error(
3303
+					sprintf(
3304
+						__(
3305
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3306
+							"event_espresso"
3307
+						),
3308
+						$key,
3309
+						var_export($value, true),
3310
+						var_export($query_params, true),
3311
+						get_class($this)
3312
+					)
3313
+				);
3314
+			}
3315
+		}
3316
+		if (
3317
+			array_key_exists('default_where_conditions', $query_params)
3318
+			&& ! empty($query_params['default_where_conditions'])
3319
+		) {
3320
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3321
+		} else {
3322
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3323
+		}
3324
+		$where_query_params = array_merge(
3325
+			$this->_get_default_where_conditions_for_models_in_query(
3326
+				$query_object,
3327
+				$use_default_where_conditions,
3328
+				$where_query_params
3329
+			),
3330
+			$where_query_params
3331
+		);
3332
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3333
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3334
+		// So we need to setup a subquery and use that for the main join.
3335
+		// Note for now this only works on the primary table for the model.
3336
+		// So for instance, you could set the limit array like this:
3337
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3338
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3339
+			$query_object->set_main_model_join_sql(
3340
+				$this->_construct_limit_join_select(
3341
+					$query_params['on_join_limit'][0],
3342
+					$query_params['on_join_limit'][1]
3343
+				)
3344
+			);
3345
+		}
3346
+		//set limit
3347
+		if (array_key_exists('limit', $query_params)) {
3348
+			if (is_array($query_params['limit'])) {
3349
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3350
+					$e = sprintf(
3351
+						__(
3352
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3353
+							"event_espresso"
3354
+						),
3355
+						http_build_query($query_params['limit'])
3356
+					);
3357
+					throw new EE_Error($e . "|" . $e);
3358
+				}
3359
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3360
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3361
+			} elseif (! empty ($query_params['limit'])) {
3362
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3363
+			}
3364
+		}
3365
+		//set order by
3366
+		if (array_key_exists('order_by', $query_params)) {
3367
+			if (is_array($query_params['order_by'])) {
3368
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3369
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3370
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3371
+				if (array_key_exists('order', $query_params)) {
3372
+					throw new EE_Error(
3373
+						sprintf(
3374
+							__(
3375
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3376
+								"event_espresso"
3377
+							),
3378
+							get_class($this),
3379
+							implode(", ", array_keys($query_params['order_by'])),
3380
+							implode(", ", $query_params['order_by']),
3381
+							$query_params['order']
3382
+						)
3383
+					);
3384
+				}
3385
+				$this->_extract_related_models_from_sub_params_array_keys(
3386
+					$query_params['order_by'],
3387
+					$query_object,
3388
+					'order_by'
3389
+				);
3390
+				//assume it's an array of fields to order by
3391
+				$order_array = array();
3392
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3393
+					$order = $this->_extract_order($order);
3394
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3395
+				}
3396
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3397
+			} elseif (! empty ($query_params['order_by'])) {
3398
+				$this->_extract_related_model_info_from_query_param(
3399
+					$query_params['order_by'],
3400
+					$query_object,
3401
+					'order',
3402
+					$query_params['order_by']
3403
+				);
3404
+				$order = isset($query_params['order'])
3405
+					? $this->_extract_order($query_params['order'])
3406
+					: 'DESC';
3407
+				$query_object->set_order_by_sql(
3408
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3409
+				);
3410
+			}
3411
+		}
3412
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3413
+		if (! array_key_exists('order_by', $query_params)
3414
+			&& array_key_exists('order', $query_params)
3415
+			&& ! empty($query_params['order'])
3416
+		) {
3417
+			$pk_field = $this->get_primary_key_field();
3418
+			$order = $this->_extract_order($query_params['order']);
3419
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3420
+		}
3421
+		//set group by
3422
+		if (array_key_exists('group_by', $query_params)) {
3423
+			if (is_array($query_params['group_by'])) {
3424
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3425
+				$group_by_array = array();
3426
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3427
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3428
+				}
3429
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3430
+			} elseif (! empty ($query_params['group_by'])) {
3431
+				$query_object->set_group_by_sql(
3432
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3433
+				);
3434
+			}
3435
+		}
3436
+		//set having
3437
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3438
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3439
+		}
3440
+		//now, just verify they didn't pass anything wack
3441
+		foreach ($query_params as $query_key => $query_value) {
3442
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3443
+				throw new EE_Error(
3444
+					sprintf(
3445
+						__(
3446
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3447
+							'event_espresso'
3448
+						),
3449
+						$query_key,
3450
+						get_class($this),
3451
+						//						print_r( $this->_allowed_query_params, TRUE )
3452
+						implode(',', $this->_allowed_query_params)
3453
+					)
3454
+				);
3455
+			}
3456
+		}
3457
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3458
+		if (empty($main_model_join_sql)) {
3459
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3460
+		}
3461
+		return $query_object;
3462
+	}
3463
+
3464
+
3465
+
3466
+	/**
3467
+	 * Gets the where conditions that should be imposed on the query based on the
3468
+	 * context (eg reading frontend, backend, edit or delete).
3469
+	 *
3470
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3471
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3472
+	 * @throws EE_Error
3473
+	 */
3474
+	public function caps_where_conditions($context = self::caps_read)
3475
+	{
3476
+		EEM_Base::verify_is_valid_cap_context($context);
3477
+		$cap_where_conditions = array();
3478
+		$cap_restrictions = $this->caps_missing($context);
3479
+		/**
3480
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3481
+		 */
3482
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3483
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3484
+				$restriction_if_no_cap->get_default_where_conditions());
3485
+		}
3486
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3487
+			$cap_restrictions);
3488
+	}
3489
+
3490
+
3491
+
3492
+	/**
3493
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3494
+	 * otherwise throws an exception
3495
+	 *
3496
+	 * @param string $should_be_order_string
3497
+	 * @return string either ASC, asc, DESC or desc
3498
+	 * @throws EE_Error
3499
+	 */
3500
+	private function _extract_order($should_be_order_string)
3501
+	{
3502
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3503
+			return $should_be_order_string;
3504
+		} else {
3505
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3506
+				"event_espresso"), get_class($this), $should_be_order_string));
3507
+		}
3508
+	}
3509
+
3510
+
3511
+
3512
+	/**
3513
+	 * Looks at all the models which are included in this query, and asks each
3514
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3515
+	 * so they can be merged
3516
+	 *
3517
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3518
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3519
+	 *                                                                  'none' means NO default where conditions will
3520
+	 *                                                                  be used AT ALL during this query.
3521
+	 *                                                                  'other_models_only' means default where
3522
+	 *                                                                  conditions from other models will be used, but
3523
+	 *                                                                  not for this primary model. 'all', the default,
3524
+	 *                                                                  means default where conditions will apply as
3525
+	 *                                                                  normal
3526
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3527
+	 * @throws EE_Error
3528
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3529
+	 */
3530
+	private function _get_default_where_conditions_for_models_in_query(
3531
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3532
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3533
+		$where_query_params = array()
3534
+	) {
3535
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3536
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3537
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3538
+				"event_espresso"), $use_default_where_conditions,
3539
+				implode(", ", $allowed_used_default_where_conditions_values)));
3540
+		}
3541
+		$universal_query_params = array();
3542
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3543
+			$universal_query_params = $this->_get_default_where_conditions();
3544
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3545
+			$universal_query_params = $this->_get_minimum_where_conditions();
3546
+		}
3547
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3548
+			$related_model = $this->get_related_model_obj($model_name);
3549
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3550
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3551
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3552
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3553
+			} else {
3554
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3555
+				continue;
3556
+			}
3557
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3558
+				$related_model_universal_where_params,
3559
+				$where_query_params,
3560
+				$related_model,
3561
+				$model_relation_path
3562
+			);
3563
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3564
+				$universal_query_params,
3565
+				$overrides
3566
+			);
3567
+		}
3568
+		return $universal_query_params;
3569
+	}
3570
+
3571
+
3572
+
3573
+	/**
3574
+	 * Determines whether or not we should use default where conditions for the model in question
3575
+	 * (this model, or other related models).
3576
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3577
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3578
+	 * We should use default where conditions on related models when they requested to use default where conditions
3579
+	 * on all models, or specifically just on other related models
3580
+	 * @param      $default_where_conditions_value
3581
+	 * @param bool $for_this_model false means this is for OTHER related models
3582
+	 * @return bool
3583
+	 */
3584
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3585
+	{
3586
+		return (
3587
+				   $for_this_model
3588
+				   && in_array(
3589
+					   $default_where_conditions_value,
3590
+					   array(
3591
+						   EEM_Base::default_where_conditions_all,
3592
+						   EEM_Base::default_where_conditions_this_only,
3593
+						   EEM_Base::default_where_conditions_minimum_others,
3594
+					   ),
3595
+					   true
3596
+				   )
3597
+			   )
3598
+			   || (
3599
+				   ! $for_this_model
3600
+				   && in_array(
3601
+					   $default_where_conditions_value,
3602
+					   array(
3603
+						   EEM_Base::default_where_conditions_all,
3604
+						   EEM_Base::default_where_conditions_others_only,
3605
+					   ),
3606
+					   true
3607
+				   )
3608
+			   );
3609
+	}
3610
+
3611
+	/**
3612
+	 * Determines whether or not we should use default minimum conditions for the model in question
3613
+	 * (this model, or other related models).
3614
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3615
+	 * where conditions.
3616
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3617
+	 * on this model or others
3618
+	 * @param      $default_where_conditions_value
3619
+	 * @param bool $for_this_model false means this is for OTHER related models
3620
+	 * @return bool
3621
+	 */
3622
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3623
+	{
3624
+		return (
3625
+				   $for_this_model
3626
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3627
+			   )
3628
+			   || (
3629
+				   ! $for_this_model
3630
+				   && in_array(
3631
+					   $default_where_conditions_value,
3632
+					   array(
3633
+						   EEM_Base::default_where_conditions_minimum_others,
3634
+						   EEM_Base::default_where_conditions_minimum_all,
3635
+					   ),
3636
+					   true
3637
+				   )
3638
+			   );
3639
+	}
3640
+
3641
+
3642
+	/**
3643
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3644
+	 * then we also add a special where condition which allows for that model's primary key
3645
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3646
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3647
+	 *
3648
+	 * @param array    $default_where_conditions
3649
+	 * @param array    $provided_where_conditions
3650
+	 * @param EEM_Base $model
3651
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3652
+	 * @return array like EEM_Base::get_all's $query_params[0]
3653
+	 * @throws EE_Error
3654
+	 */
3655
+	private function _override_defaults_or_make_null_friendly(
3656
+		$default_where_conditions,
3657
+		$provided_where_conditions,
3658
+		$model,
3659
+		$model_relation_path
3660
+	) {
3661
+		$null_friendly_where_conditions = array();
3662
+		$none_overridden = true;
3663
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3664
+		foreach ($default_where_conditions as $key => $val) {
3665
+			if (isset($provided_where_conditions[$key])) {
3666
+				$none_overridden = false;
3667
+			} else {
3668
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3669
+			}
3670
+		}
3671
+		if ($none_overridden && $default_where_conditions) {
3672
+			if ($model->has_primary_key_field()) {
3673
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3674
+																				. "."
3675
+																				. $model->primary_key_name()] = array('IS NULL');
3676
+			}/*else{
3677 3677
 				//@todo NO PK, use other defaults
3678 3678
 			}*/
3679
-        }
3680
-        return $null_friendly_where_conditions;
3681
-    }
3682
-
3683
-
3684
-
3685
-    /**
3686
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3687
-     * default where conditions on all get_all, update, and delete queries done by this model.
3688
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3689
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3690
-     *
3691
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3692
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3693
-     */
3694
-    private function _get_default_where_conditions($model_relation_path = null)
3695
-    {
3696
-        if ($this->_ignore_where_strategy) {
3697
-            return array();
3698
-        }
3699
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3700
-    }
3701
-
3702
-
3703
-
3704
-    /**
3705
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3706
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3707
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3708
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3709
-     * Similar to _get_default_where_conditions
3710
-     *
3711
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3712
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3713
-     */
3714
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3715
-    {
3716
-        if ($this->_ignore_where_strategy) {
3717
-            return array();
3718
-        }
3719
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3720
-    }
3721
-
3722
-
3723
-
3724
-    /**
3725
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3726
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3727
-     *
3728
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3729
-     * @return string
3730
-     * @throws EE_Error
3731
-     */
3732
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3733
-    {
3734
-        $selects = $this->_get_columns_to_select_for_this_model();
3735
-        foreach (
3736
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3737
-            $name_of_other_model_included
3738
-        ) {
3739
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3740
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3741
-            foreach ($other_model_selects as $key => $value) {
3742
-                $selects[] = $value;
3743
-            }
3744
-        }
3745
-        return implode(", ", $selects);
3746
-    }
3747
-
3748
-
3749
-
3750
-    /**
3751
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3752
-     * So that's going to be the columns for all the fields on the model
3753
-     *
3754
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3755
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3756
-     */
3757
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3758
-    {
3759
-        $fields = $this->field_settings();
3760
-        $selects = array();
3761
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3762
-            $this->get_this_model_name());
3763
-        foreach ($fields as $field_obj) {
3764
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3765
-                         . $field_obj->get_table_alias()
3766
-                         . "."
3767
-                         . $field_obj->get_table_column()
3768
-                         . " AS '"
3769
-                         . $table_alias_with_model_relation_chain_prefix
3770
-                         . $field_obj->get_table_alias()
3771
-                         . "."
3772
-                         . $field_obj->get_table_column()
3773
-                         . "'";
3774
-        }
3775
-        //make sure we are also getting the PKs of each table
3776
-        $tables = $this->get_tables();
3777
-        if (count($tables) > 1) {
3778
-            foreach ($tables as $table_obj) {
3779
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3780
-                                       . $table_obj->get_fully_qualified_pk_column();
3781
-                if (! in_array($qualified_pk_column, $selects)) {
3782
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3783
-                }
3784
-            }
3785
-        }
3786
-        return $selects;
3787
-    }
3788
-
3789
-
3790
-
3791
-    /**
3792
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3793
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3794
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3795
-     * SQL for joining, and the data types
3796
-     *
3797
-     * @param null|string                 $original_query_param
3798
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3799
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3800
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3801
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3802
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3803
-     *                                                          or 'Registration's
3804
-     * @param string                      $original_query_param what it originally was (eg
3805
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3806
-     *                                                          matches $query_param
3807
-     * @throws EE_Error
3808
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3809
-     */
3810
-    private function _extract_related_model_info_from_query_param(
3811
-        $query_param,
3812
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3813
-        $query_param_type,
3814
-        $original_query_param = null
3815
-    ) {
3816
-        if ($original_query_param === null) {
3817
-            $original_query_param = $query_param;
3818
-        }
3819
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3820
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3821
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3822
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3823
-        //check to see if we have a field on this model
3824
-        $this_model_fields = $this->field_settings(true);
3825
-        if (array_key_exists($query_param, $this_model_fields)) {
3826
-            if ($allow_fields) {
3827
-                return;
3828
-            } else {
3829
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3830
-                    "event_espresso"),
3831
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3832
-            }
3833
-        } //check if this is a special logic query param
3834
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3835
-            if ($allow_logic_query_params) {
3836
-                return;
3837
-            } else {
3838
-                throw new EE_Error(
3839
-                    sprintf(
3840
-                        __('Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3841
-                            'event_espresso'),
3842
-                        implode('", "', $this->_logic_query_param_keys),
3843
-                        $query_param,
3844
-                        get_class($this),
3845
-                        '<br />',
3846
-                        "\t"
3847
-                        . ' $passed_in_query_info = <pre>'
3848
-                        . print_r($passed_in_query_info, true)
3849
-                        . '</pre>'
3850
-                        . "\n\t"
3851
-                        . ' $query_param_type = '
3852
-                        . $query_param_type
3853
-                        . "\n\t"
3854
-                        . ' $original_query_param = '
3855
-                        . $original_query_param
3856
-                    )
3857
-                );
3858
-            }
3859
-        } //check if it's a custom selection
3860
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3861
-            return;
3862
-        }
3863
-        //check if has a model name at the beginning
3864
-        //and
3865
-        //check if it's a field on a related model
3866
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3867
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3868
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3869
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3870
-                if ($query_param === '') {
3871
-                    //nothing left to $query_param
3872
-                    //we should actually end in a field name, not a model like this!
3873
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3874
-                        "event_espresso"),
3875
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3876
-                } else {
3877
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3878
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3879
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3880
-                    return;
3881
-                }
3882
-            } elseif ($query_param === $valid_related_model_name) {
3883
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3884
-                return;
3885
-            }
3886
-        }
3887
-        //ok so $query_param didn't start with a model name
3888
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3889
-        //it's wack, that's what it is
3890
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3891
-            "event_espresso"),
3892
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3893
-    }
3894
-
3895
-
3896
-
3897
-    /**
3898
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3899
-     * and store it on $passed_in_query_info
3900
-     *
3901
-     * @param string                      $model_name
3902
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3903
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3904
-     *                                                          model and $model_name. Eg, if we are querying Event,
3905
-     *                                                          and are adding a join to 'Payment' with the original
3906
-     *                                                          query param key
3907
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3908
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3909
-     *                                                          Payment wants to add default query params so that it
3910
-     *                                                          will know what models to prepend onto its default query
3911
-     *                                                          params or in case it wants to rename tables (in case
3912
-     *                                                          there are multiple joins to the same table)
3913
-     * @return void
3914
-     * @throws EE_Error
3915
-     */
3916
-    private function _add_join_to_model(
3917
-        $model_name,
3918
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3919
-        $original_query_param
3920
-    ) {
3921
-        $relation_obj = $this->related_settings_for($model_name);
3922
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3923
-        //check if the relation is HABTM, because then we're essentially doing two joins
3924
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3925
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3926
-            $join_model_obj = $relation_obj->get_join_model();
3927
-            //replace the model specified with the join model for this relation chain, whi
3928
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3929
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3930
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3931
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3932
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3933
-            $passed_in_query_info->merge($new_query_info);
3934
-        }
3935
-        //now just join to the other table pointed to by the relation object, and add its data types
3936
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3937
-            array($model_relation_chain => $model_name),
3938
-            $relation_obj->get_join_statement($model_relation_chain));
3939
-        $passed_in_query_info->merge($new_query_info);
3940
-    }
3941
-
3942
-
3943
-
3944
-    /**
3945
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3946
-     *
3947
-     * @param array $where_params like EEM_Base::get_all
3948
-     * @return string of SQL
3949
-     * @throws EE_Error
3950
-     */
3951
-    private function _construct_where_clause($where_params)
3952
-    {
3953
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3954
-        if ($SQL) {
3955
-            return " WHERE " . $SQL;
3956
-        } else {
3957
-            return '';
3958
-        }
3959
-    }
3960
-
3961
-
3962
-
3963
-    /**
3964
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3965
-     * and should be passed HAVING parameters, not WHERE parameters
3966
-     *
3967
-     * @param array $having_params
3968
-     * @return string
3969
-     * @throws EE_Error
3970
-     */
3971
-    private function _construct_having_clause($having_params)
3972
-    {
3973
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3974
-        if ($SQL) {
3975
-            return " HAVING " . $SQL;
3976
-        } else {
3977
-            return '';
3978
-        }
3979
-    }
3980
-
3981
-
3982
-
3983
-    /**
3984
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3985
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3986
-     * EEM_Attendee.
3987
-     *
3988
-     * @param string $field_name
3989
-     * @param string $model_name
3990
-     * @return EE_Model_Field_Base
3991
-     * @throws EE_Error
3992
-     */
3993
-    protected function _get_field_on_model($field_name, $model_name)
3994
-    {
3995
-        $model_class = 'EEM_' . $model_name;
3996
-        $model_filepath = $model_class . ".model.php";
3997
-        if (is_readable($model_filepath)) {
3998
-            require_once($model_filepath);
3999
-            $model_instance = call_user_func($model_name . "::instance");
4000
-            /* @var $model_instance EEM_Base */
4001
-            return $model_instance->field_settings_for($field_name);
4002
-        } else {
4003
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
4004
-                'event_espresso'), $model_name, $model_class, $model_filepath));
4005
-        }
4006
-    }
4007
-
4008
-
4009
-
4010
-    /**
4011
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4012
-     * Event_Meta.meta_value = 'foo'))"
4013
-     *
4014
-     * @param array  $where_params see EEM_Base::get_all for documentation
4015
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4016
-     * @throws EE_Error
4017
-     * @return string of SQL
4018
-     */
4019
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4020
-    {
4021
-        $where_clauses = array();
4022
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4023
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4024
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4025
-                switch ($query_param) {
4026
-                    case 'not':
4027
-                    case 'NOT':
4028
-                        $where_clauses[] = "! ("
4029
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4030
-                                $glue)
4031
-                                           . ")";
4032
-                        break;
4033
-                    case 'and':
4034
-                    case 'AND':
4035
-                        $where_clauses[] = " ("
4036
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4037
-                                ' AND ')
4038
-                                           . ")";
4039
-                        break;
4040
-                    case 'or':
4041
-                    case 'OR':
4042
-                        $where_clauses[] = " ("
4043
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4044
-                                ' OR ')
4045
-                                           . ")";
4046
-                        break;
4047
-                }
4048
-            } else {
4049
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4050
-                //if it's not a normal field, maybe it's a custom selection?
4051
-                if (! $field_obj) {
4052
-                    if (isset($this->_custom_selections[$query_param][1])) {
4053
-                        $field_obj = $this->_custom_selections[$query_param][1];
4054
-                    } else {
4055
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4056
-                            "event_espresso"), $query_param));
4057
-                    }
4058
-                }
4059
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4060
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4061
-            }
4062
-        }
4063
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4064
-    }
4065
-
4066
-
4067
-
4068
-    /**
4069
-     * Takes the input parameter and extract the table name (alias) and column name
4070
-     *
4071
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4072
-     * @throws EE_Error
4073
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4074
-     */
4075
-    private function _deduce_column_name_from_query_param($query_param)
4076
-    {
4077
-        $field = $this->_deduce_field_from_query_param($query_param);
4078
-        if ($field) {
4079
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4080
-                $query_param);
4081
-            return $table_alias_prefix . $field->get_qualified_column();
4082
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4083
-            //maybe it's custom selection item?
4084
-            //if so, just use it as the "column name"
4085
-            return $query_param;
4086
-        } else {
4087
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4088
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4089
-        }
4090
-    }
4091
-
4092
-
4093
-
4094
-    /**
4095
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4096
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4097
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4098
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4099
-     *
4100
-     * @param string $condition_query_param_key
4101
-     * @return string
4102
-     */
4103
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4104
-    {
4105
-        $pos_of_star = strpos($condition_query_param_key, '*');
4106
-        if ($pos_of_star === false) {
4107
-            return $condition_query_param_key;
4108
-        } else {
4109
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4110
-            return $condition_query_param_sans_star;
4111
-        }
4112
-    }
4113
-
4114
-
4115
-
4116
-    /**
4117
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4118
-     *
4119
-     * @param                            mixed      array | string    $op_and_value
4120
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4121
-     * @throws EE_Error
4122
-     * @return string
4123
-     */
4124
-    private function _construct_op_and_value($op_and_value, $field_obj)
4125
-    {
4126
-        if (is_array($op_and_value)) {
4127
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4128
-            if (! $operator) {
4129
-                $php_array_like_string = array();
4130
-                foreach ($op_and_value as $key => $value) {
4131
-                    $php_array_like_string[] = "$key=>$value";
4132
-                }
4133
-                throw new EE_Error(
4134
-                    sprintf(
4135
-                        __(
4136
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4137
-                            "event_espresso"
4138
-                        ),
4139
-                        implode(",", $php_array_like_string)
4140
-                    )
4141
-                );
4142
-            }
4143
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4144
-        } else {
4145
-            $operator = '=';
4146
-            $value = $op_and_value;
4147
-        }
4148
-        //check to see if the value is actually another field
4149
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4150
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4151
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4152
-            //in this case, the value should be an array, or at least a comma-separated list
4153
-            //it will need to handle a little differently
4154
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4155
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4156
-            return $operator . SP . $cleaned_value;
4157
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4158
-            //the value should be an array with count of two.
4159
-            if (count($value) !== 2) {
4160
-                throw new EE_Error(
4161
-                    sprintf(
4162
-                        __(
4163
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4164
-                            'event_espresso'
4165
-                        ),
4166
-                        "BETWEEN"
4167
-                    )
4168
-                );
4169
-            }
4170
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4171
-            return $operator . SP . $cleaned_value;
4172
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4173
-            if ($value !== null) {
4174
-                throw new EE_Error(
4175
-                    sprintf(
4176
-                        __(
4177
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4178
-                            "event_espresso"
4179
-                        ),
4180
-                        $value,
4181
-                        $operator
4182
-                    )
4183
-                );
4184
-            }
4185
-            return $operator;
4186
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4187
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4188
-            //remove other junk. So just treat it as a string.
4189
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4190
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4191
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4192
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4193
-            throw new EE_Error(
4194
-                sprintf(
4195
-                    __(
4196
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4197
-                        'event_espresso'
4198
-                    ),
4199
-                    $operator,
4200
-                    $operator
4201
-                )
4202
-            );
4203
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4204
-            throw new EE_Error(
4205
-                sprintf(
4206
-                    __(
4207
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4208
-                        'event_espresso'
4209
-                    ),
4210
-                    $operator,
4211
-                    $operator
4212
-                )
4213
-            );
4214
-        } else {
4215
-            throw new EE_Error(
4216
-                sprintf(
4217
-                    __(
4218
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4219
-                        "event_espresso"
4220
-                    ),
4221
-                    http_build_query($op_and_value)
4222
-                )
4223
-            );
4224
-        }
4225
-    }
4226
-
4227
-
4228
-
4229
-    /**
4230
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4231
-     *
4232
-     * @param array                      $values
4233
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4234
-     *                                              '%s'
4235
-     * @return string
4236
-     * @throws EE_Error
4237
-     */
4238
-    public function _construct_between_value($values, $field_obj)
4239
-    {
4240
-        $cleaned_values = array();
4241
-        foreach ($values as $value) {
4242
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4243
-        }
4244
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4245
-    }
4246
-
4247
-
4248
-
4249
-    /**
4250
-     * Takes an array or a comma-separated list of $values and cleans them
4251
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4252
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4253
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4254
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4255
-     *
4256
-     * @param mixed                      $values    array or comma-separated string
4257
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4258
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4259
-     * @throws EE_Error
4260
-     */
4261
-    public function _construct_in_value($values, $field_obj)
4262
-    {
4263
-        //check if the value is a CSV list
4264
-        if (is_string($values)) {
4265
-            //in which case, turn it into an array
4266
-            $values = explode(",", $values);
4267
-        }
4268
-        $cleaned_values = array();
4269
-        foreach ($values as $value) {
4270
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4271
-        }
4272
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4273
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4274
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4275
-        if (empty($cleaned_values)) {
4276
-            $all_fields = $this->field_settings();
4277
-            $a_field = array_shift($all_fields);
4278
-            $main_table = $this->_get_main_table();
4279
-            $cleaned_values[] = "SELECT "
4280
-                                . $a_field->get_table_column()
4281
-                                . " FROM "
4282
-                                . $main_table->get_table_name()
4283
-                                . " WHERE FALSE";
4284
-        }
4285
-        return "(" . implode(",", $cleaned_values) . ")";
4286
-    }
4287
-
4288
-
4289
-
4290
-    /**
4291
-     * @param mixed                      $value
4292
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4293
-     * @throws EE_Error
4294
-     * @return false|null|string
4295
-     */
4296
-    private function _wpdb_prepare_using_field($value, $field_obj)
4297
-    {
4298
-        /** @type WPDB $wpdb */
4299
-        global $wpdb;
4300
-        if ($field_obj instanceof EE_Model_Field_Base) {
4301
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4302
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4303
-        } else {//$field_obj should really just be a data type
4304
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4305
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4306
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4307
-            }
4308
-            return $wpdb->prepare($field_obj, $value);
4309
-        }
4310
-    }
4311
-
4312
-
4313
-
4314
-    /**
4315
-     * Takes the input parameter and finds the model field that it indicates.
4316
-     *
4317
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4318
-     * @throws EE_Error
4319
-     * @return EE_Model_Field_Base
4320
-     */
4321
-    protected function _deduce_field_from_query_param($query_param_name)
4322
-    {
4323
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4324
-        //which will help us find the database table and column
4325
-        $query_param_parts = explode(".", $query_param_name);
4326
-        if (empty($query_param_parts)) {
4327
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4328
-                'event_espresso'), $query_param_name));
4329
-        }
4330
-        $number_of_parts = count($query_param_parts);
4331
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4332
-        if ($number_of_parts === 1) {
4333
-            $field_name = $last_query_param_part;
4334
-            $model_obj = $this;
4335
-        } else {// $number_of_parts >= 2
4336
-            //the last part is the column name, and there are only 2parts. therefore...
4337
-            $field_name = $last_query_param_part;
4338
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4339
-        }
4340
-        try {
4341
-            return $model_obj->field_settings_for($field_name);
4342
-        } catch (EE_Error $e) {
4343
-            return null;
4344
-        }
4345
-    }
4346
-
4347
-
4348
-
4349
-    /**
4350
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4351
-     * alias and column which corresponds to it
4352
-     *
4353
-     * @param string $field_name
4354
-     * @throws EE_Error
4355
-     * @return string
4356
-     */
4357
-    public function _get_qualified_column_for_field($field_name)
4358
-    {
4359
-        $all_fields = $this->field_settings();
4360
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4361
-        if ($field) {
4362
-            return $field->get_qualified_column();
4363
-        } else {
4364
-            throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4365
-                'event_espresso'), $field_name, get_class($this)));
4366
-        }
4367
-    }
4368
-
4369
-
4370
-
4371
-    /**
4372
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4373
-     * Example usage:
4374
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4375
-     *      array(),
4376
-     *      ARRAY_A,
4377
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4378
-     *  );
4379
-     * is equivalent to
4380
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4381
-     * and
4382
-     *  EEM_Event::instance()->get_all_wpdb_results(
4383
-     *      array(
4384
-     *          array(
4385
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4386
-     *          ),
4387
-     *          ARRAY_A,
4388
-     *          implode(
4389
-     *              ', ',
4390
-     *              array_merge(
4391
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4392
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4393
-     *              )
4394
-     *          )
4395
-     *      )
4396
-     *  );
4397
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4398
-     *
4399
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4400
-     *                                            and the one whose fields you are selecting for example: when querying
4401
-     *                                            tickets model and selecting fields from the tickets model you would
4402
-     *                                            leave this parameter empty, because no models are needed to join
4403
-     *                                            between the queried model and the selected one. Likewise when
4404
-     *                                            querying the datetime model and selecting fields from the tickets
4405
-     *                                            model, it would also be left empty, because there is a direct
4406
-     *                                            relation from datetimes to tickets, so no model is needed to join
4407
-     *                                            them together. However, when querying from the event model and
4408
-     *                                            selecting fields from the ticket model, you should provide the string
4409
-     *                                            'Datetime', indicating that the event model must first join to the
4410
-     *                                            datetime model in order to find its relation to ticket model.
4411
-     *                                            Also, when querying from the venue model and selecting fields from
4412
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4413
-     *                                            indicating you need to join the venue model to the event model,
4414
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4415
-     *                                            This string is used to deduce the prefix that gets added onto the
4416
-     *                                            models' tables qualified columns
4417
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4418
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4419
-     *                                            qualified column names
4420
-     * @return array|string
4421
-     */
4422
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4423
-    {
4424
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4425
-        $qualified_columns = array();
4426
-        foreach ($this->field_settings() as $field_name => $field) {
4427
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4428
-        }
4429
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4430
-    }
4431
-
4432
-
4433
-
4434
-    /**
4435
-     * constructs the select use on special limit joins
4436
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4437
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4438
-     * (as that is typically where the limits would be set).
4439
-     *
4440
-     * @param  string       $table_alias The table the select is being built for
4441
-     * @param  mixed|string $limit       The limit for this select
4442
-     * @return string                The final select join element for the query.
4443
-     */
4444
-    public function _construct_limit_join_select($table_alias, $limit)
4445
-    {
4446
-        $SQL = '';
4447
-        foreach ($this->_tables as $table_obj) {
4448
-            if ($table_obj instanceof EE_Primary_Table) {
4449
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4450
-                    ? $table_obj->get_select_join_limit($limit)
4451
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4452
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4453
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4454
-                    ? $table_obj->get_select_join_limit_join($limit)
4455
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4456
-            }
4457
-        }
4458
-        return $SQL;
4459
-    }
4460
-
4461
-
4462
-
4463
-    /**
4464
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4465
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4466
-     *
4467
-     * @return string SQL
4468
-     * @throws EE_Error
4469
-     */
4470
-    public function _construct_internal_join()
4471
-    {
4472
-        $SQL = $this->_get_main_table()->get_table_sql();
4473
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4474
-        return $SQL;
4475
-    }
4476
-
4477
-
4478
-
4479
-    /**
4480
-     * Constructs the SQL for joining all the tables on this model.
4481
-     * Normally $alias should be the primary table's alias, but in cases where
4482
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4483
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4484
-     * alias, this will construct SQL like:
4485
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4486
-     * With $alias being a secondary table's alias, this will construct SQL like:
4487
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4488
-     *
4489
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4490
-     * @return string
4491
-     */
4492
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4493
-    {
4494
-        $SQL = '';
4495
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4496
-        foreach ($this->_tables as $table_obj) {
4497
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4498
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4499
-                    //so we're joining to this table, meaning the table is already in
4500
-                    //the FROM statement, BUT the primary table isn't. So we want
4501
-                    //to add the inverse join sql
4502
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4503
-                } else {
4504
-                    //just add a regular JOIN to this table from the primary table
4505
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4506
-                }
4507
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4508
-        }
4509
-        return $SQL;
4510
-    }
4511
-
4512
-
4513
-
4514
-    /**
4515
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4516
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4517
-     * their data type (eg, '%s', '%d', etc)
4518
-     *
4519
-     * @return array
4520
-     */
4521
-    public function _get_data_types()
4522
-    {
4523
-        $data_types = array();
4524
-        foreach ($this->field_settings() as $field_obj) {
4525
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4526
-            /** @var $field_obj EE_Model_Field_Base */
4527
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4528
-        }
4529
-        return $data_types;
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4536
-     *
4537
-     * @param string $model_name
4538
-     * @throws EE_Error
4539
-     * @return EEM_Base
4540
-     */
4541
-    public function get_related_model_obj($model_name)
4542
-    {
4543
-        $model_classname = "EEM_" . $model_name;
4544
-        if (! class_exists($model_classname)) {
4545
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4546
-                'event_espresso'), $model_name, $model_classname));
4547
-        }
4548
-        return call_user_func($model_classname . "::instance");
4549
-    }
4550
-
4551
-
4552
-
4553
-    /**
4554
-     * Returns the array of EE_ModelRelations for this model.
4555
-     *
4556
-     * @return EE_Model_Relation_Base[]
4557
-     */
4558
-    public function relation_settings()
4559
-    {
4560
-        return $this->_model_relations;
4561
-    }
4562
-
4563
-
4564
-
4565
-    /**
4566
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4567
-     * because without THOSE models, this model probably doesn't have much purpose.
4568
-     * (Eg, without an event, datetimes have little purpose.)
4569
-     *
4570
-     * @return EE_Belongs_To_Relation[]
4571
-     */
4572
-    public function belongs_to_relations()
4573
-    {
4574
-        $belongs_to_relations = array();
4575
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4576
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4577
-                $belongs_to_relations[$model_name] = $relation_obj;
4578
-            }
4579
-        }
4580
-        return $belongs_to_relations;
4581
-    }
4582
-
4583
-
4584
-
4585
-    /**
4586
-     * Returns the specified EE_Model_Relation, or throws an exception
4587
-     *
4588
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4589
-     * @throws EE_Error
4590
-     * @return EE_Model_Relation_Base
4591
-     */
4592
-    public function related_settings_for($relation_name)
4593
-    {
4594
-        $relatedModels = $this->relation_settings();
4595
-        if (! array_key_exists($relation_name, $relatedModels)) {
4596
-            throw new EE_Error(
4597
-                sprintf(
4598
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4599
-                        'event_espresso'),
4600
-                    $relation_name,
4601
-                    $this->_get_class_name(),
4602
-                    implode(', ', array_keys($relatedModels))
4603
-                )
4604
-            );
4605
-        }
4606
-        return $relatedModels[$relation_name];
4607
-    }
4608
-
4609
-
4610
-
4611
-    /**
4612
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4613
-     * fields
4614
-     *
4615
-     * @param string $fieldName
4616
-     * @throws EE_Error
4617
-     * @return EE_Model_Field_Base
4618
-     */
4619
-    public function field_settings_for($fieldName)
4620
-    {
4621
-        $fieldSettings = $this->field_settings(true);
4622
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4623
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4624
-                get_class($this)));
4625
-        }
4626
-        return $fieldSettings[$fieldName];
4627
-    }
4628
-
4629
-
4630
-
4631
-    /**
4632
-     * Checks if this field exists on this model
4633
-     *
4634
-     * @param string $fieldName a key in the model's _field_settings array
4635
-     * @return boolean
4636
-     */
4637
-    public function has_field($fieldName)
4638
-    {
4639
-        $fieldSettings = $this->field_settings(true);
4640
-        if (isset($fieldSettings[$fieldName])) {
4641
-            return true;
4642
-        } else {
4643
-            return false;
4644
-        }
4645
-    }
4646
-
4647
-
4648
-
4649
-    /**
4650
-     * Returns whether or not this model has a relation to the specified model
4651
-     *
4652
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4653
-     * @return boolean
4654
-     */
4655
-    public function has_relation($relation_name)
4656
-    {
4657
-        $relations = $this->relation_settings();
4658
-        if (isset($relations[$relation_name])) {
4659
-            return true;
4660
-        } else {
4661
-            return false;
4662
-        }
4663
-    }
4664
-
4665
-
4666
-
4667
-    /**
4668
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4669
-     * Eg, on EE_Answer that would be ANS_ID field object
4670
-     *
4671
-     * @param $field_obj
4672
-     * @return boolean
4673
-     */
4674
-    public function is_primary_key_field($field_obj)
4675
-    {
4676
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4677
-    }
4678
-
4679
-
4680
-
4681
-    /**
4682
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4683
-     * Eg, on EE_Answer that would be ANS_ID field object
4684
-     *
4685
-     * @return EE_Model_Field_Base
4686
-     * @throws EE_Error
4687
-     */
4688
-    public function get_primary_key_field()
4689
-    {
4690
-        if ($this->_primary_key_field === null) {
4691
-            foreach ($this->field_settings(true) as $field_obj) {
4692
-                if ($this->is_primary_key_field($field_obj)) {
4693
-                    $this->_primary_key_field = $field_obj;
4694
-                    break;
4695
-                }
4696
-            }
4697
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4698
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4699
-                    get_class($this)));
4700
-            }
4701
-        }
4702
-        return $this->_primary_key_field;
4703
-    }
4704
-
4705
-
4706
-
4707
-    /**
4708
-     * Returns whether or not not there is a primary key on this model.
4709
-     * Internally does some caching.
4710
-     *
4711
-     * @return boolean
4712
-     */
4713
-    public function has_primary_key_field()
4714
-    {
4715
-        if ($this->_has_primary_key_field === null) {
4716
-            try {
4717
-                $this->get_primary_key_field();
4718
-                $this->_has_primary_key_field = true;
4719
-            } catch (EE_Error $e) {
4720
-                $this->_has_primary_key_field = false;
4721
-            }
4722
-        }
4723
-        return $this->_has_primary_key_field;
4724
-    }
4725
-
4726
-
4727
-
4728
-    /**
4729
-     * Finds the first field of type $field_class_name.
4730
-     *
4731
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4732
-     *                                 EE_Foreign_Key_Field, etc
4733
-     * @return EE_Model_Field_Base or null if none is found
4734
-     */
4735
-    public function get_a_field_of_type($field_class_name)
4736
-    {
4737
-        foreach ($this->field_settings() as $field) {
4738
-            if ($field instanceof $field_class_name) {
4739
-                return $field;
4740
-            }
4741
-        }
4742
-        return null;
4743
-    }
4744
-
4745
-
4746
-
4747
-    /**
4748
-     * Gets a foreign key field pointing to model.
4749
-     *
4750
-     * @param string $model_name eg Event, Registration, not EEM_Event
4751
-     * @return EE_Foreign_Key_Field_Base
4752
-     * @throws EE_Error
4753
-     */
4754
-    public function get_foreign_key_to($model_name)
4755
-    {
4756
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4757
-            foreach ($this->field_settings() as $field) {
4758
-                if (
4759
-                    $field instanceof EE_Foreign_Key_Field_Base
4760
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4761
-                ) {
4762
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4763
-                    break;
4764
-                }
4765
-            }
4766
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4767
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4768
-                    'event_espresso'), $model_name, get_class($this)));
4769
-            }
4770
-        }
4771
-        return $this->_cache_foreign_key_to_fields[$model_name];
4772
-    }
4773
-
4774
-
4775
-
4776
-    /**
4777
-     * Gets the table name (including $wpdb->prefix) for the table alias
4778
-     *
4779
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4780
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4781
-     *                            Either one works
4782
-     * @return string
4783
-     */
4784
-    public function get_table_for_alias($table_alias)
4785
-    {
4786
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4787
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4788
-    }
4789
-
4790
-
4791
-
4792
-    /**
4793
-     * Returns a flat array of all field son this model, instead of organizing them
4794
-     * by table_alias as they are in the constructor.
4795
-     *
4796
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4797
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4798
-     */
4799
-    public function field_settings($include_db_only_fields = false)
4800
-    {
4801
-        if ($include_db_only_fields) {
4802
-            if ($this->_cached_fields === null) {
4803
-                $this->_cached_fields = array();
4804
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4805
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4806
-                        $this->_cached_fields[$field_name] = $field_obj;
4807
-                    }
4808
-                }
4809
-            }
4810
-            return $this->_cached_fields;
4811
-        } else {
4812
-            if ($this->_cached_fields_non_db_only === null) {
4813
-                $this->_cached_fields_non_db_only = array();
4814
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4815
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4816
-                        /** @var $field_obj EE_Model_Field_Base */
4817
-                        if (! $field_obj->is_db_only_field()) {
4818
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4819
-                        }
4820
-                    }
4821
-                }
4822
-            }
4823
-            return $this->_cached_fields_non_db_only;
4824
-        }
4825
-    }
4826
-
4827
-
4828
-
4829
-    /**
4830
-     *        cycle though array of attendees and create objects out of each item
4831
-     *
4832
-     * @access        private
4833
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4834
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4835
-     *                           numerically indexed)
4836
-     * @throws EE_Error
4837
-     */
4838
-    protected function _create_objects($rows = array())
4839
-    {
4840
-        $array_of_objects = array();
4841
-        if (empty($rows)) {
4842
-            return array();
4843
-        }
4844
-        $count_if_model_has_no_primary_key = 0;
4845
-        $has_primary_key = $this->has_primary_key_field();
4846
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4847
-        foreach ((array)$rows as $row) {
4848
-            if (empty($row)) {
4849
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4850
-                return array();
4851
-            }
4852
-            //check if we've already set this object in the results array,
4853
-            //in which case there's no need to process it further (again)
4854
-            if ($has_primary_key) {
4855
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4856
-                    $row,
4857
-                    $primary_key_field->get_qualified_column(),
4858
-                    $primary_key_field->get_table_column()
4859
-                );
4860
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4861
-                    continue;
4862
-                }
4863
-            }
4864
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4865
-            if (! $classInstance) {
4866
-                throw new EE_Error(
4867
-                    sprintf(
4868
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4869
-                        $this->get_this_model_name(),
4870
-                        http_build_query($row)
4871
-                    )
4872
-                );
4873
-            }
4874
-            //set the timezone on the instantiated objects
4875
-            $classInstance->set_timezone($this->_timezone);
4876
-            //make sure if there is any timezone setting present that we set the timezone for the object
4877
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4878
-            $array_of_objects[$key] = $classInstance;
4879
-            //also, for all the relations of type BelongsTo, see if we can cache
4880
-            //those related models
4881
-            //(we could do this for other relations too, but if there are conditions
4882
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4883
-            //so it requires a little more thought than just caching them immediately...)
4884
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4885
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4886
-                    //check if this model's INFO is present. If so, cache it on the model
4887
-                    $other_model = $relation_obj->get_other_model();
4888
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4889
-                    //if we managed to make a model object from the results, cache it on the main model object
4890
-                    if ($other_model_obj_maybe) {
4891
-                        //set timezone on these other model objects if they are present
4892
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4893
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4894
-                    }
4895
-                }
4896
-            }
4897
-        }
4898
-        return $array_of_objects;
4899
-    }
4900
-
4901
-
4902
-
4903
-    /**
4904
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4905
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4906
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4907
-     * object (as set in the model_field!).
4908
-     *
4909
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4910
-     * @throws Exception
4911
-     */
4912
-    public function create_default_object()
4913
-    {
4914
-        $this_model_fields_and_values = array();
4915
-        //setup the row using default values;
4916
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4917
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4918
-        }
4919
-        $classInstance = $this->_instantiate_new_instance_from_db(
4920
-            $this->_get_class_name(),
4921
-            $this_model_fields_and_values
4922
-        );
4923
-        return $classInstance;
4924
-    }
4925
-
4926
-
4927
-
4928
-    /**
4929
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4930
-     *                             or an stdClass where each property is the name of a column,
4931
-     * @return EE_Base_Class
4932
-     * @throws Exception
4933
-     * @throws EE_Error
4934
-     */
4935
-    public function instantiate_class_from_array_or_object($cols_n_values)
4936
-    {
4937
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4938
-            $cols_n_values = get_object_vars($cols_n_values);
4939
-        }
4940
-        $primary_key = null;
4941
-        //make sure the array only has keys that are fields/columns on this model
4942
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4943
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4944
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4945
-        }
4946
-        //check we actually found results that we can use to build our model object
4947
-        //if not, return null
4948
-        if ($this->has_primary_key_field()) {
4949
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4950
-                return null;
4951
-            }
4952
-        } else if ($this->unique_indexes()) {
4953
-            $first_column = reset($this_model_fields_n_values);
4954
-            if (empty($first_column)) {
4955
-                return null;
4956
-            }
4957
-        }
4958
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4959
-        if ($primary_key) {
4960
-            $classInstance = $this->get_from_entity_map($primary_key);
4961
-            if (! $classInstance) {
4962
-                $classInstance = $this->_instantiate_new_instance_from_db(
4963
-                    $this->_get_class_name(),
4964
-                    $this_model_fields_n_values
4965
-                );
4966
-                // add this new object to the entity map
4967
-                $classInstance = $this->add_to_entity_map($classInstance);
4968
-            }
4969
-        } else {
4970
-            $classInstance = $this->_instantiate_new_instance_from_db(
4971
-                $this->_get_class_name(),
4972
-                $this_model_fields_n_values
4973
-            );
4974
-        }
4975
-        // it is entirely possible that the instantiated class object has a set
4976
-        // timezone_string db field and has set it's internal _timezone property accordingly
4977
-        // (see new_instance_from_db in model objects particularly EE_Event for example).
4978
-        // In this case, we want to make sure the model object doesn't have its timezone string
4979
-        // overwritten by any timezone property currently set here on the model so,
4980
-        // we intentionally override the model _timezone property with the model_object timezone property.
4981
-        $this->set_timezone($classInstance->get_timezone());
4982
-        return $classInstance;
4983
-    }
4984
-
4985
-
4986
-
4987
-    /**
4988
-     * Gets the model object from the  entity map if it exists
4989
-     *
4990
-     * @param int|string $id the ID of the model object
4991
-     * @return EE_Base_Class
4992
-     */
4993
-    public function get_from_entity_map($id)
4994
-    {
4995
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4996
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4997
-    }
4998
-
4999
-
5000
-
5001
-    /**
5002
-     * add_to_entity_map
5003
-     * Adds the object to the model's entity mappings
5004
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5005
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5006
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5007
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5008
-     *        then this method should be called immediately after the update query
5009
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5010
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5011
-     *
5012
-     * @param    EE_Base_Class $object
5013
-     * @throws EE_Error
5014
-     * @return \EE_Base_Class
5015
-     */
5016
-    public function add_to_entity_map(EE_Base_Class $object)
5017
-    {
5018
-        $className = $this->_get_class_name();
5019
-        if (! $object instanceof $className) {
5020
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5021
-                is_object($object) ? get_class($object) : $object, $className));
5022
-        }
5023
-        /** @var $object EE_Base_Class */
5024
-        if (! $object->ID()) {
5025
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5026
-                "event_espresso"), get_class($this)));
5027
-        }
5028
-        // double check it's not already there
5029
-        $classInstance = $this->get_from_entity_map($object->ID());
5030
-        if ($classInstance) {
5031
-            return $classInstance;
5032
-        } else {
5033
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5034
-            return $object;
5035
-        }
5036
-    }
5037
-
5038
-
5039
-
5040
-    /**
5041
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5042
-     * if no identifier is provided, then the entire entity map is emptied
5043
-     *
5044
-     * @param int|string $id the ID of the model object
5045
-     * @return boolean
5046
-     */
5047
-    public function clear_entity_map($id = null)
5048
-    {
5049
-        if (empty($id)) {
5050
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5051
-            return true;
5052
-        }
5053
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5054
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5055
-            return true;
5056
-        }
5057
-        return false;
5058
-    }
5059
-
5060
-
5061
-
5062
-    /**
5063
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5064
-     * Given an array where keys are column (or column alias) names and values,
5065
-     * returns an array of their corresponding field names and database values
5066
-     *
5067
-     * @param array $cols_n_values
5068
-     * @return array
5069
-     */
5070
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5071
-    {
5072
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5073
-    }
5074
-
5075
-
5076
-
5077
-    /**
5078
-     * _deduce_fields_n_values_from_cols_n_values
5079
-     * Given an array where keys are column (or column alias) names and values,
5080
-     * returns an array of their corresponding field names and database values
5081
-     *
5082
-     * @param string $cols_n_values
5083
-     * @return array
5084
-     */
5085
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5086
-    {
5087
-        $this_model_fields_n_values = array();
5088
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5089
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5090
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5091
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5092
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5093
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5094
-                    if (! $field_obj->is_db_only_field()) {
5095
-                        //prepare field as if its coming from db
5096
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5097
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5098
-                    }
5099
-                }
5100
-            } else {
5101
-                //the table's rows existed. Use their values
5102
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5103
-                    if (! $field_obj->is_db_only_field()) {
5104
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5105
-                            $cols_n_values, $field_obj->get_qualified_column(),
5106
-                            $field_obj->get_table_column()
5107
-                        );
5108
-                    }
5109
-                }
5110
-            }
5111
-        }
5112
-        return $this_model_fields_n_values;
5113
-    }
5114
-
5115
-
5116
-
5117
-    /**
5118
-     * @param $cols_n_values
5119
-     * @param $qualified_column
5120
-     * @param $regular_column
5121
-     * @return null
5122
-     */
5123
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5124
-    {
5125
-        $value = null;
5126
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5127
-        //does the field on the model relate to this column retrieved from the db?
5128
-        //or is it a db-only field? (not relating to the model)
5129
-        if (isset($cols_n_values[$qualified_column])) {
5130
-            $value = $cols_n_values[$qualified_column];
5131
-        } elseif (isset($cols_n_values[$regular_column])) {
5132
-            $value = $cols_n_values[$regular_column];
5133
-        }
5134
-        return $value;
5135
-    }
5136
-
5137
-
5138
-
5139
-    /**
5140
-     * refresh_entity_map_from_db
5141
-     * Makes sure the model object in the entity map at $id assumes the values
5142
-     * of the database (opposite of EE_base_Class::save())
5143
-     *
5144
-     * @param int|string $id
5145
-     * @return EE_Base_Class
5146
-     * @throws EE_Error
5147
-     */
5148
-    public function refresh_entity_map_from_db($id)
5149
-    {
5150
-        $obj_in_map = $this->get_from_entity_map($id);
5151
-        if ($obj_in_map) {
5152
-            $wpdb_results = $this->_get_all_wpdb_results(
5153
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5154
-            );
5155
-            if ($wpdb_results && is_array($wpdb_results)) {
5156
-                $one_row = reset($wpdb_results);
5157
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5158
-                    $obj_in_map->set_from_db($field_name, $db_value);
5159
-                }
5160
-                //clear the cache of related model objects
5161
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5162
-                    $obj_in_map->clear_cache($relation_name, null, true);
5163
-                }
5164
-            }
5165
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5166
-            return $obj_in_map;
5167
-        } else {
5168
-            return $this->get_one_by_ID($id);
5169
-        }
5170
-    }
5171
-
5172
-
5173
-
5174
-    /**
5175
-     * refresh_entity_map_with
5176
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5177
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5178
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5179
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5180
-     *
5181
-     * @param int|string    $id
5182
-     * @param EE_Base_Class $replacing_model_obj
5183
-     * @return \EE_Base_Class
5184
-     * @throws EE_Error
5185
-     */
5186
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5187
-    {
5188
-        $obj_in_map = $this->get_from_entity_map($id);
5189
-        if ($obj_in_map) {
5190
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5191
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5192
-                    $obj_in_map->set($field_name, $value);
5193
-                }
5194
-                //make the model object in the entity map's cache match the $replacing_model_obj
5195
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5196
-                    $obj_in_map->clear_cache($relation_name, null, true);
5197
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5198
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5199
-                    }
5200
-                }
5201
-            }
5202
-            return $obj_in_map;
5203
-        } else {
5204
-            $this->add_to_entity_map($replacing_model_obj);
5205
-            return $replacing_model_obj;
5206
-        }
5207
-    }
5208
-
5209
-
5210
-
5211
-    /**
5212
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5213
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5214
-     * require_once($this->_getClassName().".class.php");
5215
-     *
5216
-     * @return string
5217
-     */
5218
-    private function _get_class_name()
5219
-    {
5220
-        return "EE_" . $this->get_this_model_name();
5221
-    }
5222
-
5223
-
5224
-
5225
-    /**
5226
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5227
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5228
-     * it would be 'Events'.
5229
-     *
5230
-     * @param int $quantity
5231
-     * @return string
5232
-     */
5233
-    public function item_name($quantity = 1)
5234
-    {
5235
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5236
-    }
5237
-
5238
-
5239
-
5240
-    /**
5241
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5242
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5243
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5244
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5245
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5246
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5247
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5248
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5249
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5250
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5251
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5252
-     *        return $previousReturnValue.$returnString;
5253
-     * }
5254
-     * require('EEM_Answer.model.php');
5255
-     * $answer=EEM_Answer::instance();
5256
-     * echo $answer->my_callback('monkeys',100);
5257
-     * //will output "you called my_callback! and passed args:monkeys,100"
5258
-     *
5259
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5260
-     * @param array  $args       array of original arguments passed to the function
5261
-     * @throws EE_Error
5262
-     * @return mixed whatever the plugin which calls add_filter decides
5263
-     */
5264
-    public function __call($methodName, $args)
5265
-    {
5266
-        $className = get_class($this);
5267
-        $tagName = "FHEE__{$className}__{$methodName}";
5268
-        if (! has_filter($tagName)) {
5269
-            throw new EE_Error(
5270
-                sprintf(
5271
-                    __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5272
-                        'event_espresso'),
5273
-                    $methodName,
5274
-                    $className,
5275
-                    $tagName,
5276
-                    '<br />'
5277
-                )
5278
-            );
5279
-        }
5280
-        return apply_filters($tagName, null, $this, $args);
5281
-    }
5282
-
5283
-
5284
-
5285
-    /**
5286
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5287
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5288
-     *
5289
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5290
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5291
-     *                                                       the object's class name
5292
-     *                                                       or object's ID
5293
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5294
-     *                                                       exists in the database. If it does not, we add it
5295
-     * @throws EE_Error
5296
-     * @return EE_Base_Class
5297
-     */
5298
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5299
-    {
5300
-        $className = $this->_get_class_name();
5301
-        if ($base_class_obj_or_id instanceof $className) {
5302
-            $model_object = $base_class_obj_or_id;
5303
-        } else {
5304
-            $primary_key_field = $this->get_primary_key_field();
5305
-            if (
5306
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5307
-                && (
5308
-                    is_int($base_class_obj_or_id)
5309
-                    || is_string($base_class_obj_or_id)
5310
-                )
5311
-            ) {
5312
-                // assume it's an ID.
5313
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5314
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5315
-            } else if (
5316
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5317
-                && is_string($base_class_obj_or_id)
5318
-            ) {
5319
-                // assume its a string representation of the object
5320
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5321
-            } else {
5322
-                throw new EE_Error(
5323
-                    sprintf(
5324
-                        __(
5325
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5326
-                            'event_espresso'
5327
-                        ),
5328
-                        $base_class_obj_or_id,
5329
-                        $this->_get_class_name(),
5330
-                        print_r($base_class_obj_or_id, true)
5331
-                    )
5332
-                );
5333
-            }
5334
-        }
5335
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5336
-            $model_object->save();
5337
-        }
5338
-        return $model_object;
5339
-    }
5340
-
5341
-
5342
-
5343
-    /**
5344
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5345
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5346
-     * returns it ID.
5347
-     *
5348
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5349
-     * @return int|string depending on the type of this model object's ID
5350
-     * @throws EE_Error
5351
-     */
5352
-    public function ensure_is_ID($base_class_obj_or_id)
5353
-    {
5354
-        $className = $this->_get_class_name();
5355
-        if ($base_class_obj_or_id instanceof $className) {
5356
-            /** @var $base_class_obj_or_id EE_Base_Class */
5357
-            $id = $base_class_obj_or_id->ID();
5358
-        } elseif (is_int($base_class_obj_or_id)) {
5359
-            //assume it's an ID
5360
-            $id = $base_class_obj_or_id;
5361
-        } elseif (is_string($base_class_obj_or_id)) {
5362
-            //assume its a string representation of the object
5363
-            $id = $base_class_obj_or_id;
5364
-        } else {
5365
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5366
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5367
-                print_r($base_class_obj_or_id, true)));
5368
-        }
5369
-        return $id;
5370
-    }
5371
-
5372
-
5373
-
5374
-    /**
5375
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5376
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5377
-     * been sanitized and converted into the appropriate domain.
5378
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5379
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5380
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5381
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5382
-     * $EVT = EEM_Event::instance(); $old_setting =
5383
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5384
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5385
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5386
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5387
-     *
5388
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5389
-     * @return void
5390
-     */
5391
-    public function assume_values_already_prepared_by_model_object(
5392
-        $values_already_prepared = self::not_prepared_by_model_object
5393
-    ) {
5394
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5395
-    }
5396
-
5397
-
5398
-
5399
-    /**
5400
-     * Read comments for assume_values_already_prepared_by_model_object()
5401
-     *
5402
-     * @return int
5403
-     */
5404
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5405
-    {
5406
-        return $this->_values_already_prepared_by_model_object;
5407
-    }
5408
-
5409
-
5410
-
5411
-    /**
5412
-     * Gets all the indexes on this model
5413
-     *
5414
-     * @return EE_Index[]
5415
-     */
5416
-    public function indexes()
5417
-    {
5418
-        return $this->_indexes;
5419
-    }
5420
-
5421
-
5422
-
5423
-    /**
5424
-     * Gets all the Unique Indexes on this model
5425
-     *
5426
-     * @return EE_Unique_Index[]
5427
-     */
5428
-    public function unique_indexes()
5429
-    {
5430
-        $unique_indexes = array();
5431
-        foreach ($this->_indexes as $name => $index) {
5432
-            if ($index instanceof EE_Unique_Index) {
5433
-                $unique_indexes [$name] = $index;
5434
-            }
5435
-        }
5436
-        return $unique_indexes;
5437
-    }
5438
-
5439
-
5440
-
5441
-    /**
5442
-     * Gets all the fields which, when combined, make the primary key.
5443
-     * This is usually just an array with 1 element (the primary key), but in cases
5444
-     * where there is no primary key, it's a combination of fields as defined
5445
-     * on a primary index
5446
-     *
5447
-     * @return EE_Model_Field_Base[] indexed by the field's name
5448
-     * @throws EE_Error
5449
-     */
5450
-    public function get_combined_primary_key_fields()
5451
-    {
5452
-        foreach ($this->indexes() as $index) {
5453
-            if ($index instanceof EE_Primary_Key_Index) {
5454
-                return $index->fields();
5455
-            }
5456
-        }
5457
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5458
-    }
5459
-
5460
-
5461
-
5462
-    /**
5463
-     * Used to build a primary key string (when the model has no primary key),
5464
-     * which can be used a unique string to identify this model object.
5465
-     *
5466
-     * @param array $cols_n_values keys are field names, values are their values
5467
-     * @return string
5468
-     * @throws EE_Error
5469
-     */
5470
-    public function get_index_primary_key_string($cols_n_values)
5471
-    {
5472
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5473
-            $this->get_combined_primary_key_fields());
5474
-        return http_build_query($cols_n_values_for_primary_key_index);
5475
-    }
5476
-
5477
-
5478
-
5479
-    /**
5480
-     * Gets the field values from the primary key string
5481
-     *
5482
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5483
-     * @param string $index_primary_key_string
5484
-     * @return null|array
5485
-     * @throws EE_Error
5486
-     */
5487
-    public function parse_index_primary_key_string($index_primary_key_string)
5488
-    {
5489
-        $key_fields = $this->get_combined_primary_key_fields();
5490
-        //check all of them are in the $id
5491
-        $key_vals_in_combined_pk = array();
5492
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5493
-        foreach ($key_fields as $key_field_name => $field_obj) {
5494
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5495
-                return null;
5496
-            }
5497
-        }
5498
-        return $key_vals_in_combined_pk;
5499
-    }
5500
-
5501
-
5502
-
5503
-    /**
5504
-     * verifies that an array of key-value pairs for model fields has a key
5505
-     * for each field comprising the primary key index
5506
-     *
5507
-     * @param array $key_vals
5508
-     * @return boolean
5509
-     * @throws EE_Error
5510
-     */
5511
-    public function has_all_combined_primary_key_fields($key_vals)
5512
-    {
5513
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5514
-        foreach ($keys_it_should_have as $key) {
5515
-            if (! isset($key_vals[$key])) {
5516
-                return false;
5517
-            }
5518
-        }
5519
-        return true;
5520
-    }
5521
-
5522
-
5523
-
5524
-    /**
5525
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5526
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5527
-     *
5528
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5529
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5530
-     * @throws EE_Error
5531
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5532
-     *                                                              indexed)
5533
-     */
5534
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5535
-    {
5536
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5537
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5538
-        } elseif (is_array($model_object_or_attributes_array)) {
5539
-            $attributes_array = $model_object_or_attributes_array;
5540
-        } else {
5541
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5542
-                "event_espresso"), $model_object_or_attributes_array));
5543
-        }
5544
-        //even copies obviously won't have the same ID, so remove the primary key
5545
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5546
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5547
-            unset($attributes_array[$this->primary_key_name()]);
5548
-        }
5549
-        if (isset($query_params[0])) {
5550
-            $query_params[0] = array_merge($attributes_array, $query_params);
5551
-        } else {
5552
-            $query_params[0] = $attributes_array;
5553
-        }
5554
-        return $this->get_all($query_params);
5555
-    }
5556
-
5557
-
5558
-
5559
-    /**
5560
-     * Gets the first copy we find. See get_all_copies for more details
5561
-     *
5562
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5563
-     * @param array $query_params
5564
-     * @return EE_Base_Class
5565
-     * @throws EE_Error
5566
-     */
5567
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5568
-    {
5569
-        if (! is_array($query_params)) {
5570
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5571
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5572
-                    gettype($query_params)), '4.6.0');
5573
-            $query_params = array();
5574
-        }
5575
-        $query_params['limit'] = 1;
5576
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5577
-        if (is_array($copies)) {
5578
-            return array_shift($copies);
5579
-        } else {
5580
-            return null;
5581
-        }
5582
-    }
5583
-
5584
-
5585
-
5586
-    /**
5587
-     * Updates the item with the specified id. Ignores default query parameters because
5588
-     * we have specified the ID, and its assumed we KNOW what we're doing
5589
-     *
5590
-     * @param array      $fields_n_values keys are field names, values are their new values
5591
-     * @param int|string $id              the value of the primary key to update
5592
-     * @return int number of rows updated
5593
-     * @throws EE_Error
5594
-     */
5595
-    public function update_by_ID($fields_n_values, $id)
5596
-    {
5597
-        $query_params = array(
5598
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5599
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5600
-        );
5601
-        return $this->update($fields_n_values, $query_params);
5602
-    }
5603
-
5604
-
5605
-
5606
-    /**
5607
-     * Changes an operator which was supplied to the models into one usable in SQL
5608
-     *
5609
-     * @param string $operator_supplied
5610
-     * @return string an operator which can be used in SQL
5611
-     * @throws EE_Error
5612
-     */
5613
-    private function _prepare_operator_for_sql($operator_supplied)
5614
-    {
5615
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5616
-            : null;
5617
-        if ($sql_operator) {
5618
-            return $sql_operator;
5619
-        } else {
5620
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5621
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5622
-        }
5623
-    }
5624
-
5625
-
5626
-
5627
-    /**
5628
-     * Gets an array where keys are the primary keys and values are their 'names'
5629
-     * (as determined by the model object's name() function, which is often overridden)
5630
-     *
5631
-     * @param array $query_params like get_all's
5632
-     * @return string[]
5633
-     * @throws EE_Error
5634
-     */
5635
-    public function get_all_names($query_params = array())
5636
-    {
5637
-        $objs = $this->get_all($query_params);
5638
-        $names = array();
5639
-        foreach ($objs as $obj) {
5640
-            $names[$obj->ID()] = $obj->name();
5641
-        }
5642
-        return $names;
5643
-    }
5644
-
5645
-
5646
-
5647
-    /**
5648
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5649
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5650
-     * this is duplicated effort and reduces efficiency) you would be better to use
5651
-     * array_keys() on $model_objects.
5652
-     *
5653
-     * @param \EE_Base_Class[] $model_objects
5654
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5655
-     *                                               in the returned array
5656
-     * @return array
5657
-     * @throws EE_Error
5658
-     */
5659
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5660
-    {
5661
-        if (! $this->has_primary_key_field()) {
5662
-            if (WP_DEBUG) {
5663
-                EE_Error::add_error(
5664
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5665
-                    __FILE__,
5666
-                    __FUNCTION__,
5667
-                    __LINE__
5668
-                );
5669
-            }
5670
-        }
5671
-        $IDs = array();
5672
-        foreach ($model_objects as $model_object) {
5673
-            $id = $model_object->ID();
5674
-            if (! $id) {
5675
-                if ($filter_out_empty_ids) {
5676
-                    continue;
5677
-                }
5678
-                if (WP_DEBUG) {
5679
-                    EE_Error::add_error(
5680
-                        __(
5681
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5682
-                            'event_espresso'
5683
-                        ),
5684
-                        __FILE__,
5685
-                        __FUNCTION__,
5686
-                        __LINE__
5687
-                    );
5688
-                }
5689
-            }
5690
-            $IDs[] = $id;
5691
-        }
5692
-        return $IDs;
5693
-    }
5694
-
5695
-
5696
-
5697
-    /**
5698
-     * Returns the string used in capabilities relating to this model. If there
5699
-     * are no capabilities that relate to this model returns false
5700
-     *
5701
-     * @return string|false
5702
-     */
5703
-    public function cap_slug()
5704
-    {
5705
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5706
-    }
5707
-
5708
-
5709
-
5710
-    /**
5711
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5712
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5713
-     * only returns the cap restrictions array in that context (ie, the array
5714
-     * at that key)
5715
-     *
5716
-     * @param string $context
5717
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5718
-     * @throws EE_Error
5719
-     */
5720
-    public function cap_restrictions($context = EEM_Base::caps_read)
5721
-    {
5722
-        EEM_Base::verify_is_valid_cap_context($context);
5723
-        //check if we ought to run the restriction generator first
5724
-        if (
5725
-            isset($this->_cap_restriction_generators[$context])
5726
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5727
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5728
-        ) {
5729
-            $this->_cap_restrictions[$context] = array_merge(
5730
-                $this->_cap_restrictions[$context],
5731
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5732
-            );
5733
-        }
5734
-        //and make sure we've finalized the construction of each restriction
5735
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5736
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5737
-                $where_conditions_obj->_finalize_construct($this);
5738
-            }
5739
-        }
5740
-        return $this->_cap_restrictions[$context];
5741
-    }
5742
-
5743
-
5744
-
5745
-    /**
5746
-     * Indicating whether or not this model thinks its a wp core model
5747
-     *
5748
-     * @return boolean
5749
-     */
5750
-    public function is_wp_core_model()
5751
-    {
5752
-        return $this->_wp_core_model;
5753
-    }
5754
-
5755
-
5756
-
5757
-    /**
5758
-     * Gets all the caps that are missing which impose a restriction on
5759
-     * queries made in this context
5760
-     *
5761
-     * @param string $context one of EEM_Base::caps_ constants
5762
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5763
-     * @throws EE_Error
5764
-     */
5765
-    public function caps_missing($context = EEM_Base::caps_read)
5766
-    {
5767
-        $missing_caps = array();
5768
-        $cap_restrictions = $this->cap_restrictions($context);
5769
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5770
-            if (! EE_Capabilities::instance()
5771
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5772
-            ) {
5773
-                $missing_caps[$cap] = $restriction_if_no_cap;
5774
-            }
5775
-        }
5776
-        return $missing_caps;
5777
-    }
5778
-
5779
-
5780
-
5781
-    /**
5782
-     * Gets the mapping from capability contexts to action strings used in capability names
5783
-     *
5784
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5785
-     * one of 'read', 'edit', or 'delete'
5786
-     */
5787
-    public function cap_contexts_to_cap_action_map()
5788
-    {
5789
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5790
-            $this);
5791
-    }
5792
-
5793
-
5794
-
5795
-    /**
5796
-     * Gets the action string for the specified capability context
5797
-     *
5798
-     * @param string $context
5799
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5800
-     * @throws EE_Error
5801
-     */
5802
-    public function cap_action_for_context($context)
5803
-    {
5804
-        $mapping = $this->cap_contexts_to_cap_action_map();
5805
-        if (isset($mapping[$context])) {
5806
-            return $mapping[$context];
5807
-        }
5808
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5809
-            return $action;
5810
-        }
5811
-        throw new EE_Error(
5812
-            sprintf(
5813
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5814
-                $context,
5815
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5816
-            )
5817
-        );
5818
-    }
5819
-
5820
-
5821
-
5822
-    /**
5823
-     * Returns all the capability contexts which are valid when querying models
5824
-     *
5825
-     * @return array
5826
-     */
5827
-    public static function valid_cap_contexts()
5828
-    {
5829
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5830
-            self::caps_read,
5831
-            self::caps_read_admin,
5832
-            self::caps_edit,
5833
-            self::caps_delete,
5834
-        ));
5835
-    }
5836
-
5837
-
5838
-
5839
-    /**
5840
-     * Returns all valid options for 'default_where_conditions'
5841
-     *
5842
-     * @return array
5843
-     */
5844
-    public static function valid_default_where_conditions()
5845
-    {
5846
-        return array(
5847
-            EEM_Base::default_where_conditions_all,
5848
-            EEM_Base::default_where_conditions_this_only,
5849
-            EEM_Base::default_where_conditions_others_only,
5850
-            EEM_Base::default_where_conditions_minimum_all,
5851
-            EEM_Base::default_where_conditions_minimum_others,
5852
-            EEM_Base::default_where_conditions_none
5853
-        );
5854
-    }
5855
-
5856
-    // public static function default_where_conditions_full
5857
-    /**
5858
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5859
-     *
5860
-     * @param string $context
5861
-     * @return bool
5862
-     * @throws EE_Error
5863
-     */
5864
-    static public function verify_is_valid_cap_context($context)
5865
-    {
5866
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5867
-        if (in_array($context, $valid_cap_contexts)) {
5868
-            return true;
5869
-        } else {
5870
-            throw new EE_Error(
5871
-                sprintf(
5872
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5873
-                        'event_espresso'),
5874
-                    $context,
5875
-                    'EEM_Base',
5876
-                    implode(',', $valid_cap_contexts)
5877
-                )
5878
-            );
5879
-        }
5880
-    }
5881
-
5882
-
5883
-
5884
-    /**
5885
-     * Clears all the models field caches. This is only useful when a sub-class
5886
-     * might have added a field or something and these caches might be invalidated
5887
-     */
5888
-    protected function _invalidate_field_caches()
5889
-    {
5890
-        $this->_cache_foreign_key_to_fields = array();
5891
-        $this->_cached_fields = null;
5892
-        $this->_cached_fields_non_db_only = null;
5893
-    }
5894
-
5895
-
5896
-
5897
-    /**
5898
-     * _instantiate_new_instance_from_db
5899
-     *
5900
-     * @param string $class_name
5901
-     * @param array  $arguments
5902
-     * @return \EE_Base_Class
5903
-     * @throws Exception
5904
-     */
5905
-    public function _instantiate_new_instance_from_db($class_name, $arguments)
5906
-    {
5907
-        if ( ! class_exists($class_name)) {
5908
-            throw new EE_Error(
5909
-                sprintf(
5910
-                    __('The "%s" class does not exist. Please ensure that an autoloader is set.', 'event_espresso'),
5911
-                    $class_name
5912
-                )
5913
-            );
5914
-        }
5915
-        return call_user_func_array(
5916
-            array($class_name, 'new_instance'),
5917
-            array((array)$arguments, $this->_timezone, array(), true)
5918
-        );
5919
-    }
5920
-
5921
-
5922
-    /**
5923
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5924
-     * (eg "and", "or", "not").
5925
-     *
5926
-     * @return array
5927
-     */
5928
-    public function logic_query_param_keys()
5929
-    {
5930
-        return $this->_logic_query_param_keys;
5931
-    }
5932
-
5933
-
5934
-
5935
-    /**
5936
-     * Determines whether or not the where query param array key is for a logic query param.
5937
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5938
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5939
-     *
5940
-     * @param $query_param_key
5941
-     * @return bool
5942
-     */
5943
-    public function is_logic_query_param_key($query_param_key)
5944
-    {
5945
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5946
-            if ($query_param_key === $logic_query_param_key
5947
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5948
-            ) {
5949
-                return true;
5950
-            }
5951
-        }
5952
-        return false;
5953
-    }
3679
+		}
3680
+		return $null_friendly_where_conditions;
3681
+	}
3682
+
3683
+
3684
+
3685
+	/**
3686
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3687
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3688
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3689
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3690
+	 *
3691
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3692
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3693
+	 */
3694
+	private function _get_default_where_conditions($model_relation_path = null)
3695
+	{
3696
+		if ($this->_ignore_where_strategy) {
3697
+			return array();
3698
+		}
3699
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3700
+	}
3701
+
3702
+
3703
+
3704
+	/**
3705
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3706
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3707
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3708
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3709
+	 * Similar to _get_default_where_conditions
3710
+	 *
3711
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3712
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3713
+	 */
3714
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3715
+	{
3716
+		if ($this->_ignore_where_strategy) {
3717
+			return array();
3718
+		}
3719
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3720
+	}
3721
+
3722
+
3723
+
3724
+	/**
3725
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3726
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3727
+	 *
3728
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3729
+	 * @return string
3730
+	 * @throws EE_Error
3731
+	 */
3732
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3733
+	{
3734
+		$selects = $this->_get_columns_to_select_for_this_model();
3735
+		foreach (
3736
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3737
+			$name_of_other_model_included
3738
+		) {
3739
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3740
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3741
+			foreach ($other_model_selects as $key => $value) {
3742
+				$selects[] = $value;
3743
+			}
3744
+		}
3745
+		return implode(", ", $selects);
3746
+	}
3747
+
3748
+
3749
+
3750
+	/**
3751
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3752
+	 * So that's going to be the columns for all the fields on the model
3753
+	 *
3754
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3755
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3756
+	 */
3757
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3758
+	{
3759
+		$fields = $this->field_settings();
3760
+		$selects = array();
3761
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3762
+			$this->get_this_model_name());
3763
+		foreach ($fields as $field_obj) {
3764
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3765
+						 . $field_obj->get_table_alias()
3766
+						 . "."
3767
+						 . $field_obj->get_table_column()
3768
+						 . " AS '"
3769
+						 . $table_alias_with_model_relation_chain_prefix
3770
+						 . $field_obj->get_table_alias()
3771
+						 . "."
3772
+						 . $field_obj->get_table_column()
3773
+						 . "'";
3774
+		}
3775
+		//make sure we are also getting the PKs of each table
3776
+		$tables = $this->get_tables();
3777
+		if (count($tables) > 1) {
3778
+			foreach ($tables as $table_obj) {
3779
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3780
+									   . $table_obj->get_fully_qualified_pk_column();
3781
+				if (! in_array($qualified_pk_column, $selects)) {
3782
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3783
+				}
3784
+			}
3785
+		}
3786
+		return $selects;
3787
+	}
3788
+
3789
+
3790
+
3791
+	/**
3792
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3793
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3794
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3795
+	 * SQL for joining, and the data types
3796
+	 *
3797
+	 * @param null|string                 $original_query_param
3798
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3799
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3800
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3801
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3802
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3803
+	 *                                                          or 'Registration's
3804
+	 * @param string                      $original_query_param what it originally was (eg
3805
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3806
+	 *                                                          matches $query_param
3807
+	 * @throws EE_Error
3808
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3809
+	 */
3810
+	private function _extract_related_model_info_from_query_param(
3811
+		$query_param,
3812
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3813
+		$query_param_type,
3814
+		$original_query_param = null
3815
+	) {
3816
+		if ($original_query_param === null) {
3817
+			$original_query_param = $query_param;
3818
+		}
3819
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3820
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3821
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3822
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3823
+		//check to see if we have a field on this model
3824
+		$this_model_fields = $this->field_settings(true);
3825
+		if (array_key_exists($query_param, $this_model_fields)) {
3826
+			if ($allow_fields) {
3827
+				return;
3828
+			} else {
3829
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3830
+					"event_espresso"),
3831
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3832
+			}
3833
+		} //check if this is a special logic query param
3834
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3835
+			if ($allow_logic_query_params) {
3836
+				return;
3837
+			} else {
3838
+				throw new EE_Error(
3839
+					sprintf(
3840
+						__('Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3841
+							'event_espresso'),
3842
+						implode('", "', $this->_logic_query_param_keys),
3843
+						$query_param,
3844
+						get_class($this),
3845
+						'<br />',
3846
+						"\t"
3847
+						. ' $passed_in_query_info = <pre>'
3848
+						. print_r($passed_in_query_info, true)
3849
+						. '</pre>'
3850
+						. "\n\t"
3851
+						. ' $query_param_type = '
3852
+						. $query_param_type
3853
+						. "\n\t"
3854
+						. ' $original_query_param = '
3855
+						. $original_query_param
3856
+					)
3857
+				);
3858
+			}
3859
+		} //check if it's a custom selection
3860
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3861
+			return;
3862
+		}
3863
+		//check if has a model name at the beginning
3864
+		//and
3865
+		//check if it's a field on a related model
3866
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3867
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3868
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3869
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3870
+				if ($query_param === '') {
3871
+					//nothing left to $query_param
3872
+					//we should actually end in a field name, not a model like this!
3873
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3874
+						"event_espresso"),
3875
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3876
+				} else {
3877
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3878
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3879
+						$passed_in_query_info, $query_param_type, $original_query_param);
3880
+					return;
3881
+				}
3882
+			} elseif ($query_param === $valid_related_model_name) {
3883
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3884
+				return;
3885
+			}
3886
+		}
3887
+		//ok so $query_param didn't start with a model name
3888
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3889
+		//it's wack, that's what it is
3890
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3891
+			"event_espresso"),
3892
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3893
+	}
3894
+
3895
+
3896
+
3897
+	/**
3898
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3899
+	 * and store it on $passed_in_query_info
3900
+	 *
3901
+	 * @param string                      $model_name
3902
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3903
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3904
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3905
+	 *                                                          and are adding a join to 'Payment' with the original
3906
+	 *                                                          query param key
3907
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3908
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3909
+	 *                                                          Payment wants to add default query params so that it
3910
+	 *                                                          will know what models to prepend onto its default query
3911
+	 *                                                          params or in case it wants to rename tables (in case
3912
+	 *                                                          there are multiple joins to the same table)
3913
+	 * @return void
3914
+	 * @throws EE_Error
3915
+	 */
3916
+	private function _add_join_to_model(
3917
+		$model_name,
3918
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3919
+		$original_query_param
3920
+	) {
3921
+		$relation_obj = $this->related_settings_for($model_name);
3922
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3923
+		//check if the relation is HABTM, because then we're essentially doing two joins
3924
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3925
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3926
+			$join_model_obj = $relation_obj->get_join_model();
3927
+			//replace the model specified with the join model for this relation chain, whi
3928
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3929
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3930
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3931
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3932
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3933
+			$passed_in_query_info->merge($new_query_info);
3934
+		}
3935
+		//now just join to the other table pointed to by the relation object, and add its data types
3936
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3937
+			array($model_relation_chain => $model_name),
3938
+			$relation_obj->get_join_statement($model_relation_chain));
3939
+		$passed_in_query_info->merge($new_query_info);
3940
+	}
3941
+
3942
+
3943
+
3944
+	/**
3945
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3946
+	 *
3947
+	 * @param array $where_params like EEM_Base::get_all
3948
+	 * @return string of SQL
3949
+	 * @throws EE_Error
3950
+	 */
3951
+	private function _construct_where_clause($where_params)
3952
+	{
3953
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3954
+		if ($SQL) {
3955
+			return " WHERE " . $SQL;
3956
+		} else {
3957
+			return '';
3958
+		}
3959
+	}
3960
+
3961
+
3962
+
3963
+	/**
3964
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3965
+	 * and should be passed HAVING parameters, not WHERE parameters
3966
+	 *
3967
+	 * @param array $having_params
3968
+	 * @return string
3969
+	 * @throws EE_Error
3970
+	 */
3971
+	private function _construct_having_clause($having_params)
3972
+	{
3973
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3974
+		if ($SQL) {
3975
+			return " HAVING " . $SQL;
3976
+		} else {
3977
+			return '';
3978
+		}
3979
+	}
3980
+
3981
+
3982
+
3983
+	/**
3984
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3985
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3986
+	 * EEM_Attendee.
3987
+	 *
3988
+	 * @param string $field_name
3989
+	 * @param string $model_name
3990
+	 * @return EE_Model_Field_Base
3991
+	 * @throws EE_Error
3992
+	 */
3993
+	protected function _get_field_on_model($field_name, $model_name)
3994
+	{
3995
+		$model_class = 'EEM_' . $model_name;
3996
+		$model_filepath = $model_class . ".model.php";
3997
+		if (is_readable($model_filepath)) {
3998
+			require_once($model_filepath);
3999
+			$model_instance = call_user_func($model_name . "::instance");
4000
+			/* @var $model_instance EEM_Base */
4001
+			return $model_instance->field_settings_for($field_name);
4002
+		} else {
4003
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
4004
+				'event_espresso'), $model_name, $model_class, $model_filepath));
4005
+		}
4006
+	}
4007
+
4008
+
4009
+
4010
+	/**
4011
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4012
+	 * Event_Meta.meta_value = 'foo'))"
4013
+	 *
4014
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4015
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4016
+	 * @throws EE_Error
4017
+	 * @return string of SQL
4018
+	 */
4019
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4020
+	{
4021
+		$where_clauses = array();
4022
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4023
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4024
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4025
+				switch ($query_param) {
4026
+					case 'not':
4027
+					case 'NOT':
4028
+						$where_clauses[] = "! ("
4029
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4030
+								$glue)
4031
+										   . ")";
4032
+						break;
4033
+					case 'and':
4034
+					case 'AND':
4035
+						$where_clauses[] = " ("
4036
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4037
+								' AND ')
4038
+										   . ")";
4039
+						break;
4040
+					case 'or':
4041
+					case 'OR':
4042
+						$where_clauses[] = " ("
4043
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4044
+								' OR ')
4045
+										   . ")";
4046
+						break;
4047
+				}
4048
+			} else {
4049
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4050
+				//if it's not a normal field, maybe it's a custom selection?
4051
+				if (! $field_obj) {
4052
+					if (isset($this->_custom_selections[$query_param][1])) {
4053
+						$field_obj = $this->_custom_selections[$query_param][1];
4054
+					} else {
4055
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4056
+							"event_espresso"), $query_param));
4057
+					}
4058
+				}
4059
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4060
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4061
+			}
4062
+		}
4063
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4064
+	}
4065
+
4066
+
4067
+
4068
+	/**
4069
+	 * Takes the input parameter and extract the table name (alias) and column name
4070
+	 *
4071
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4072
+	 * @throws EE_Error
4073
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4074
+	 */
4075
+	private function _deduce_column_name_from_query_param($query_param)
4076
+	{
4077
+		$field = $this->_deduce_field_from_query_param($query_param);
4078
+		if ($field) {
4079
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4080
+				$query_param);
4081
+			return $table_alias_prefix . $field->get_qualified_column();
4082
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4083
+			//maybe it's custom selection item?
4084
+			//if so, just use it as the "column name"
4085
+			return $query_param;
4086
+		} else {
4087
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4088
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4089
+		}
4090
+	}
4091
+
4092
+
4093
+
4094
+	/**
4095
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4096
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4097
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4098
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4099
+	 *
4100
+	 * @param string $condition_query_param_key
4101
+	 * @return string
4102
+	 */
4103
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4104
+	{
4105
+		$pos_of_star = strpos($condition_query_param_key, '*');
4106
+		if ($pos_of_star === false) {
4107
+			return $condition_query_param_key;
4108
+		} else {
4109
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4110
+			return $condition_query_param_sans_star;
4111
+		}
4112
+	}
4113
+
4114
+
4115
+
4116
+	/**
4117
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4118
+	 *
4119
+	 * @param                            mixed      array | string    $op_and_value
4120
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4121
+	 * @throws EE_Error
4122
+	 * @return string
4123
+	 */
4124
+	private function _construct_op_and_value($op_and_value, $field_obj)
4125
+	{
4126
+		if (is_array($op_and_value)) {
4127
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4128
+			if (! $operator) {
4129
+				$php_array_like_string = array();
4130
+				foreach ($op_and_value as $key => $value) {
4131
+					$php_array_like_string[] = "$key=>$value";
4132
+				}
4133
+				throw new EE_Error(
4134
+					sprintf(
4135
+						__(
4136
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4137
+							"event_espresso"
4138
+						),
4139
+						implode(",", $php_array_like_string)
4140
+					)
4141
+				);
4142
+			}
4143
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4144
+		} else {
4145
+			$operator = '=';
4146
+			$value = $op_and_value;
4147
+		}
4148
+		//check to see if the value is actually another field
4149
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4150
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4151
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4152
+			//in this case, the value should be an array, or at least a comma-separated list
4153
+			//it will need to handle a little differently
4154
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4155
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4156
+			return $operator . SP . $cleaned_value;
4157
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4158
+			//the value should be an array with count of two.
4159
+			if (count($value) !== 2) {
4160
+				throw new EE_Error(
4161
+					sprintf(
4162
+						__(
4163
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4164
+							'event_espresso'
4165
+						),
4166
+						"BETWEEN"
4167
+					)
4168
+				);
4169
+			}
4170
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4171
+			return $operator . SP . $cleaned_value;
4172
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4173
+			if ($value !== null) {
4174
+				throw new EE_Error(
4175
+					sprintf(
4176
+						__(
4177
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4178
+							"event_espresso"
4179
+						),
4180
+						$value,
4181
+						$operator
4182
+					)
4183
+				);
4184
+			}
4185
+			return $operator;
4186
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4187
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4188
+			//remove other junk. So just treat it as a string.
4189
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4190
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4191
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4192
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4193
+			throw new EE_Error(
4194
+				sprintf(
4195
+					__(
4196
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4197
+						'event_espresso'
4198
+					),
4199
+					$operator,
4200
+					$operator
4201
+				)
4202
+			);
4203
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4204
+			throw new EE_Error(
4205
+				sprintf(
4206
+					__(
4207
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4208
+						'event_espresso'
4209
+					),
4210
+					$operator,
4211
+					$operator
4212
+				)
4213
+			);
4214
+		} else {
4215
+			throw new EE_Error(
4216
+				sprintf(
4217
+					__(
4218
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4219
+						"event_espresso"
4220
+					),
4221
+					http_build_query($op_and_value)
4222
+				)
4223
+			);
4224
+		}
4225
+	}
4226
+
4227
+
4228
+
4229
+	/**
4230
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4231
+	 *
4232
+	 * @param array                      $values
4233
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4234
+	 *                                              '%s'
4235
+	 * @return string
4236
+	 * @throws EE_Error
4237
+	 */
4238
+	public function _construct_between_value($values, $field_obj)
4239
+	{
4240
+		$cleaned_values = array();
4241
+		foreach ($values as $value) {
4242
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4243
+		}
4244
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4245
+	}
4246
+
4247
+
4248
+
4249
+	/**
4250
+	 * Takes an array or a comma-separated list of $values and cleans them
4251
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4252
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4253
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4254
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4255
+	 *
4256
+	 * @param mixed                      $values    array or comma-separated string
4257
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4258
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4259
+	 * @throws EE_Error
4260
+	 */
4261
+	public function _construct_in_value($values, $field_obj)
4262
+	{
4263
+		//check if the value is a CSV list
4264
+		if (is_string($values)) {
4265
+			//in which case, turn it into an array
4266
+			$values = explode(",", $values);
4267
+		}
4268
+		$cleaned_values = array();
4269
+		foreach ($values as $value) {
4270
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4271
+		}
4272
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4273
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4274
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4275
+		if (empty($cleaned_values)) {
4276
+			$all_fields = $this->field_settings();
4277
+			$a_field = array_shift($all_fields);
4278
+			$main_table = $this->_get_main_table();
4279
+			$cleaned_values[] = "SELECT "
4280
+								. $a_field->get_table_column()
4281
+								. " FROM "
4282
+								. $main_table->get_table_name()
4283
+								. " WHERE FALSE";
4284
+		}
4285
+		return "(" . implode(",", $cleaned_values) . ")";
4286
+	}
4287
+
4288
+
4289
+
4290
+	/**
4291
+	 * @param mixed                      $value
4292
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4293
+	 * @throws EE_Error
4294
+	 * @return false|null|string
4295
+	 */
4296
+	private function _wpdb_prepare_using_field($value, $field_obj)
4297
+	{
4298
+		/** @type WPDB $wpdb */
4299
+		global $wpdb;
4300
+		if ($field_obj instanceof EE_Model_Field_Base) {
4301
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4302
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4303
+		} else {//$field_obj should really just be a data type
4304
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4305
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4306
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4307
+			}
4308
+			return $wpdb->prepare($field_obj, $value);
4309
+		}
4310
+	}
4311
+
4312
+
4313
+
4314
+	/**
4315
+	 * Takes the input parameter and finds the model field that it indicates.
4316
+	 *
4317
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4318
+	 * @throws EE_Error
4319
+	 * @return EE_Model_Field_Base
4320
+	 */
4321
+	protected function _deduce_field_from_query_param($query_param_name)
4322
+	{
4323
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4324
+		//which will help us find the database table and column
4325
+		$query_param_parts = explode(".", $query_param_name);
4326
+		if (empty($query_param_parts)) {
4327
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4328
+				'event_espresso'), $query_param_name));
4329
+		}
4330
+		$number_of_parts = count($query_param_parts);
4331
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4332
+		if ($number_of_parts === 1) {
4333
+			$field_name = $last_query_param_part;
4334
+			$model_obj = $this;
4335
+		} else {// $number_of_parts >= 2
4336
+			//the last part is the column name, and there are only 2parts. therefore...
4337
+			$field_name = $last_query_param_part;
4338
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4339
+		}
4340
+		try {
4341
+			return $model_obj->field_settings_for($field_name);
4342
+		} catch (EE_Error $e) {
4343
+			return null;
4344
+		}
4345
+	}
4346
+
4347
+
4348
+
4349
+	/**
4350
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4351
+	 * alias and column which corresponds to it
4352
+	 *
4353
+	 * @param string $field_name
4354
+	 * @throws EE_Error
4355
+	 * @return string
4356
+	 */
4357
+	public function _get_qualified_column_for_field($field_name)
4358
+	{
4359
+		$all_fields = $this->field_settings();
4360
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4361
+		if ($field) {
4362
+			return $field->get_qualified_column();
4363
+		} else {
4364
+			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4365
+				'event_espresso'), $field_name, get_class($this)));
4366
+		}
4367
+	}
4368
+
4369
+
4370
+
4371
+	/**
4372
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4373
+	 * Example usage:
4374
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4375
+	 *      array(),
4376
+	 *      ARRAY_A,
4377
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4378
+	 *  );
4379
+	 * is equivalent to
4380
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4381
+	 * and
4382
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4383
+	 *      array(
4384
+	 *          array(
4385
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4386
+	 *          ),
4387
+	 *          ARRAY_A,
4388
+	 *          implode(
4389
+	 *              ', ',
4390
+	 *              array_merge(
4391
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4392
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4393
+	 *              )
4394
+	 *          )
4395
+	 *      )
4396
+	 *  );
4397
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4398
+	 *
4399
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4400
+	 *                                            and the one whose fields you are selecting for example: when querying
4401
+	 *                                            tickets model and selecting fields from the tickets model you would
4402
+	 *                                            leave this parameter empty, because no models are needed to join
4403
+	 *                                            between the queried model and the selected one. Likewise when
4404
+	 *                                            querying the datetime model and selecting fields from the tickets
4405
+	 *                                            model, it would also be left empty, because there is a direct
4406
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4407
+	 *                                            them together. However, when querying from the event model and
4408
+	 *                                            selecting fields from the ticket model, you should provide the string
4409
+	 *                                            'Datetime', indicating that the event model must first join to the
4410
+	 *                                            datetime model in order to find its relation to ticket model.
4411
+	 *                                            Also, when querying from the venue model and selecting fields from
4412
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4413
+	 *                                            indicating you need to join the venue model to the event model,
4414
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4415
+	 *                                            This string is used to deduce the prefix that gets added onto the
4416
+	 *                                            models' tables qualified columns
4417
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4418
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4419
+	 *                                            qualified column names
4420
+	 * @return array|string
4421
+	 */
4422
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4423
+	{
4424
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4425
+		$qualified_columns = array();
4426
+		foreach ($this->field_settings() as $field_name => $field) {
4427
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4428
+		}
4429
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4430
+	}
4431
+
4432
+
4433
+
4434
+	/**
4435
+	 * constructs the select use on special limit joins
4436
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4437
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4438
+	 * (as that is typically where the limits would be set).
4439
+	 *
4440
+	 * @param  string       $table_alias The table the select is being built for
4441
+	 * @param  mixed|string $limit       The limit for this select
4442
+	 * @return string                The final select join element for the query.
4443
+	 */
4444
+	public function _construct_limit_join_select($table_alias, $limit)
4445
+	{
4446
+		$SQL = '';
4447
+		foreach ($this->_tables as $table_obj) {
4448
+			if ($table_obj instanceof EE_Primary_Table) {
4449
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4450
+					? $table_obj->get_select_join_limit($limit)
4451
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4452
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4453
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4454
+					? $table_obj->get_select_join_limit_join($limit)
4455
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4456
+			}
4457
+		}
4458
+		return $SQL;
4459
+	}
4460
+
4461
+
4462
+
4463
+	/**
4464
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4465
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4466
+	 *
4467
+	 * @return string SQL
4468
+	 * @throws EE_Error
4469
+	 */
4470
+	public function _construct_internal_join()
4471
+	{
4472
+		$SQL = $this->_get_main_table()->get_table_sql();
4473
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4474
+		return $SQL;
4475
+	}
4476
+
4477
+
4478
+
4479
+	/**
4480
+	 * Constructs the SQL for joining all the tables on this model.
4481
+	 * Normally $alias should be the primary table's alias, but in cases where
4482
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4483
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4484
+	 * alias, this will construct SQL like:
4485
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4486
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4487
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4488
+	 *
4489
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4490
+	 * @return string
4491
+	 */
4492
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4493
+	{
4494
+		$SQL = '';
4495
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4496
+		foreach ($this->_tables as $table_obj) {
4497
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4498
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4499
+					//so we're joining to this table, meaning the table is already in
4500
+					//the FROM statement, BUT the primary table isn't. So we want
4501
+					//to add the inverse join sql
4502
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4503
+				} else {
4504
+					//just add a regular JOIN to this table from the primary table
4505
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4506
+				}
4507
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4508
+		}
4509
+		return $SQL;
4510
+	}
4511
+
4512
+
4513
+
4514
+	/**
4515
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4516
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4517
+	 * their data type (eg, '%s', '%d', etc)
4518
+	 *
4519
+	 * @return array
4520
+	 */
4521
+	public function _get_data_types()
4522
+	{
4523
+		$data_types = array();
4524
+		foreach ($this->field_settings() as $field_obj) {
4525
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4526
+			/** @var $field_obj EE_Model_Field_Base */
4527
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4528
+		}
4529
+		return $data_types;
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4536
+	 *
4537
+	 * @param string $model_name
4538
+	 * @throws EE_Error
4539
+	 * @return EEM_Base
4540
+	 */
4541
+	public function get_related_model_obj($model_name)
4542
+	{
4543
+		$model_classname = "EEM_" . $model_name;
4544
+		if (! class_exists($model_classname)) {
4545
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4546
+				'event_espresso'), $model_name, $model_classname));
4547
+		}
4548
+		return call_user_func($model_classname . "::instance");
4549
+	}
4550
+
4551
+
4552
+
4553
+	/**
4554
+	 * Returns the array of EE_ModelRelations for this model.
4555
+	 *
4556
+	 * @return EE_Model_Relation_Base[]
4557
+	 */
4558
+	public function relation_settings()
4559
+	{
4560
+		return $this->_model_relations;
4561
+	}
4562
+
4563
+
4564
+
4565
+	/**
4566
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4567
+	 * because without THOSE models, this model probably doesn't have much purpose.
4568
+	 * (Eg, without an event, datetimes have little purpose.)
4569
+	 *
4570
+	 * @return EE_Belongs_To_Relation[]
4571
+	 */
4572
+	public function belongs_to_relations()
4573
+	{
4574
+		$belongs_to_relations = array();
4575
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4576
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4577
+				$belongs_to_relations[$model_name] = $relation_obj;
4578
+			}
4579
+		}
4580
+		return $belongs_to_relations;
4581
+	}
4582
+
4583
+
4584
+
4585
+	/**
4586
+	 * Returns the specified EE_Model_Relation, or throws an exception
4587
+	 *
4588
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4589
+	 * @throws EE_Error
4590
+	 * @return EE_Model_Relation_Base
4591
+	 */
4592
+	public function related_settings_for($relation_name)
4593
+	{
4594
+		$relatedModels = $this->relation_settings();
4595
+		if (! array_key_exists($relation_name, $relatedModels)) {
4596
+			throw new EE_Error(
4597
+				sprintf(
4598
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4599
+						'event_espresso'),
4600
+					$relation_name,
4601
+					$this->_get_class_name(),
4602
+					implode(', ', array_keys($relatedModels))
4603
+				)
4604
+			);
4605
+		}
4606
+		return $relatedModels[$relation_name];
4607
+	}
4608
+
4609
+
4610
+
4611
+	/**
4612
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4613
+	 * fields
4614
+	 *
4615
+	 * @param string $fieldName
4616
+	 * @throws EE_Error
4617
+	 * @return EE_Model_Field_Base
4618
+	 */
4619
+	public function field_settings_for($fieldName)
4620
+	{
4621
+		$fieldSettings = $this->field_settings(true);
4622
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4623
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4624
+				get_class($this)));
4625
+		}
4626
+		return $fieldSettings[$fieldName];
4627
+	}
4628
+
4629
+
4630
+
4631
+	/**
4632
+	 * Checks if this field exists on this model
4633
+	 *
4634
+	 * @param string $fieldName a key in the model's _field_settings array
4635
+	 * @return boolean
4636
+	 */
4637
+	public function has_field($fieldName)
4638
+	{
4639
+		$fieldSettings = $this->field_settings(true);
4640
+		if (isset($fieldSettings[$fieldName])) {
4641
+			return true;
4642
+		} else {
4643
+			return false;
4644
+		}
4645
+	}
4646
+
4647
+
4648
+
4649
+	/**
4650
+	 * Returns whether or not this model has a relation to the specified model
4651
+	 *
4652
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4653
+	 * @return boolean
4654
+	 */
4655
+	public function has_relation($relation_name)
4656
+	{
4657
+		$relations = $this->relation_settings();
4658
+		if (isset($relations[$relation_name])) {
4659
+			return true;
4660
+		} else {
4661
+			return false;
4662
+		}
4663
+	}
4664
+
4665
+
4666
+
4667
+	/**
4668
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4669
+	 * Eg, on EE_Answer that would be ANS_ID field object
4670
+	 *
4671
+	 * @param $field_obj
4672
+	 * @return boolean
4673
+	 */
4674
+	public function is_primary_key_field($field_obj)
4675
+	{
4676
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4677
+	}
4678
+
4679
+
4680
+
4681
+	/**
4682
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4683
+	 * Eg, on EE_Answer that would be ANS_ID field object
4684
+	 *
4685
+	 * @return EE_Model_Field_Base
4686
+	 * @throws EE_Error
4687
+	 */
4688
+	public function get_primary_key_field()
4689
+	{
4690
+		if ($this->_primary_key_field === null) {
4691
+			foreach ($this->field_settings(true) as $field_obj) {
4692
+				if ($this->is_primary_key_field($field_obj)) {
4693
+					$this->_primary_key_field = $field_obj;
4694
+					break;
4695
+				}
4696
+			}
4697
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4698
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4699
+					get_class($this)));
4700
+			}
4701
+		}
4702
+		return $this->_primary_key_field;
4703
+	}
4704
+
4705
+
4706
+
4707
+	/**
4708
+	 * Returns whether or not not there is a primary key on this model.
4709
+	 * Internally does some caching.
4710
+	 *
4711
+	 * @return boolean
4712
+	 */
4713
+	public function has_primary_key_field()
4714
+	{
4715
+		if ($this->_has_primary_key_field === null) {
4716
+			try {
4717
+				$this->get_primary_key_field();
4718
+				$this->_has_primary_key_field = true;
4719
+			} catch (EE_Error $e) {
4720
+				$this->_has_primary_key_field = false;
4721
+			}
4722
+		}
4723
+		return $this->_has_primary_key_field;
4724
+	}
4725
+
4726
+
4727
+
4728
+	/**
4729
+	 * Finds the first field of type $field_class_name.
4730
+	 *
4731
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4732
+	 *                                 EE_Foreign_Key_Field, etc
4733
+	 * @return EE_Model_Field_Base or null if none is found
4734
+	 */
4735
+	public function get_a_field_of_type($field_class_name)
4736
+	{
4737
+		foreach ($this->field_settings() as $field) {
4738
+			if ($field instanceof $field_class_name) {
4739
+				return $field;
4740
+			}
4741
+		}
4742
+		return null;
4743
+	}
4744
+
4745
+
4746
+
4747
+	/**
4748
+	 * Gets a foreign key field pointing to model.
4749
+	 *
4750
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4751
+	 * @return EE_Foreign_Key_Field_Base
4752
+	 * @throws EE_Error
4753
+	 */
4754
+	public function get_foreign_key_to($model_name)
4755
+	{
4756
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4757
+			foreach ($this->field_settings() as $field) {
4758
+				if (
4759
+					$field instanceof EE_Foreign_Key_Field_Base
4760
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4761
+				) {
4762
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4763
+					break;
4764
+				}
4765
+			}
4766
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4767
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4768
+					'event_espresso'), $model_name, get_class($this)));
4769
+			}
4770
+		}
4771
+		return $this->_cache_foreign_key_to_fields[$model_name];
4772
+	}
4773
+
4774
+
4775
+
4776
+	/**
4777
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4778
+	 *
4779
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4780
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4781
+	 *                            Either one works
4782
+	 * @return string
4783
+	 */
4784
+	public function get_table_for_alias($table_alias)
4785
+	{
4786
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4787
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4788
+	}
4789
+
4790
+
4791
+
4792
+	/**
4793
+	 * Returns a flat array of all field son this model, instead of organizing them
4794
+	 * by table_alias as they are in the constructor.
4795
+	 *
4796
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4797
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4798
+	 */
4799
+	public function field_settings($include_db_only_fields = false)
4800
+	{
4801
+		if ($include_db_only_fields) {
4802
+			if ($this->_cached_fields === null) {
4803
+				$this->_cached_fields = array();
4804
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4805
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4806
+						$this->_cached_fields[$field_name] = $field_obj;
4807
+					}
4808
+				}
4809
+			}
4810
+			return $this->_cached_fields;
4811
+		} else {
4812
+			if ($this->_cached_fields_non_db_only === null) {
4813
+				$this->_cached_fields_non_db_only = array();
4814
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4815
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4816
+						/** @var $field_obj EE_Model_Field_Base */
4817
+						if (! $field_obj->is_db_only_field()) {
4818
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4819
+						}
4820
+					}
4821
+				}
4822
+			}
4823
+			return $this->_cached_fields_non_db_only;
4824
+		}
4825
+	}
4826
+
4827
+
4828
+
4829
+	/**
4830
+	 *        cycle though array of attendees and create objects out of each item
4831
+	 *
4832
+	 * @access        private
4833
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4834
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4835
+	 *                           numerically indexed)
4836
+	 * @throws EE_Error
4837
+	 */
4838
+	protected function _create_objects($rows = array())
4839
+	{
4840
+		$array_of_objects = array();
4841
+		if (empty($rows)) {
4842
+			return array();
4843
+		}
4844
+		$count_if_model_has_no_primary_key = 0;
4845
+		$has_primary_key = $this->has_primary_key_field();
4846
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4847
+		foreach ((array)$rows as $row) {
4848
+			if (empty($row)) {
4849
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4850
+				return array();
4851
+			}
4852
+			//check if we've already set this object in the results array,
4853
+			//in which case there's no need to process it further (again)
4854
+			if ($has_primary_key) {
4855
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4856
+					$row,
4857
+					$primary_key_field->get_qualified_column(),
4858
+					$primary_key_field->get_table_column()
4859
+				);
4860
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4861
+					continue;
4862
+				}
4863
+			}
4864
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4865
+			if (! $classInstance) {
4866
+				throw new EE_Error(
4867
+					sprintf(
4868
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4869
+						$this->get_this_model_name(),
4870
+						http_build_query($row)
4871
+					)
4872
+				);
4873
+			}
4874
+			//set the timezone on the instantiated objects
4875
+			$classInstance->set_timezone($this->_timezone);
4876
+			//make sure if there is any timezone setting present that we set the timezone for the object
4877
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4878
+			$array_of_objects[$key] = $classInstance;
4879
+			//also, for all the relations of type BelongsTo, see if we can cache
4880
+			//those related models
4881
+			//(we could do this for other relations too, but if there are conditions
4882
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4883
+			//so it requires a little more thought than just caching them immediately...)
4884
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4885
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4886
+					//check if this model's INFO is present. If so, cache it on the model
4887
+					$other_model = $relation_obj->get_other_model();
4888
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4889
+					//if we managed to make a model object from the results, cache it on the main model object
4890
+					if ($other_model_obj_maybe) {
4891
+						//set timezone on these other model objects if they are present
4892
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4893
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4894
+					}
4895
+				}
4896
+			}
4897
+		}
4898
+		return $array_of_objects;
4899
+	}
4900
+
4901
+
4902
+
4903
+	/**
4904
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4905
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4906
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4907
+	 * object (as set in the model_field!).
4908
+	 *
4909
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4910
+	 * @throws Exception
4911
+	 */
4912
+	public function create_default_object()
4913
+	{
4914
+		$this_model_fields_and_values = array();
4915
+		//setup the row using default values;
4916
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4917
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4918
+		}
4919
+		$classInstance = $this->_instantiate_new_instance_from_db(
4920
+			$this->_get_class_name(),
4921
+			$this_model_fields_and_values
4922
+		);
4923
+		return $classInstance;
4924
+	}
4925
+
4926
+
4927
+
4928
+	/**
4929
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4930
+	 *                             or an stdClass where each property is the name of a column,
4931
+	 * @return EE_Base_Class
4932
+	 * @throws Exception
4933
+	 * @throws EE_Error
4934
+	 */
4935
+	public function instantiate_class_from_array_or_object($cols_n_values)
4936
+	{
4937
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4938
+			$cols_n_values = get_object_vars($cols_n_values);
4939
+		}
4940
+		$primary_key = null;
4941
+		//make sure the array only has keys that are fields/columns on this model
4942
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4943
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4944
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4945
+		}
4946
+		//check we actually found results that we can use to build our model object
4947
+		//if not, return null
4948
+		if ($this->has_primary_key_field()) {
4949
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4950
+				return null;
4951
+			}
4952
+		} else if ($this->unique_indexes()) {
4953
+			$first_column = reset($this_model_fields_n_values);
4954
+			if (empty($first_column)) {
4955
+				return null;
4956
+			}
4957
+		}
4958
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4959
+		if ($primary_key) {
4960
+			$classInstance = $this->get_from_entity_map($primary_key);
4961
+			if (! $classInstance) {
4962
+				$classInstance = $this->_instantiate_new_instance_from_db(
4963
+					$this->_get_class_name(),
4964
+					$this_model_fields_n_values
4965
+				);
4966
+				// add this new object to the entity map
4967
+				$classInstance = $this->add_to_entity_map($classInstance);
4968
+			}
4969
+		} else {
4970
+			$classInstance = $this->_instantiate_new_instance_from_db(
4971
+				$this->_get_class_name(),
4972
+				$this_model_fields_n_values
4973
+			);
4974
+		}
4975
+		// it is entirely possible that the instantiated class object has a set
4976
+		// timezone_string db field and has set it's internal _timezone property accordingly
4977
+		// (see new_instance_from_db in model objects particularly EE_Event for example).
4978
+		// In this case, we want to make sure the model object doesn't have its timezone string
4979
+		// overwritten by any timezone property currently set here on the model so,
4980
+		// we intentionally override the model _timezone property with the model_object timezone property.
4981
+		$this->set_timezone($classInstance->get_timezone());
4982
+		return $classInstance;
4983
+	}
4984
+
4985
+
4986
+
4987
+	/**
4988
+	 * Gets the model object from the  entity map if it exists
4989
+	 *
4990
+	 * @param int|string $id the ID of the model object
4991
+	 * @return EE_Base_Class
4992
+	 */
4993
+	public function get_from_entity_map($id)
4994
+	{
4995
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4996
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4997
+	}
4998
+
4999
+
5000
+
5001
+	/**
5002
+	 * add_to_entity_map
5003
+	 * Adds the object to the model's entity mappings
5004
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5005
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5006
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5007
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5008
+	 *        then this method should be called immediately after the update query
5009
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5010
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5011
+	 *
5012
+	 * @param    EE_Base_Class $object
5013
+	 * @throws EE_Error
5014
+	 * @return \EE_Base_Class
5015
+	 */
5016
+	public function add_to_entity_map(EE_Base_Class $object)
5017
+	{
5018
+		$className = $this->_get_class_name();
5019
+		if (! $object instanceof $className) {
5020
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5021
+				is_object($object) ? get_class($object) : $object, $className));
5022
+		}
5023
+		/** @var $object EE_Base_Class */
5024
+		if (! $object->ID()) {
5025
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5026
+				"event_espresso"), get_class($this)));
5027
+		}
5028
+		// double check it's not already there
5029
+		$classInstance = $this->get_from_entity_map($object->ID());
5030
+		if ($classInstance) {
5031
+			return $classInstance;
5032
+		} else {
5033
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5034
+			return $object;
5035
+		}
5036
+	}
5037
+
5038
+
5039
+
5040
+	/**
5041
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5042
+	 * if no identifier is provided, then the entire entity map is emptied
5043
+	 *
5044
+	 * @param int|string $id the ID of the model object
5045
+	 * @return boolean
5046
+	 */
5047
+	public function clear_entity_map($id = null)
5048
+	{
5049
+		if (empty($id)) {
5050
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5051
+			return true;
5052
+		}
5053
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5054
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5055
+			return true;
5056
+		}
5057
+		return false;
5058
+	}
5059
+
5060
+
5061
+
5062
+	/**
5063
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5064
+	 * Given an array where keys are column (or column alias) names and values,
5065
+	 * returns an array of their corresponding field names and database values
5066
+	 *
5067
+	 * @param array $cols_n_values
5068
+	 * @return array
5069
+	 */
5070
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5071
+	{
5072
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5073
+	}
5074
+
5075
+
5076
+
5077
+	/**
5078
+	 * _deduce_fields_n_values_from_cols_n_values
5079
+	 * Given an array where keys are column (or column alias) names and values,
5080
+	 * returns an array of their corresponding field names and database values
5081
+	 *
5082
+	 * @param string $cols_n_values
5083
+	 * @return array
5084
+	 */
5085
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5086
+	{
5087
+		$this_model_fields_n_values = array();
5088
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5089
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5090
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5091
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5092
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5093
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5094
+					if (! $field_obj->is_db_only_field()) {
5095
+						//prepare field as if its coming from db
5096
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5097
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5098
+					}
5099
+				}
5100
+			} else {
5101
+				//the table's rows existed. Use their values
5102
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5103
+					if (! $field_obj->is_db_only_field()) {
5104
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5105
+							$cols_n_values, $field_obj->get_qualified_column(),
5106
+							$field_obj->get_table_column()
5107
+						);
5108
+					}
5109
+				}
5110
+			}
5111
+		}
5112
+		return $this_model_fields_n_values;
5113
+	}
5114
+
5115
+
5116
+
5117
+	/**
5118
+	 * @param $cols_n_values
5119
+	 * @param $qualified_column
5120
+	 * @param $regular_column
5121
+	 * @return null
5122
+	 */
5123
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5124
+	{
5125
+		$value = null;
5126
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5127
+		//does the field on the model relate to this column retrieved from the db?
5128
+		//or is it a db-only field? (not relating to the model)
5129
+		if (isset($cols_n_values[$qualified_column])) {
5130
+			$value = $cols_n_values[$qualified_column];
5131
+		} elseif (isset($cols_n_values[$regular_column])) {
5132
+			$value = $cols_n_values[$regular_column];
5133
+		}
5134
+		return $value;
5135
+	}
5136
+
5137
+
5138
+
5139
+	/**
5140
+	 * refresh_entity_map_from_db
5141
+	 * Makes sure the model object in the entity map at $id assumes the values
5142
+	 * of the database (opposite of EE_base_Class::save())
5143
+	 *
5144
+	 * @param int|string $id
5145
+	 * @return EE_Base_Class
5146
+	 * @throws EE_Error
5147
+	 */
5148
+	public function refresh_entity_map_from_db($id)
5149
+	{
5150
+		$obj_in_map = $this->get_from_entity_map($id);
5151
+		if ($obj_in_map) {
5152
+			$wpdb_results = $this->_get_all_wpdb_results(
5153
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5154
+			);
5155
+			if ($wpdb_results && is_array($wpdb_results)) {
5156
+				$one_row = reset($wpdb_results);
5157
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5158
+					$obj_in_map->set_from_db($field_name, $db_value);
5159
+				}
5160
+				//clear the cache of related model objects
5161
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5162
+					$obj_in_map->clear_cache($relation_name, null, true);
5163
+				}
5164
+			}
5165
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5166
+			return $obj_in_map;
5167
+		} else {
5168
+			return $this->get_one_by_ID($id);
5169
+		}
5170
+	}
5171
+
5172
+
5173
+
5174
+	/**
5175
+	 * refresh_entity_map_with
5176
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5177
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5178
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5179
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5180
+	 *
5181
+	 * @param int|string    $id
5182
+	 * @param EE_Base_Class $replacing_model_obj
5183
+	 * @return \EE_Base_Class
5184
+	 * @throws EE_Error
5185
+	 */
5186
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5187
+	{
5188
+		$obj_in_map = $this->get_from_entity_map($id);
5189
+		if ($obj_in_map) {
5190
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5191
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5192
+					$obj_in_map->set($field_name, $value);
5193
+				}
5194
+				//make the model object in the entity map's cache match the $replacing_model_obj
5195
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5196
+					$obj_in_map->clear_cache($relation_name, null, true);
5197
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5198
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5199
+					}
5200
+				}
5201
+			}
5202
+			return $obj_in_map;
5203
+		} else {
5204
+			$this->add_to_entity_map($replacing_model_obj);
5205
+			return $replacing_model_obj;
5206
+		}
5207
+	}
5208
+
5209
+
5210
+
5211
+	/**
5212
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5213
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5214
+	 * require_once($this->_getClassName().".class.php");
5215
+	 *
5216
+	 * @return string
5217
+	 */
5218
+	private function _get_class_name()
5219
+	{
5220
+		return "EE_" . $this->get_this_model_name();
5221
+	}
5222
+
5223
+
5224
+
5225
+	/**
5226
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5227
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5228
+	 * it would be 'Events'.
5229
+	 *
5230
+	 * @param int $quantity
5231
+	 * @return string
5232
+	 */
5233
+	public function item_name($quantity = 1)
5234
+	{
5235
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5236
+	}
5237
+
5238
+
5239
+
5240
+	/**
5241
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5242
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5243
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5244
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5245
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5246
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5247
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5248
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5249
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5250
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5251
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5252
+	 *        return $previousReturnValue.$returnString;
5253
+	 * }
5254
+	 * require('EEM_Answer.model.php');
5255
+	 * $answer=EEM_Answer::instance();
5256
+	 * echo $answer->my_callback('monkeys',100);
5257
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5258
+	 *
5259
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5260
+	 * @param array  $args       array of original arguments passed to the function
5261
+	 * @throws EE_Error
5262
+	 * @return mixed whatever the plugin which calls add_filter decides
5263
+	 */
5264
+	public function __call($methodName, $args)
5265
+	{
5266
+		$className = get_class($this);
5267
+		$tagName = "FHEE__{$className}__{$methodName}";
5268
+		if (! has_filter($tagName)) {
5269
+			throw new EE_Error(
5270
+				sprintf(
5271
+					__('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5272
+						'event_espresso'),
5273
+					$methodName,
5274
+					$className,
5275
+					$tagName,
5276
+					'<br />'
5277
+				)
5278
+			);
5279
+		}
5280
+		return apply_filters($tagName, null, $this, $args);
5281
+	}
5282
+
5283
+
5284
+
5285
+	/**
5286
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5287
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5288
+	 *
5289
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5290
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5291
+	 *                                                       the object's class name
5292
+	 *                                                       or object's ID
5293
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5294
+	 *                                                       exists in the database. If it does not, we add it
5295
+	 * @throws EE_Error
5296
+	 * @return EE_Base_Class
5297
+	 */
5298
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5299
+	{
5300
+		$className = $this->_get_class_name();
5301
+		if ($base_class_obj_or_id instanceof $className) {
5302
+			$model_object = $base_class_obj_or_id;
5303
+		} else {
5304
+			$primary_key_field = $this->get_primary_key_field();
5305
+			if (
5306
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5307
+				&& (
5308
+					is_int($base_class_obj_or_id)
5309
+					|| is_string($base_class_obj_or_id)
5310
+				)
5311
+			) {
5312
+				// assume it's an ID.
5313
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5314
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5315
+			} else if (
5316
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5317
+				&& is_string($base_class_obj_or_id)
5318
+			) {
5319
+				// assume its a string representation of the object
5320
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5321
+			} else {
5322
+				throw new EE_Error(
5323
+					sprintf(
5324
+						__(
5325
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5326
+							'event_espresso'
5327
+						),
5328
+						$base_class_obj_or_id,
5329
+						$this->_get_class_name(),
5330
+						print_r($base_class_obj_or_id, true)
5331
+					)
5332
+				);
5333
+			}
5334
+		}
5335
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5336
+			$model_object->save();
5337
+		}
5338
+		return $model_object;
5339
+	}
5340
+
5341
+
5342
+
5343
+	/**
5344
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5345
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5346
+	 * returns it ID.
5347
+	 *
5348
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5349
+	 * @return int|string depending on the type of this model object's ID
5350
+	 * @throws EE_Error
5351
+	 */
5352
+	public function ensure_is_ID($base_class_obj_or_id)
5353
+	{
5354
+		$className = $this->_get_class_name();
5355
+		if ($base_class_obj_or_id instanceof $className) {
5356
+			/** @var $base_class_obj_or_id EE_Base_Class */
5357
+			$id = $base_class_obj_or_id->ID();
5358
+		} elseif (is_int($base_class_obj_or_id)) {
5359
+			//assume it's an ID
5360
+			$id = $base_class_obj_or_id;
5361
+		} elseif (is_string($base_class_obj_or_id)) {
5362
+			//assume its a string representation of the object
5363
+			$id = $base_class_obj_or_id;
5364
+		} else {
5365
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5366
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5367
+				print_r($base_class_obj_or_id, true)));
5368
+		}
5369
+		return $id;
5370
+	}
5371
+
5372
+
5373
+
5374
+	/**
5375
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5376
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5377
+	 * been sanitized and converted into the appropriate domain.
5378
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5379
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5380
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5381
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5382
+	 * $EVT = EEM_Event::instance(); $old_setting =
5383
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5384
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5385
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5386
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5387
+	 *
5388
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5389
+	 * @return void
5390
+	 */
5391
+	public function assume_values_already_prepared_by_model_object(
5392
+		$values_already_prepared = self::not_prepared_by_model_object
5393
+	) {
5394
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5395
+	}
5396
+
5397
+
5398
+
5399
+	/**
5400
+	 * Read comments for assume_values_already_prepared_by_model_object()
5401
+	 *
5402
+	 * @return int
5403
+	 */
5404
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5405
+	{
5406
+		return $this->_values_already_prepared_by_model_object;
5407
+	}
5408
+
5409
+
5410
+
5411
+	/**
5412
+	 * Gets all the indexes on this model
5413
+	 *
5414
+	 * @return EE_Index[]
5415
+	 */
5416
+	public function indexes()
5417
+	{
5418
+		return $this->_indexes;
5419
+	}
5420
+
5421
+
5422
+
5423
+	/**
5424
+	 * Gets all the Unique Indexes on this model
5425
+	 *
5426
+	 * @return EE_Unique_Index[]
5427
+	 */
5428
+	public function unique_indexes()
5429
+	{
5430
+		$unique_indexes = array();
5431
+		foreach ($this->_indexes as $name => $index) {
5432
+			if ($index instanceof EE_Unique_Index) {
5433
+				$unique_indexes [$name] = $index;
5434
+			}
5435
+		}
5436
+		return $unique_indexes;
5437
+	}
5438
+
5439
+
5440
+
5441
+	/**
5442
+	 * Gets all the fields which, when combined, make the primary key.
5443
+	 * This is usually just an array with 1 element (the primary key), but in cases
5444
+	 * where there is no primary key, it's a combination of fields as defined
5445
+	 * on a primary index
5446
+	 *
5447
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5448
+	 * @throws EE_Error
5449
+	 */
5450
+	public function get_combined_primary_key_fields()
5451
+	{
5452
+		foreach ($this->indexes() as $index) {
5453
+			if ($index instanceof EE_Primary_Key_Index) {
5454
+				return $index->fields();
5455
+			}
5456
+		}
5457
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5458
+	}
5459
+
5460
+
5461
+
5462
+	/**
5463
+	 * Used to build a primary key string (when the model has no primary key),
5464
+	 * which can be used a unique string to identify this model object.
5465
+	 *
5466
+	 * @param array $cols_n_values keys are field names, values are their values
5467
+	 * @return string
5468
+	 * @throws EE_Error
5469
+	 */
5470
+	public function get_index_primary_key_string($cols_n_values)
5471
+	{
5472
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5473
+			$this->get_combined_primary_key_fields());
5474
+		return http_build_query($cols_n_values_for_primary_key_index);
5475
+	}
5476
+
5477
+
5478
+
5479
+	/**
5480
+	 * Gets the field values from the primary key string
5481
+	 *
5482
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5483
+	 * @param string $index_primary_key_string
5484
+	 * @return null|array
5485
+	 * @throws EE_Error
5486
+	 */
5487
+	public function parse_index_primary_key_string($index_primary_key_string)
5488
+	{
5489
+		$key_fields = $this->get_combined_primary_key_fields();
5490
+		//check all of them are in the $id
5491
+		$key_vals_in_combined_pk = array();
5492
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5493
+		foreach ($key_fields as $key_field_name => $field_obj) {
5494
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5495
+				return null;
5496
+			}
5497
+		}
5498
+		return $key_vals_in_combined_pk;
5499
+	}
5500
+
5501
+
5502
+
5503
+	/**
5504
+	 * verifies that an array of key-value pairs for model fields has a key
5505
+	 * for each field comprising the primary key index
5506
+	 *
5507
+	 * @param array $key_vals
5508
+	 * @return boolean
5509
+	 * @throws EE_Error
5510
+	 */
5511
+	public function has_all_combined_primary_key_fields($key_vals)
5512
+	{
5513
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5514
+		foreach ($keys_it_should_have as $key) {
5515
+			if (! isset($key_vals[$key])) {
5516
+				return false;
5517
+			}
5518
+		}
5519
+		return true;
5520
+	}
5521
+
5522
+
5523
+
5524
+	/**
5525
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5526
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5527
+	 *
5528
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5529
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5530
+	 * @throws EE_Error
5531
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5532
+	 *                                                              indexed)
5533
+	 */
5534
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5535
+	{
5536
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5537
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5538
+		} elseif (is_array($model_object_or_attributes_array)) {
5539
+			$attributes_array = $model_object_or_attributes_array;
5540
+		} else {
5541
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5542
+				"event_espresso"), $model_object_or_attributes_array));
5543
+		}
5544
+		//even copies obviously won't have the same ID, so remove the primary key
5545
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5546
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5547
+			unset($attributes_array[$this->primary_key_name()]);
5548
+		}
5549
+		if (isset($query_params[0])) {
5550
+			$query_params[0] = array_merge($attributes_array, $query_params);
5551
+		} else {
5552
+			$query_params[0] = $attributes_array;
5553
+		}
5554
+		return $this->get_all($query_params);
5555
+	}
5556
+
5557
+
5558
+
5559
+	/**
5560
+	 * Gets the first copy we find. See get_all_copies for more details
5561
+	 *
5562
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5563
+	 * @param array $query_params
5564
+	 * @return EE_Base_Class
5565
+	 * @throws EE_Error
5566
+	 */
5567
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5568
+	{
5569
+		if (! is_array($query_params)) {
5570
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5571
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5572
+					gettype($query_params)), '4.6.0');
5573
+			$query_params = array();
5574
+		}
5575
+		$query_params['limit'] = 1;
5576
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5577
+		if (is_array($copies)) {
5578
+			return array_shift($copies);
5579
+		} else {
5580
+			return null;
5581
+		}
5582
+	}
5583
+
5584
+
5585
+
5586
+	/**
5587
+	 * Updates the item with the specified id. Ignores default query parameters because
5588
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5589
+	 *
5590
+	 * @param array      $fields_n_values keys are field names, values are their new values
5591
+	 * @param int|string $id              the value of the primary key to update
5592
+	 * @return int number of rows updated
5593
+	 * @throws EE_Error
5594
+	 */
5595
+	public function update_by_ID($fields_n_values, $id)
5596
+	{
5597
+		$query_params = array(
5598
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5599
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5600
+		);
5601
+		return $this->update($fields_n_values, $query_params);
5602
+	}
5603
+
5604
+
5605
+
5606
+	/**
5607
+	 * Changes an operator which was supplied to the models into one usable in SQL
5608
+	 *
5609
+	 * @param string $operator_supplied
5610
+	 * @return string an operator which can be used in SQL
5611
+	 * @throws EE_Error
5612
+	 */
5613
+	private function _prepare_operator_for_sql($operator_supplied)
5614
+	{
5615
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5616
+			: null;
5617
+		if ($sql_operator) {
5618
+			return $sql_operator;
5619
+		} else {
5620
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5621
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5622
+		}
5623
+	}
5624
+
5625
+
5626
+
5627
+	/**
5628
+	 * Gets an array where keys are the primary keys and values are their 'names'
5629
+	 * (as determined by the model object's name() function, which is often overridden)
5630
+	 *
5631
+	 * @param array $query_params like get_all's
5632
+	 * @return string[]
5633
+	 * @throws EE_Error
5634
+	 */
5635
+	public function get_all_names($query_params = array())
5636
+	{
5637
+		$objs = $this->get_all($query_params);
5638
+		$names = array();
5639
+		foreach ($objs as $obj) {
5640
+			$names[$obj->ID()] = $obj->name();
5641
+		}
5642
+		return $names;
5643
+	}
5644
+
5645
+
5646
+
5647
+	/**
5648
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5649
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5650
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5651
+	 * array_keys() on $model_objects.
5652
+	 *
5653
+	 * @param \EE_Base_Class[] $model_objects
5654
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5655
+	 *                                               in the returned array
5656
+	 * @return array
5657
+	 * @throws EE_Error
5658
+	 */
5659
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5660
+	{
5661
+		if (! $this->has_primary_key_field()) {
5662
+			if (WP_DEBUG) {
5663
+				EE_Error::add_error(
5664
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5665
+					__FILE__,
5666
+					__FUNCTION__,
5667
+					__LINE__
5668
+				);
5669
+			}
5670
+		}
5671
+		$IDs = array();
5672
+		foreach ($model_objects as $model_object) {
5673
+			$id = $model_object->ID();
5674
+			if (! $id) {
5675
+				if ($filter_out_empty_ids) {
5676
+					continue;
5677
+				}
5678
+				if (WP_DEBUG) {
5679
+					EE_Error::add_error(
5680
+						__(
5681
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5682
+							'event_espresso'
5683
+						),
5684
+						__FILE__,
5685
+						__FUNCTION__,
5686
+						__LINE__
5687
+					);
5688
+				}
5689
+			}
5690
+			$IDs[] = $id;
5691
+		}
5692
+		return $IDs;
5693
+	}
5694
+
5695
+
5696
+
5697
+	/**
5698
+	 * Returns the string used in capabilities relating to this model. If there
5699
+	 * are no capabilities that relate to this model returns false
5700
+	 *
5701
+	 * @return string|false
5702
+	 */
5703
+	public function cap_slug()
5704
+	{
5705
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5706
+	}
5707
+
5708
+
5709
+
5710
+	/**
5711
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5712
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5713
+	 * only returns the cap restrictions array in that context (ie, the array
5714
+	 * at that key)
5715
+	 *
5716
+	 * @param string $context
5717
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5718
+	 * @throws EE_Error
5719
+	 */
5720
+	public function cap_restrictions($context = EEM_Base::caps_read)
5721
+	{
5722
+		EEM_Base::verify_is_valid_cap_context($context);
5723
+		//check if we ought to run the restriction generator first
5724
+		if (
5725
+			isset($this->_cap_restriction_generators[$context])
5726
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5727
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5728
+		) {
5729
+			$this->_cap_restrictions[$context] = array_merge(
5730
+				$this->_cap_restrictions[$context],
5731
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5732
+			);
5733
+		}
5734
+		//and make sure we've finalized the construction of each restriction
5735
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5736
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5737
+				$where_conditions_obj->_finalize_construct($this);
5738
+			}
5739
+		}
5740
+		return $this->_cap_restrictions[$context];
5741
+	}
5742
+
5743
+
5744
+
5745
+	/**
5746
+	 * Indicating whether or not this model thinks its a wp core model
5747
+	 *
5748
+	 * @return boolean
5749
+	 */
5750
+	public function is_wp_core_model()
5751
+	{
5752
+		return $this->_wp_core_model;
5753
+	}
5754
+
5755
+
5756
+
5757
+	/**
5758
+	 * Gets all the caps that are missing which impose a restriction on
5759
+	 * queries made in this context
5760
+	 *
5761
+	 * @param string $context one of EEM_Base::caps_ constants
5762
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5763
+	 * @throws EE_Error
5764
+	 */
5765
+	public function caps_missing($context = EEM_Base::caps_read)
5766
+	{
5767
+		$missing_caps = array();
5768
+		$cap_restrictions = $this->cap_restrictions($context);
5769
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5770
+			if (! EE_Capabilities::instance()
5771
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5772
+			) {
5773
+				$missing_caps[$cap] = $restriction_if_no_cap;
5774
+			}
5775
+		}
5776
+		return $missing_caps;
5777
+	}
5778
+
5779
+
5780
+
5781
+	/**
5782
+	 * Gets the mapping from capability contexts to action strings used in capability names
5783
+	 *
5784
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5785
+	 * one of 'read', 'edit', or 'delete'
5786
+	 */
5787
+	public function cap_contexts_to_cap_action_map()
5788
+	{
5789
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5790
+			$this);
5791
+	}
5792
+
5793
+
5794
+
5795
+	/**
5796
+	 * Gets the action string for the specified capability context
5797
+	 *
5798
+	 * @param string $context
5799
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5800
+	 * @throws EE_Error
5801
+	 */
5802
+	public function cap_action_for_context($context)
5803
+	{
5804
+		$mapping = $this->cap_contexts_to_cap_action_map();
5805
+		if (isset($mapping[$context])) {
5806
+			return $mapping[$context];
5807
+		}
5808
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5809
+			return $action;
5810
+		}
5811
+		throw new EE_Error(
5812
+			sprintf(
5813
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5814
+				$context,
5815
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5816
+			)
5817
+		);
5818
+	}
5819
+
5820
+
5821
+
5822
+	/**
5823
+	 * Returns all the capability contexts which are valid when querying models
5824
+	 *
5825
+	 * @return array
5826
+	 */
5827
+	public static function valid_cap_contexts()
5828
+	{
5829
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5830
+			self::caps_read,
5831
+			self::caps_read_admin,
5832
+			self::caps_edit,
5833
+			self::caps_delete,
5834
+		));
5835
+	}
5836
+
5837
+
5838
+
5839
+	/**
5840
+	 * Returns all valid options for 'default_where_conditions'
5841
+	 *
5842
+	 * @return array
5843
+	 */
5844
+	public static function valid_default_where_conditions()
5845
+	{
5846
+		return array(
5847
+			EEM_Base::default_where_conditions_all,
5848
+			EEM_Base::default_where_conditions_this_only,
5849
+			EEM_Base::default_where_conditions_others_only,
5850
+			EEM_Base::default_where_conditions_minimum_all,
5851
+			EEM_Base::default_where_conditions_minimum_others,
5852
+			EEM_Base::default_where_conditions_none
5853
+		);
5854
+	}
5855
+
5856
+	// public static function default_where_conditions_full
5857
+	/**
5858
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5859
+	 *
5860
+	 * @param string $context
5861
+	 * @return bool
5862
+	 * @throws EE_Error
5863
+	 */
5864
+	static public function verify_is_valid_cap_context($context)
5865
+	{
5866
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5867
+		if (in_array($context, $valid_cap_contexts)) {
5868
+			return true;
5869
+		} else {
5870
+			throw new EE_Error(
5871
+				sprintf(
5872
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5873
+						'event_espresso'),
5874
+					$context,
5875
+					'EEM_Base',
5876
+					implode(',', $valid_cap_contexts)
5877
+				)
5878
+			);
5879
+		}
5880
+	}
5881
+
5882
+
5883
+
5884
+	/**
5885
+	 * Clears all the models field caches. This is only useful when a sub-class
5886
+	 * might have added a field or something and these caches might be invalidated
5887
+	 */
5888
+	protected function _invalidate_field_caches()
5889
+	{
5890
+		$this->_cache_foreign_key_to_fields = array();
5891
+		$this->_cached_fields = null;
5892
+		$this->_cached_fields_non_db_only = null;
5893
+	}
5894
+
5895
+
5896
+
5897
+	/**
5898
+	 * _instantiate_new_instance_from_db
5899
+	 *
5900
+	 * @param string $class_name
5901
+	 * @param array  $arguments
5902
+	 * @return \EE_Base_Class
5903
+	 * @throws Exception
5904
+	 */
5905
+	public function _instantiate_new_instance_from_db($class_name, $arguments)
5906
+	{
5907
+		if ( ! class_exists($class_name)) {
5908
+			throw new EE_Error(
5909
+				sprintf(
5910
+					__('The "%s" class does not exist. Please ensure that an autoloader is set.', 'event_espresso'),
5911
+					$class_name
5912
+				)
5913
+			);
5914
+		}
5915
+		return call_user_func_array(
5916
+			array($class_name, 'new_instance'),
5917
+			array((array)$arguments, $this->_timezone, array(), true)
5918
+		);
5919
+	}
5920
+
5921
+
5922
+	/**
5923
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5924
+	 * (eg "and", "or", "not").
5925
+	 *
5926
+	 * @return array
5927
+	 */
5928
+	public function logic_query_param_keys()
5929
+	{
5930
+		return $this->_logic_query_param_keys;
5931
+	}
5932
+
5933
+
5934
+
5935
+	/**
5936
+	 * Determines whether or not the where query param array key is for a logic query param.
5937
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5938
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5939
+	 *
5940
+	 * @param $query_param_key
5941
+	 * @return bool
5942
+	 */
5943
+	public function is_logic_query_param_key($query_param_key)
5944
+	{
5945
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5946
+			if ($query_param_key === $logic_query_param_key
5947
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5948
+			) {
5949
+				return true;
5950
+			}
5951
+		}
5952
+		return false;
5953
+	}
5954 5954
 
5955 5955
 
5956 5956
 
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
     protected function __construct($timezone = null)
516 516
     {
517 517
         // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
518
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+            throw new EE_Error(
520 520
                 sprintf(
521 521
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522 522
                         'event_espresso'),
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
          *
537 537
          * @var EE_Table_Base[] $_tables
538 538
          */
539
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
539
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
540 540
         foreach ($this->_tables as $table_alias => $table_obj) {
541 541
             /** @var $table_obj EE_Table_Base */
542 542
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -551,10 +551,10 @@  discard block
 block discarded – undo
551 551
          *
552 552
          * @param EE_Model_Field_Base[] $_fields
553 553
          */
554
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
554
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
555 555
         $this->_invalidate_field_caches();
556 556
         foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
557
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
558 558
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559 559
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
560 560
             }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
          *
583 583
          * @param EE_Model_Relation_Base[] $_model_relations
584 584
          */
585
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
585
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
586 586
             $this->_model_relations);
587 587
         foreach ($this->_model_relations as $model_name => $relation_obj) {
588 588
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -594,12 +594,12 @@  discard block
 block discarded – undo
594 594
         }
595 595
         $this->set_timezone($timezone);
596 596
         //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
597
+        if ( ! $this->_default_where_conditions_strategy) {
598 598
             //nothing was set during child constructor, so set default
599 599
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600 600
         }
601 601
         $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
602
+        if ( ! $this->_minimum_where_conditions_strategy) {
603 603
             //nothing was set during child constructor, so set default
604 604
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605 605
         }
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
         //initialize the standard cap restriction generators if none were specified by the child constructor
613 613
         if ($this->_cap_restriction_generators !== false) {
614 614
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
615
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
616 616
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
617 617
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618 618
                         new EE_Restriction_Generator_Protected(),
@@ -625,10 +625,10 @@  discard block
 block discarded – undo
625 625
         //if there are cap restriction generators, use them to make the default cap restrictions
626 626
         if ($this->_cap_restriction_generators !== false) {
627 627
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
628
+                if ( ! $generator_object) {
629 629
                     continue;
630 630
                 }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
631
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
632 632
                     throw new EE_Error(
633 633
                         sprintf(
634 634
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
                     );
640 640
                 }
641 641
                 $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
642
+                if ( ! $generator_object->construction_finalized()) {
643 643
                     $generator_object->_construct_finalize($this, $action);
644 644
                 }
645 645
             }
646 646
         }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
647
+        do_action('AHEE__'.get_class($this).'__construct__end');
648 648
     }
649 649
 
650 650
 
@@ -679,7 +679,7 @@  discard block
 block discarded – undo
679 679
      */
680 680
     public static function set_model_query_blog_id($blog_id = 0)
681 681
     {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
682
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
683 683
     }
684 684
 
685 685
 
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
     public static function instance($timezone = null)
710 710
     {
711 711
         // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
712
+        if ( ! static::$_instance instanceof static) {
713 713
             // instantiate Espresso_model
714 714
             static::$_instance = new static($timezone);
715 715
         }
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
             foreach ($r->getDefaultProperties() as $property => $value) {
741 741
                 //don't set instance to null like it was originally,
742 742
                 //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
743
+                if ( ! isset($static_properties[$property])) {
744 744
                     static::$_instance->{$property} = $value;
745 745
                 }
746 746
             }
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
      */
764 764
     public function status_array($translated = false)
765 765
     {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
766
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
767 767
             return array();
768 768
         }
769 769
         $model_name = $this->get_this_model_name();
@@ -966,17 +966,17 @@  discard block
 block discarded – undo
966 966
     public function wp_user_field_name()
967 967
     {
968 968
         try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
969
+            if ( ! empty($this->_model_chain_to_wp_user)) {
970 970
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971 971
                 $last_model_name = end($models_to_follow_to_wp_users);
972 972
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
973
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
974 974
             } else {
975 975
                 $model_with_fk_to_wp_users = $this;
976 976
                 $model_chain_to_wp_user = '';
977 977
             }
978 978
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
979
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
980 980
         } catch (EE_Error $e) {
981 981
             return false;
982 982
         }
@@ -1048,12 +1048,12 @@  discard block
 block discarded – undo
1048 1048
         // remember the custom selections, if any, and type cast as array
1049 1049
         // (unless $columns_to_select is an object, then just set as an empty array)
1050 1050
         // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1051
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1052 1052
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053 1053
         $select_expressions = $columns_to_select !== null
1054 1054
             ? $this->_construct_select_from_input($columns_to_select)
1055 1055
             : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1056
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1057 1057
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058 1058
     }
1059 1059
 
@@ -1098,7 +1098,7 @@  discard block
 block discarded – undo
1098 1098
         if (is_array($columns_to_select)) {
1099 1099
             $select_sql_array = array();
1100 1100
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1101
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102 1102
                     throw new EE_Error(
1103 1103
                         sprintf(
1104 1104
                             __(
@@ -1110,7 +1110,7 @@  discard block
 block discarded – undo
1110 1110
                         )
1111 1111
                     );
1112 1112
                 }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1113
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114 1114
                     throw new EE_Error(
1115 1115
                         sprintf(
1116 1116
                             __(
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
      */
1183 1183
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184 1184
     {
1185
-        if (! isset($query_params[0])) {
1185
+        if ( ! isset($query_params[0])) {
1186 1186
             $query_params[0] = array();
1187 1187
         }
1188 1188
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1207,7 +1207,7 @@  discard block
 block discarded – undo
1207 1207
      */
1208 1208
     public function get_one($query_params = array())
1209 1209
     {
1210
-        if (! is_array($query_params)) {
1210
+        if ( ! is_array($query_params)) {
1211 1211
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1212 1212
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213 1213
                     gettype($query_params)), '4.6.0');
@@ -1375,7 +1375,7 @@  discard block
 block discarded – undo
1375 1375
                 return array();
1376 1376
             }
1377 1377
         }
1378
-        if (! is_array($query_params)) {
1378
+        if ( ! is_array($query_params)) {
1379 1379
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380 1380
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381 1381
                     gettype($query_params)), '4.6.0');
@@ -1385,7 +1385,7 @@  discard block
 block discarded – undo
1385 1385
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386 1386
         $query_params['limit'] = $limit;
1387 1387
         //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1388
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1389 1389
         $query_params['order_by'] = $operand === '>'
1390 1390
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391 1391
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1464,7 +1464,7 @@  discard block
 block discarded – undo
1464 1464
     {
1465 1465
         $field_settings = $this->field_settings_for($field_name);
1466 1466
         //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1467
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1468 1468
             throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469 1469
                 'event_espresso'), $field_name));
1470 1470
         }
@@ -1543,7 +1543,7 @@  discard block
 block discarded – undo
1543 1543
         //load EEH_DTT_Helper
1544 1544
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545 1545
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1546
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1547 1547
     }
1548 1548
 
1549 1549
 
@@ -1611,7 +1611,7 @@  discard block
 block discarded – undo
1611 1611
      */
1612 1612
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613 1613
     {
1614
-        if (! is_array($query_params)) {
1614
+        if ( ! is_array($query_params)) {
1615 1615
             EE_Error::doing_it_wrong('EEM_Base::update',
1616 1616
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617 1617
                     gettype($query_params)), '4.6.0');
@@ -1633,7 +1633,7 @@  discard block
 block discarded – undo
1633 1633
          * @param EEM_Base $model           the model being queried
1634 1634
          * @param array    $query_params    see EEM_Base::get_all()
1635 1635
          */
1636
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637 1637
             $query_params);
1638 1638
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1639 1639
         //to do that, for each table, verify that it's PK isn't null.
@@ -1647,7 +1647,7 @@  discard block
 block discarded – undo
1647 1647
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648 1648
         foreach ($wpdb_select_results as $wpdb_result) {
1649 1649
             // type cast stdClass as array
1650
-            $wpdb_result = (array)$wpdb_result;
1650
+            $wpdb_result = (array) $wpdb_result;
1651 1651
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652 1652
             if ($this->has_primary_key_field()) {
1653 1653
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1664,13 +1664,13 @@  discard block
 block discarded – undo
1664 1664
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665 1665
                     //if there is no private key for this table on the results, it means there's no entry
1666 1666
                     //in this table, right? so insert a row in the current table, using any fields available
1667
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1667
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1668 1668
                            && $wpdb_result[$this_table_pk_column])
1669 1669
                     ) {
1670 1670
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671 1671
                             $main_table_pk_value);
1672 1672
                         //if we died here, report the error
1673
-                        if (! $success) {
1673
+                        if ( ! $success) {
1674 1674
                             return false;
1675 1675
                         }
1676 1676
                     }
@@ -1701,7 +1701,7 @@  discard block
 block discarded – undo
1701 1701
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702 1702
                 }
1703 1703
             }
1704
-            if (! $model_objs_affected_ids) {
1704
+            if ( ! $model_objs_affected_ids) {
1705 1705
                 //wait wait wait- if nothing was affected let's stop here
1706 1706
                 return 0;
1707 1707
             }
@@ -1728,7 +1728,7 @@  discard block
 block discarded – undo
1728 1728
                . $model_query_info->get_full_join_sql()
1729 1729
                . " SET "
1730 1730
                . $this->_construct_update_sql($fields_n_values)
1731
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732 1732
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733 1733
         /**
1734 1734
          * Action called after a model update call has been made.
@@ -1739,7 +1739,7 @@  discard block
 block discarded – undo
1739 1739
          * @param int      $rows_affected
1740 1740
          */
1741 1741
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
-        return $rows_affected;//how many supposedly got updated
1742
+        return $rows_affected; //how many supposedly got updated
1743 1743
     }
1744 1744
 
1745 1745
 
@@ -1767,7 +1767,7 @@  discard block
 block discarded – undo
1767 1767
         }
1768 1768
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769 1769
         $select_expressions = $field->get_qualified_column();
1770
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1770
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1771 1771
         return $this->_do_wpdb_query('get_col', array($SQL));
1772 1772
     }
1773 1773
 
@@ -1785,7 +1785,7 @@  discard block
 block discarded – undo
1785 1785
     {
1786 1786
         $query_params['limit'] = 1;
1787 1787
         $col = $this->get_col($query_params, $field_to_select);
1788
-        if (! empty($col)) {
1788
+        if ( ! empty($col)) {
1789 1789
             return reset($col);
1790 1790
         } else {
1791 1791
             return null;
@@ -1817,7 +1817,7 @@  discard block
 block discarded – undo
1817 1817
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818 1818
             $value_sql = $prepared_value === null ? 'NULL'
1819 1819
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1820
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1821 1821
         }
1822 1822
         return implode(",", $cols_n_values);
1823 1823
     }
@@ -1995,7 +1995,7 @@  discard block
 block discarded – undo
1995 1995
          * @param int      $rows_deleted
1996 1996
          */
1997 1997
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1998
-        return $rows_deleted;//how many supposedly got deleted
1998
+        return $rows_deleted; //how many supposedly got deleted
1999 1999
     }
2000 2000
 
2001 2001
 
@@ -2138,7 +2138,7 @@  discard block
 block discarded – undo
2138 2138
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2139 2139
                 //make sure we have unique $ids
2140 2140
                 $ids = array_unique($ids);
2141
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2141
+                $query[] = $column.' IN('.implode(',', $ids).')';
2142 2142
             }
2143 2143
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2144 2144
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2146,9 +2146,9 @@  discard block
 block discarded – undo
2146 2146
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2147 2147
                 $values_for_each_combined_primary_key_for_a_row = array();
2148 2148
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2149
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2149
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2150 2150
                 }
2151
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2151
+                $ways_to_identify_a_row[] = '('.implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2152 2152
             }
2153 2153
             $query_part = implode(' OR ', $ways_to_identify_a_row);
2154 2154
         }
@@ -2194,9 +2194,9 @@  discard block
 block discarded – undo
2194 2194
                 $column_to_count = '*';
2195 2195
             }
2196 2196
         }
2197
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2198
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2199
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2197
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2198
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2199
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2200 2200
     }
2201 2201
 
2202 2202
 
@@ -2218,13 +2218,13 @@  discard block
 block discarded – undo
2218 2218
             $field_obj = $this->get_primary_key_field();
2219 2219
         }
2220 2220
         $column_to_count = $field_obj->get_qualified_column();
2221
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2221
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2222 2222
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2223 2223
         $data_type = $field_obj->get_wpdb_data_type();
2224 2224
         if ($data_type === '%d' || $data_type === '%s') {
2225
-            return (float)$return_value;
2225
+            return (float) $return_value;
2226 2226
         } else {//must be %f
2227
-            return (float)$return_value;
2227
+            return (float) $return_value;
2228 2228
         }
2229 2229
     }
2230 2230
 
@@ -2245,13 +2245,13 @@  discard block
 block discarded – undo
2245 2245
         //if we're in maintenance mode level 2, DON'T run any queries
2246 2246
         //because level 2 indicates the database needs updating and
2247 2247
         //is probably out of sync with the code
2248
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2248
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2249 2249
             throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2250 2250
                 "event_espresso")));
2251 2251
         }
2252 2252
         /** @type WPDB $wpdb */
2253 2253
         global $wpdb;
2254
-        if (! method_exists($wpdb, $wpdb_method)) {
2254
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2255 2255
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2256 2256
                 'event_espresso'), $wpdb_method));
2257 2257
         }
@@ -2263,7 +2263,7 @@  discard block
 block discarded – undo
2263 2263
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2264 2264
         if (WP_DEBUG) {
2265 2265
             $wpdb->show_errors($old_show_errors_value);
2266
-            if (! empty($wpdb->last_error)) {
2266
+            if ( ! empty($wpdb->last_error)) {
2267 2267
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2268 2268
             } elseif ($result === false) {
2269 2269
                 throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
@@ -2323,7 +2323,7 @@  discard block
 block discarded – undo
2323 2323
                     return $result;
2324 2324
                     break;
2325 2325
             }
2326
-            if (! empty($error_message)) {
2326
+            if ( ! empty($error_message)) {
2327 2327
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2328 2328
                 trigger_error($error_message);
2329 2329
             }
@@ -2399,11 +2399,11 @@  discard block
 block discarded – undo
2399 2399
      */
2400 2400
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2401 2401
     {
2402
-        return " FROM " . $model_query_info->get_full_join_sql() .
2403
-               $model_query_info->get_where_sql() .
2404
-               $model_query_info->get_group_by_sql() .
2405
-               $model_query_info->get_having_sql() .
2406
-               $model_query_info->get_order_by_sql() .
2402
+        return " FROM ".$model_query_info->get_full_join_sql().
2403
+               $model_query_info->get_where_sql().
2404
+               $model_query_info->get_group_by_sql().
2405
+               $model_query_info->get_having_sql().
2406
+               $model_query_info->get_order_by_sql().
2407 2407
                $model_query_info->get_limit_sql();
2408 2408
     }
2409 2409
 
@@ -2599,12 +2599,12 @@  discard block
 block discarded – undo
2599 2599
         $related_model = $this->get_related_model_obj($model_name);
2600 2600
         //we're just going to use the query params on the related model's normal get_all query,
2601 2601
         //except add a condition to say to match the current mod
2602
-        if (! isset($query_params['default_where_conditions'])) {
2602
+        if ( ! isset($query_params['default_where_conditions'])) {
2603 2603
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2604 2604
         }
2605 2605
         $this_model_name = $this->get_this_model_name();
2606 2606
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2607
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2607
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2608 2608
         return $related_model->count($query_params, $field_to_count, $distinct);
2609 2609
     }
2610 2610
 
@@ -2624,7 +2624,7 @@  discard block
 block discarded – undo
2624 2624
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2625 2625
     {
2626 2626
         $related_model = $this->get_related_model_obj($model_name);
2627
-        if (! is_array($query_params)) {
2627
+        if ( ! is_array($query_params)) {
2628 2628
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2629 2629
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2630 2630
                     gettype($query_params)), '4.6.0');
@@ -2632,12 +2632,12 @@  discard block
 block discarded – undo
2632 2632
         }
2633 2633
         //we're just going to use the query params on the related model's normal get_all query,
2634 2634
         //except add a condition to say to match the current mod
2635
-        if (! isset($query_params['default_where_conditions'])) {
2635
+        if ( ! isset($query_params['default_where_conditions'])) {
2636 2636
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2637 2637
         }
2638 2638
         $this_model_name = $this->get_this_model_name();
2639 2639
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2640
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2640
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2641 2641
         return $related_model->sum($query_params, $field_to_sum);
2642 2642
     }
2643 2643
 
@@ -2691,7 +2691,7 @@  discard block
 block discarded – undo
2691 2691
                 $field_with_model_name = $field;
2692 2692
             }
2693 2693
         }
2694
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2694
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2695 2695
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2696 2696
                 $this->get_this_model_name()));
2697 2697
         }
@@ -2724,7 +2724,7 @@  discard block
 block discarded – undo
2724 2724
          * @param array    $fields_n_values keys are the fields and values are their new values
2725 2725
          * @param EEM_Base $model           the model used
2726 2726
          */
2727
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2727
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2728 2728
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2729 2729
             $main_table = $this->_get_main_table();
2730 2730
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2832,7 +2832,7 @@  discard block
 block discarded – undo
2832 2832
         }
2833 2833
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2834 2834
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2835
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2835
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2836 2836
         }
2837 2837
         //if there is nothing to base this search on, then we shouldn't find anything
2838 2838
         if (empty($query_params)) {
@@ -2919,7 +2919,7 @@  discard block
 block discarded – undo
2919 2919
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2920 2920
             //so add the fk to the main table as a column
2921 2921
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2922
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2922
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2923 2923
         }
2924 2924
         //insert the new entry
2925 2925
         $result = $this->_do_wpdb_query('insert',
@@ -3125,7 +3125,7 @@  discard block
 block discarded – undo
3125 3125
                     $query_info_carrier,
3126 3126
                     'group_by'
3127 3127
                 );
3128
-            } elseif (! empty ($query_params['group_by'])) {
3128
+            } elseif ( ! empty ($query_params['group_by'])) {
3129 3129
                 $this->_extract_related_model_info_from_query_param(
3130 3130
                     $query_params['group_by'],
3131 3131
                     $query_info_carrier,
@@ -3147,7 +3147,7 @@  discard block
 block discarded – undo
3147 3147
                     $query_info_carrier,
3148 3148
                     'order_by'
3149 3149
                 );
3150
-            } elseif (! empty($query_params['order_by'])) {
3150
+            } elseif ( ! empty($query_params['order_by'])) {
3151 3151
                 $this->_extract_related_model_info_from_query_param(
3152 3152
                     $query_params['order_by'],
3153 3153
                     $query_info_carrier,
@@ -3182,8 +3182,8 @@  discard block
 block discarded – undo
3182 3182
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3183 3183
         $query_param_type
3184 3184
     ) {
3185
-        if (! empty($sub_query_params)) {
3186
-            $sub_query_params = (array)$sub_query_params;
3185
+        if ( ! empty($sub_query_params)) {
3186
+            $sub_query_params = (array) $sub_query_params;
3187 3187
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3188 3188
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3189 3189
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3194,7 +3194,7 @@  discard block
 block discarded – undo
3194 3194
                 //of array('Registration.TXN_ID'=>23)
3195 3195
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3196 3196
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3197
-                    if (! is_array($possibly_array_of_params)) {
3197
+                    if ( ! is_array($possibly_array_of_params)) {
3198 3198
                         throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3199 3199
                             "event_espresso"),
3200 3200
                             $param, $possibly_array_of_params));
@@ -3210,7 +3210,7 @@  discard block
 block discarded – undo
3210 3210
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3211 3211
                     //indicating that $possible_array_of_params[1] is actually a field name,
3212 3212
                     //from which we should extract query parameters!
3213
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3213
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3214 3214
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3215 3215
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3216 3216
                     }
@@ -3240,8 +3240,8 @@  discard block
 block discarded – undo
3240 3240
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3241 3241
         $query_param_type
3242 3242
     ) {
3243
-        if (! empty($sub_query_params)) {
3244
-            if (! is_array($sub_query_params)) {
3243
+        if ( ! empty($sub_query_params)) {
3244
+            if ( ! is_array($sub_query_params)) {
3245 3245
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3246 3246
                     $sub_query_params));
3247 3247
             }
@@ -3270,7 +3270,7 @@  discard block
 block discarded – undo
3270 3270
      */
3271 3271
     public function _create_model_query_info_carrier($query_params)
3272 3272
     {
3273
-        if (! is_array($query_params)) {
3273
+        if ( ! is_array($query_params)) {
3274 3274
             EE_Error::doing_it_wrong(
3275 3275
                 'EEM_Base::_create_model_query_info_carrier',
3276 3276
                 sprintf(
@@ -3346,7 +3346,7 @@  discard block
 block discarded – undo
3346 3346
         //set limit
3347 3347
         if (array_key_exists('limit', $query_params)) {
3348 3348
             if (is_array($query_params['limit'])) {
3349
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3349
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3350 3350
                     $e = sprintf(
3351 3351
                         __(
3352 3352
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3354,12 +3354,12 @@  discard block
 block discarded – undo
3354 3354
                         ),
3355 3355
                         http_build_query($query_params['limit'])
3356 3356
                     );
3357
-                    throw new EE_Error($e . "|" . $e);
3357
+                    throw new EE_Error($e."|".$e);
3358 3358
                 }
3359 3359
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3360
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3361
-            } elseif (! empty ($query_params['limit'])) {
3362
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3360
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3361
+            } elseif ( ! empty ($query_params['limit'])) {
3362
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3363 3363
             }
3364 3364
         }
3365 3365
         //set order by
@@ -3391,10 +3391,10 @@  discard block
 block discarded – undo
3391 3391
                 $order_array = array();
3392 3392
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3393 3393
                     $order = $this->_extract_order($order);
3394
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3394
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3395 3395
                 }
3396
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3397
-            } elseif (! empty ($query_params['order_by'])) {
3396
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3397
+            } elseif ( ! empty ($query_params['order_by'])) {
3398 3398
                 $this->_extract_related_model_info_from_query_param(
3399 3399
                     $query_params['order_by'],
3400 3400
                     $query_object,
@@ -3405,18 +3405,18 @@  discard block
 block discarded – undo
3405 3405
                     ? $this->_extract_order($query_params['order'])
3406 3406
                     : 'DESC';
3407 3407
                 $query_object->set_order_by_sql(
3408
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3408
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3409 3409
                 );
3410 3410
             }
3411 3411
         }
3412 3412
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3413
-        if (! array_key_exists('order_by', $query_params)
3413
+        if ( ! array_key_exists('order_by', $query_params)
3414 3414
             && array_key_exists('order', $query_params)
3415 3415
             && ! empty($query_params['order'])
3416 3416
         ) {
3417 3417
             $pk_field = $this->get_primary_key_field();
3418 3418
             $order = $this->_extract_order($query_params['order']);
3419
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3419
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3420 3420
         }
3421 3421
         //set group by
3422 3422
         if (array_key_exists('group_by', $query_params)) {
@@ -3426,10 +3426,10 @@  discard block
 block discarded – undo
3426 3426
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3427 3427
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3428 3428
                 }
3429
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3430
-            } elseif (! empty ($query_params['group_by'])) {
3429
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3430
+            } elseif ( ! empty ($query_params['group_by'])) {
3431 3431
                 $query_object->set_group_by_sql(
3432
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3432
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3433 3433
                 );
3434 3434
             }
3435 3435
         }
@@ -3439,7 +3439,7 @@  discard block
 block discarded – undo
3439 3439
         }
3440 3440
         //now, just verify they didn't pass anything wack
3441 3441
         foreach ($query_params as $query_key => $query_value) {
3442
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3442
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3443 3443
                 throw new EE_Error(
3444 3444
                     sprintf(
3445 3445
                         __(
@@ -3533,22 +3533,22 @@  discard block
 block discarded – undo
3533 3533
         $where_query_params = array()
3534 3534
     ) {
3535 3535
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3536
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3536
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3537 3537
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3538 3538
                 "event_espresso"), $use_default_where_conditions,
3539 3539
                 implode(", ", $allowed_used_default_where_conditions_values)));
3540 3540
         }
3541 3541
         $universal_query_params = array();
3542
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3542
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3543 3543
             $universal_query_params = $this->_get_default_where_conditions();
3544
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3544
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3545 3545
             $universal_query_params = $this->_get_minimum_where_conditions();
3546 3546
         }
3547 3547
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3548 3548
             $related_model = $this->get_related_model_obj($model_name);
3549
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3549
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3550 3550
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3551
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3551
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3552 3552
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3553 3553
             } else {
3554 3554
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3581,7 +3581,7 @@  discard block
 block discarded – undo
3581 3581
      * @param bool $for_this_model false means this is for OTHER related models
3582 3582
      * @return bool
3583 3583
      */
3584
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3584
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3585 3585
     {
3586 3586
         return (
3587 3587
                    $for_this_model
@@ -3660,7 +3660,7 @@  discard block
 block discarded – undo
3660 3660
     ) {
3661 3661
         $null_friendly_where_conditions = array();
3662 3662
         $none_overridden = true;
3663
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3663
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3664 3664
         foreach ($default_where_conditions as $key => $val) {
3665 3665
             if (isset($provided_where_conditions[$key])) {
3666 3666
                 $none_overridden = false;
@@ -3778,7 +3778,7 @@  discard block
 block discarded – undo
3778 3778
             foreach ($tables as $table_obj) {
3779 3779
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3780 3780
                                        . $table_obj->get_fully_qualified_pk_column();
3781
-                if (! in_array($qualified_pk_column, $selects)) {
3781
+                if ( ! in_array($qualified_pk_column, $selects)) {
3782 3782
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3783 3783
                 }
3784 3784
             }
@@ -3864,9 +3864,9 @@  discard block
 block discarded – undo
3864 3864
         //and
3865 3865
         //check if it's a field on a related model
3866 3866
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3867
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3867
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3868 3868
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3869
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3869
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3870 3870
                 if ($query_param === '') {
3871 3871
                     //nothing left to $query_param
3872 3872
                     //we should actually end in a field name, not a model like this!
@@ -3952,7 +3952,7 @@  discard block
 block discarded – undo
3952 3952
     {
3953 3953
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3954 3954
         if ($SQL) {
3955
-            return " WHERE " . $SQL;
3955
+            return " WHERE ".$SQL;
3956 3956
         } else {
3957 3957
             return '';
3958 3958
         }
@@ -3972,7 +3972,7 @@  discard block
 block discarded – undo
3972 3972
     {
3973 3973
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3974 3974
         if ($SQL) {
3975
-            return " HAVING " . $SQL;
3975
+            return " HAVING ".$SQL;
3976 3976
         } else {
3977 3977
             return '';
3978 3978
         }
@@ -3992,11 +3992,11 @@  discard block
 block discarded – undo
3992 3992
      */
3993 3993
     protected function _get_field_on_model($field_name, $model_name)
3994 3994
     {
3995
-        $model_class = 'EEM_' . $model_name;
3996
-        $model_filepath = $model_class . ".model.php";
3995
+        $model_class = 'EEM_'.$model_name;
3996
+        $model_filepath = $model_class.".model.php";
3997 3997
         if (is_readable($model_filepath)) {
3998 3998
             require_once($model_filepath);
3999
-            $model_instance = call_user_func($model_name . "::instance");
3999
+            $model_instance = call_user_func($model_name."::instance");
4000 4000
             /* @var $model_instance EEM_Base */
4001 4001
             return $model_instance->field_settings_for($field_name);
4002 4002
         } else {
@@ -4020,7 +4020,7 @@  discard block
 block discarded – undo
4020 4020
     {
4021 4021
         $where_clauses = array();
4022 4022
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4023
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4023
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4024 4024
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4025 4025
                 switch ($query_param) {
4026 4026
                     case 'not':
@@ -4048,7 +4048,7 @@  discard block
 block discarded – undo
4048 4048
             } else {
4049 4049
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4050 4050
                 //if it's not a normal field, maybe it's a custom selection?
4051
-                if (! $field_obj) {
4051
+                if ( ! $field_obj) {
4052 4052
                     if (isset($this->_custom_selections[$query_param][1])) {
4053 4053
                         $field_obj = $this->_custom_selections[$query_param][1];
4054 4054
                     } else {
@@ -4057,7 +4057,7 @@  discard block
 block discarded – undo
4057 4057
                     }
4058 4058
                 }
4059 4059
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4060
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4060
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4061 4061
             }
4062 4062
         }
4063 4063
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4078,7 +4078,7 @@  discard block
 block discarded – undo
4078 4078
         if ($field) {
4079 4079
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4080 4080
                 $query_param);
4081
-            return $table_alias_prefix . $field->get_qualified_column();
4081
+            return $table_alias_prefix.$field->get_qualified_column();
4082 4082
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4083 4083
             //maybe it's custom selection item?
4084 4084
             //if so, just use it as the "column name"
@@ -4125,7 +4125,7 @@  discard block
 block discarded – undo
4125 4125
     {
4126 4126
         if (is_array($op_and_value)) {
4127 4127
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4128
-            if (! $operator) {
4128
+            if ( ! $operator) {
4129 4129
                 $php_array_like_string = array();
4130 4130
                 foreach ($op_and_value as $key => $value) {
4131 4131
                     $php_array_like_string[] = "$key=>$value";
@@ -4147,13 +4147,13 @@  discard block
 block discarded – undo
4147 4147
         }
4148 4148
         //check to see if the value is actually another field
4149 4149
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4150
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4150
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4151 4151
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4152 4152
             //in this case, the value should be an array, or at least a comma-separated list
4153 4153
             //it will need to handle a little differently
4154 4154
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4155 4155
             //note: $cleaned_value has already been run through $wpdb->prepare()
4156
-            return $operator . SP . $cleaned_value;
4156
+            return $operator.SP.$cleaned_value;
4157 4157
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4158 4158
             //the value should be an array with count of two.
4159 4159
             if (count($value) !== 2) {
@@ -4168,7 +4168,7 @@  discard block
 block discarded – undo
4168 4168
                 );
4169 4169
             }
4170 4170
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4171
-            return $operator . SP . $cleaned_value;
4171
+            return $operator.SP.$cleaned_value;
4172 4172
         } elseif (in_array($operator, $this->_null_style_operators)) {
4173 4173
             if ($value !== null) {
4174 4174
                 throw new EE_Error(
@@ -4186,9 +4186,9 @@  discard block
 block discarded – undo
4186 4186
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
4187 4187
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4188 4188
             //remove other junk. So just treat it as a string.
4189
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4190
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4191
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4189
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4190
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4191
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4192 4192
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4193 4193
             throw new EE_Error(
4194 4194
                 sprintf(
@@ -4200,7 +4200,7 @@  discard block
 block discarded – undo
4200 4200
                     $operator
4201 4201
                 )
4202 4202
             );
4203
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4203
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4204 4204
             throw new EE_Error(
4205 4205
                 sprintf(
4206 4206
                     __(
@@ -4241,7 +4241,7 @@  discard block
 block discarded – undo
4241 4241
         foreach ($values as $value) {
4242 4242
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4243 4243
         }
4244
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4244
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4245 4245
     }
4246 4246
 
4247 4247
 
@@ -4282,7 +4282,7 @@  discard block
 block discarded – undo
4282 4282
                                 . $main_table->get_table_name()
4283 4283
                                 . " WHERE FALSE";
4284 4284
         }
4285
-        return "(" . implode(",", $cleaned_values) . ")";
4285
+        return "(".implode(",", $cleaned_values).")";
4286 4286
     }
4287 4287
 
4288 4288
 
@@ -4301,7 +4301,7 @@  discard block
 block discarded – undo
4301 4301
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4302 4302
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4303 4303
         } else {//$field_obj should really just be a data type
4304
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4304
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4305 4305
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4306 4306
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4307 4307
             }
@@ -4421,10 +4421,10 @@  discard block
 block discarded – undo
4421 4421
      */
4422 4422
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4423 4423
     {
4424
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4424
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4425 4425
         $qualified_columns = array();
4426 4426
         foreach ($this->field_settings() as $field_name => $field) {
4427
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4427
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4428 4428
         }
4429 4429
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4430 4430
     }
@@ -4448,11 +4448,11 @@  discard block
 block discarded – undo
4448 4448
             if ($table_obj instanceof EE_Primary_Table) {
4449 4449
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4450 4450
                     ? $table_obj->get_select_join_limit($limit)
4451
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4451
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4452 4452
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4453 4453
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4454 4454
                     ? $table_obj->get_select_join_limit_join($limit)
4455
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4455
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4456 4456
             }
4457 4457
         }
4458 4458
         return $SQL;
@@ -4540,12 +4540,12 @@  discard block
 block discarded – undo
4540 4540
      */
4541 4541
     public function get_related_model_obj($model_name)
4542 4542
     {
4543
-        $model_classname = "EEM_" . $model_name;
4544
-        if (! class_exists($model_classname)) {
4543
+        $model_classname = "EEM_".$model_name;
4544
+        if ( ! class_exists($model_classname)) {
4545 4545
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4546 4546
                 'event_espresso'), $model_name, $model_classname));
4547 4547
         }
4548
-        return call_user_func($model_classname . "::instance");
4548
+        return call_user_func($model_classname."::instance");
4549 4549
     }
4550 4550
 
4551 4551
 
@@ -4592,7 +4592,7 @@  discard block
 block discarded – undo
4592 4592
     public function related_settings_for($relation_name)
4593 4593
     {
4594 4594
         $relatedModels = $this->relation_settings();
4595
-        if (! array_key_exists($relation_name, $relatedModels)) {
4595
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4596 4596
             throw new EE_Error(
4597 4597
                 sprintf(
4598 4598
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4619,7 +4619,7 @@  discard block
 block discarded – undo
4619 4619
     public function field_settings_for($fieldName)
4620 4620
     {
4621 4621
         $fieldSettings = $this->field_settings(true);
4622
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4622
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4623 4623
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4624 4624
                 get_class($this)));
4625 4625
         }
@@ -4694,7 +4694,7 @@  discard block
 block discarded – undo
4694 4694
                     break;
4695 4695
                 }
4696 4696
             }
4697
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4697
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4698 4698
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4699 4699
                     get_class($this)));
4700 4700
             }
@@ -4753,7 +4753,7 @@  discard block
 block discarded – undo
4753 4753
      */
4754 4754
     public function get_foreign_key_to($model_name)
4755 4755
     {
4756
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4756
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4757 4757
             foreach ($this->field_settings() as $field) {
4758 4758
                 if (
4759 4759
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4763,7 +4763,7 @@  discard block
 block discarded – undo
4763 4763
                     break;
4764 4764
                 }
4765 4765
             }
4766
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4766
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4767 4767
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4768 4768
                     'event_espresso'), $model_name, get_class($this)));
4769 4769
             }
@@ -4814,7 +4814,7 @@  discard block
 block discarded – undo
4814 4814
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4815 4815
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4816 4816
                         /** @var $field_obj EE_Model_Field_Base */
4817
-                        if (! $field_obj->is_db_only_field()) {
4817
+                        if ( ! $field_obj->is_db_only_field()) {
4818 4818
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4819 4819
                         }
4820 4820
                     }
@@ -4844,7 +4844,7 @@  discard block
 block discarded – undo
4844 4844
         $count_if_model_has_no_primary_key = 0;
4845 4845
         $has_primary_key = $this->has_primary_key_field();
4846 4846
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4847
-        foreach ((array)$rows as $row) {
4847
+        foreach ((array) $rows as $row) {
4848 4848
             if (empty($row)) {
4849 4849
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4850 4850
                 return array();
@@ -4862,7 +4862,7 @@  discard block
 block discarded – undo
4862 4862
                 }
4863 4863
             }
4864 4864
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4865
-            if (! $classInstance) {
4865
+            if ( ! $classInstance) {
4866 4866
                 throw new EE_Error(
4867 4867
                     sprintf(
4868 4868
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4934,7 +4934,7 @@  discard block
 block discarded – undo
4934 4934
      */
4935 4935
     public function instantiate_class_from_array_or_object($cols_n_values)
4936 4936
     {
4937
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4937
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4938 4938
             $cols_n_values = get_object_vars($cols_n_values);
4939 4939
         }
4940 4940
         $primary_key = null;
@@ -4958,7 +4958,7 @@  discard block
 block discarded – undo
4958 4958
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4959 4959
         if ($primary_key) {
4960 4960
             $classInstance = $this->get_from_entity_map($primary_key);
4961
-            if (! $classInstance) {
4961
+            if ( ! $classInstance) {
4962 4962
                 $classInstance = $this->_instantiate_new_instance_from_db(
4963 4963
                     $this->_get_class_name(),
4964 4964
                     $this_model_fields_n_values
@@ -5016,12 +5016,12 @@  discard block
 block discarded – undo
5016 5016
     public function add_to_entity_map(EE_Base_Class $object)
5017 5017
     {
5018 5018
         $className = $this->_get_class_name();
5019
-        if (! $object instanceof $className) {
5019
+        if ( ! $object instanceof $className) {
5020 5020
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5021 5021
                 is_object($object) ? get_class($object) : $object, $className));
5022 5022
         }
5023 5023
         /** @var $object EE_Base_Class */
5024
-        if (! $object->ID()) {
5024
+        if ( ! $object->ID()) {
5025 5025
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5026 5026
                 "event_espresso"), get_class($this)));
5027 5027
         }
@@ -5091,7 +5091,7 @@  discard block
 block discarded – undo
5091 5091
             //there is a primary key on this table and its not set. Use defaults for all its columns
5092 5092
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5093 5093
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5094
-                    if (! $field_obj->is_db_only_field()) {
5094
+                    if ( ! $field_obj->is_db_only_field()) {
5095 5095
                         //prepare field as if its coming from db
5096 5096
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5097 5097
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5100,7 +5100,7 @@  discard block
 block discarded – undo
5100 5100
             } else {
5101 5101
                 //the table's rows existed. Use their values
5102 5102
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5103
-                    if (! $field_obj->is_db_only_field()) {
5103
+                    if ( ! $field_obj->is_db_only_field()) {
5104 5104
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5105 5105
                             $cols_n_values, $field_obj->get_qualified_column(),
5106 5106
                             $field_obj->get_table_column()
@@ -5217,7 +5217,7 @@  discard block
 block discarded – undo
5217 5217
      */
5218 5218
     private function _get_class_name()
5219 5219
     {
5220
-        return "EE_" . $this->get_this_model_name();
5220
+        return "EE_".$this->get_this_model_name();
5221 5221
     }
5222 5222
 
5223 5223
 
@@ -5232,7 +5232,7 @@  discard block
 block discarded – undo
5232 5232
      */
5233 5233
     public function item_name($quantity = 1)
5234 5234
     {
5235
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5235
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5236 5236
     }
5237 5237
 
5238 5238
 
@@ -5265,7 +5265,7 @@  discard block
 block discarded – undo
5265 5265
     {
5266 5266
         $className = get_class($this);
5267 5267
         $tagName = "FHEE__{$className}__{$methodName}";
5268
-        if (! has_filter($tagName)) {
5268
+        if ( ! has_filter($tagName)) {
5269 5269
             throw new EE_Error(
5270 5270
                 sprintf(
5271 5271
                     __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
@@ -5491,7 +5491,7 @@  discard block
 block discarded – undo
5491 5491
         $key_vals_in_combined_pk = array();
5492 5492
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5493 5493
         foreach ($key_fields as $key_field_name => $field_obj) {
5494
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5494
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5495 5495
                 return null;
5496 5496
             }
5497 5497
         }
@@ -5512,7 +5512,7 @@  discard block
 block discarded – undo
5512 5512
     {
5513 5513
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5514 5514
         foreach ($keys_it_should_have as $key) {
5515
-            if (! isset($key_vals[$key])) {
5515
+            if ( ! isset($key_vals[$key])) {
5516 5516
                 return false;
5517 5517
             }
5518 5518
         }
@@ -5566,7 +5566,7 @@  discard block
 block discarded – undo
5566 5566
      */
5567 5567
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5568 5568
     {
5569
-        if (! is_array($query_params)) {
5569
+        if ( ! is_array($query_params)) {
5570 5570
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5571 5571
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5572 5572
                     gettype($query_params)), '4.6.0');
@@ -5658,7 +5658,7 @@  discard block
 block discarded – undo
5658 5658
      */
5659 5659
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5660 5660
     {
5661
-        if (! $this->has_primary_key_field()) {
5661
+        if ( ! $this->has_primary_key_field()) {
5662 5662
             if (WP_DEBUG) {
5663 5663
                 EE_Error::add_error(
5664 5664
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5671,7 +5671,7 @@  discard block
 block discarded – undo
5671 5671
         $IDs = array();
5672 5672
         foreach ($model_objects as $model_object) {
5673 5673
             $id = $model_object->ID();
5674
-            if (! $id) {
5674
+            if ( ! $id) {
5675 5675
                 if ($filter_out_empty_ids) {
5676 5676
                     continue;
5677 5677
                 }
@@ -5767,8 +5767,8 @@  discard block
 block discarded – undo
5767 5767
         $missing_caps = array();
5768 5768
         $cap_restrictions = $this->cap_restrictions($context);
5769 5769
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5770
-            if (! EE_Capabilities::instance()
5771
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5770
+            if ( ! EE_Capabilities::instance()
5771
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5772 5772
             ) {
5773 5773
                 $missing_caps[$cap] = $restriction_if_no_cap;
5774 5774
             }
@@ -5914,7 +5914,7 @@  discard block
 block discarded – undo
5914 5914
         }
5915 5915
         return call_user_func_array(
5916 5916
             array($class_name, 'new_instance'),
5917
-            array((array)$arguments, $this->_timezone, array(), true)
5917
+            array((array) $arguments, $this->_timezone, array(), true)
5918 5918
         );
5919 5919
     }
5920 5920
 
@@ -5944,7 +5944,7 @@  discard block
 block discarded – undo
5944 5944
     {
5945 5945
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5946 5946
             if ($query_param_key === $logic_query_param_key
5947
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5947
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
5948 5948
             ) {
5949 5949
                 return true;
5950 5950
             }
Please login to merge, or discard this patch.
core/EE_Registry.core.php 3 patches
Doc Comments   +1 added lines, -4 removed lines patch added patch discarded remove patch
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
 
271 271
 
272 272
     /**
273
-     * @param $module
273
+     * @param string $module
274 274
      * @throws EE_Error
275 275
      * @throws ReflectionException
276 276
      */
@@ -636,8 +636,6 @@  discard block
 block discarded – undo
636 636
      * @param bool|string $class_name   Fully Qualified Class Name
637 637
      * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
638 638
      * @param bool        $cache        whether to cache the instantiated object for reuse
639
-     * @param bool        $from_db      some classes are instantiated from the db
640
-     *                                  and thus call a different method to instantiate
641 639
      * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
642 640
      * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
643 641
      * @return bool|null|object null = failure to load or instantiate class object.
@@ -957,7 +955,6 @@  discard block
 block discarded – undo
957 955
      * @param string $class_name
958 956
      * @param array  $arguments
959 957
      * @param string $type
960
-     * @param bool   $from_db
961 958
      * @return null|object
962 959
      * @throws EE_Error
963 960
      * @throws ReflectionException
Please login to merge, or discard this patch.
Indentation   +1439 added lines, -1439 removed lines patch added patch discarded remove patch
@@ -20,1445 +20,1445 @@
 block discarded – undo
20 20
 class EE_Registry implements ResettableInterface
21 21
 {
22 22
 
23
-    /**
24
-     * @var EE_Registry $_instance
25
-     */
26
-    private static $_instance;
27
-
28
-    /**
29
-     * @var EE_Dependency_Map $_dependency_map
30
-     */
31
-    protected $_dependency_map;
32
-
33
-    /**
34
-     * @var array $_class_abbreviations
35
-     */
36
-    protected $_class_abbreviations = array();
37
-
38
-    /**
39
-     * @var CommandBusInterface $BUS
40
-     */
41
-    public $BUS;
42
-
43
-    /**
44
-     * @var EE_Cart $CART
45
-     */
46
-    public $CART;
47
-
48
-    /**
49
-     * @var EE_Config $CFG
50
-     */
51
-    public $CFG;
52
-
53
-    /**
54
-     * @var EE_Network_Config $NET_CFG
55
-     */
56
-    public $NET_CFG;
57
-
58
-    /**
59
-     * StdClass object for storing library classes in
60
-     *
61
-     * @var StdClass $LIB
62
-     */
63
-    public $LIB;
64
-
65
-    /**
66
-     * @var EE_Request_Handler $REQ
67
-     */
68
-    public $REQ;
69
-
70
-    /**
71
-     * @var EE_Session $SSN
72
-     */
73
-    public $SSN;
74
-
75
-    /**
76
-     * @since 4.5.0
77
-     * @var EE_Capabilities $CAP
78
-     */
79
-    public $CAP;
80
-
81
-    /**
82
-     * @since 4.9.0
83
-     * @var EE_Message_Resource_Manager $MRM
84
-     */
85
-    public $MRM;
86
-
87
-
88
-    /**
89
-     * @var Registry $AssetsRegistry
90
-     */
91
-    public $AssetsRegistry;
92
-
93
-    /**
94
-     * StdClass object for holding addons which have registered themselves to work with EE core
95
-     *
96
-     * @var EE_Addon[] $addons
97
-     */
98
-    public $addons;
99
-
100
-    /**
101
-     * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
102
-     *
103
-     * @var EEM_Base[] $models
104
-     */
105
-    public $models = array();
106
-
107
-    /**
108
-     * @var EED_Module[] $modules
109
-     */
110
-    public $modules;
111
-
112
-    /**
113
-     * @var EES_Shortcode[] $shortcodes
114
-     */
115
-    public $shortcodes;
116
-
117
-    /**
118
-     * @var WP_Widget[] $widgets
119
-     */
120
-    public $widgets;
121
-
122
-    /**
123
-     * this is an array of all implemented model names (i.e. not the parent abstract models, or models
124
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
125
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
126
-     * classnames (eg "EEM_Event")
127
-     *
128
-     * @var array $non_abstract_db_models
129
-     */
130
-    public $non_abstract_db_models = array();
131
-
132
-
133
-    /**
134
-     * internationalization for JS strings
135
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
136
-     *    in js file:  var translatedString = eei18n.string_key;
137
-     *
138
-     * @var array $i18n_js_strings
139
-     */
140
-    public static $i18n_js_strings = array();
141
-
142
-
143
-    /**
144
-     * $main_file - path to espresso.php
145
-     *
146
-     * @var array $main_file
147
-     */
148
-    public $main_file;
149
-
150
-    /**
151
-     * array of ReflectionClass objects where the key is the class name
152
-     *
153
-     * @var ReflectionClass[] $_reflectors
154
-     */
155
-    public $_reflectors;
156
-
157
-    /**
158
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
159
-     *
160
-     * @var boolean $_cache_on
161
-     */
162
-    protected $_cache_on = true;
163
-
164
-
165
-
166
-    /**
167
-     * @singleton method used to instantiate class object
168
-     * @param  EE_Dependency_Map $dependency_map
169
-     * @return EE_Registry instance
170
-     */
171
-    public static function instance(EE_Dependency_Map $dependency_map = null)
172
-    {
173
-        // check if class object is instantiated
174
-        if (! self::$_instance instanceof EE_Registry) {
175
-            self::$_instance = new self($dependency_map);
176
-        }
177
-        return self::$_instance;
178
-    }
179
-
180
-
181
-
182
-    /**
183
-     * protected constructor to prevent direct creation
184
-     *
185
-     * @Constructor
186
-     * @param  EE_Dependency_Map $dependency_map
187
-     */
188
-    protected function __construct(EE_Dependency_Map $dependency_map)
189
-    {
190
-        $this->_dependency_map = $dependency_map;
191
-        $this->LIB = new stdClass();
192
-        $this->addons = new stdClass();
193
-        $this->modules = new stdClass();
194
-        $this->shortcodes = new stdClass();
195
-        $this->widgets = new stdClass();
196
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
197
-    }
198
-
199
-
200
-
201
-    /**
202
-     * initialize
203
-     *
204
-     * @throws EE_Error
205
-     * @throws ReflectionException
206
-     */
207
-    public function initialize()
208
-    {
209
-        $this->_class_abbreviations = apply_filters(
210
-            'FHEE__EE_Registry____construct___class_abbreviations',
211
-            array(
212
-                'EE_Config'                                       => 'CFG',
213
-                'EE_Session'                                      => 'SSN',
214
-                'EE_Capabilities'                                 => 'CAP',
215
-                'EE_Cart'                                         => 'CART',
216
-                'EE_Network_Config'                               => 'NET_CFG',
217
-                'EE_Request_Handler'                              => 'REQ',
218
-                'EE_Message_Resource_Manager'                     => 'MRM',
219
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
220
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
221
-            )
222
-        );
223
-        $this->load_core('Base', array(), true);
224
-        // add our request and response objects to the cache
225
-        $request_loader = $this->_dependency_map->class_loader('EE_Request');
226
-        $this->_set_cached_class(
227
-            $request_loader(),
228
-            'EE_Request'
229
-        );
230
-        $response_loader = $this->_dependency_map->class_loader('EE_Response');
231
-        $this->_set_cached_class(
232
-            $response_loader(),
233
-            'EE_Response'
234
-        );
235
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
236
-    }
237
-
238
-
239
-
240
-    /**
241
-     * @return void
242
-     */
243
-    public function init()
244
-    {
245
-        // Get current page protocol
246
-        $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
247
-        // Output admin-ajax.php URL with same protocol as current page
248
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
249
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
250
-    }
251
-
252
-
253
-
254
-    /**
255
-     * localize_i18n_js_strings
256
-     *
257
-     * @return string
258
-     */
259
-    public static function localize_i18n_js_strings()
260
-    {
261
-        $i18n_js_strings = (array)self::$i18n_js_strings;
262
-        foreach ($i18n_js_strings as $key => $value) {
263
-            if (is_scalar($value)) {
264
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
265
-            }
266
-        }
267
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
268
-    }
269
-
270
-
271
-
272
-    /**
273
-     * @param $module
274
-     * @throws EE_Error
275
-     * @throws ReflectionException
276
-     */
277
-    public function add_module($module)
278
-    {
279
-        if ($module instanceof EED_Module) {
280
-            $module_class = get_class($module);
281
-            $this->modules->{$module_class} = $module;
282
-        } else {
283
-            if (! class_exists('EE_Module_Request_Router')) {
284
-                $this->load_core('Module_Request_Router');
285
-            }
286
-            EE_Module_Request_Router::module_factory($module);
287
-        }
288
-    }
289
-
290
-
291
-
292
-    /**
293
-     * @param string $module_name
294
-     * @return mixed EED_Module | NULL
295
-     */
296
-    public function get_module($module_name = '')
297
-    {
298
-        return isset($this->modules->{$module_name})
299
-            ? $this->modules->{$module_name}
300
-            : null;
301
-    }
302
-
303
-
304
-
305
-    /**
306
-     * loads core classes - must be singletons
307
-     *
308
-     * @param string $class_name - simple class name ie: session
309
-     * @param mixed  $arguments
310
-     * @param bool   $load_only
311
-     * @return mixed
312
-     * @throws EE_Error
313
-     * @throws ReflectionException
314
-     */
315
-    public function load_core($class_name, $arguments = array(), $load_only = false)
316
-    {
317
-        $core_paths = apply_filters(
318
-            'FHEE__EE_Registry__load_core__core_paths',
319
-            array(
320
-                EE_CORE,
321
-                EE_ADMIN,
322
-                EE_CPTS,
323
-                EE_CORE . 'data_migration_scripts' . DS,
324
-                EE_CORE . 'capabilities' . DS,
325
-                EE_CORE . 'request_stack' . DS,
326
-                EE_CORE . 'middleware' . DS,
327
-            )
328
-        );
329
-        // retrieve instantiated class
330
-        return $this->_load(
331
-            $core_paths,
332
-            'EE_',
333
-            $class_name,
334
-            'core',
335
-            $arguments,
336
-            true,
337
-            $load_only
338
-        );
339
-    }
340
-
341
-
342
-
343
-    /**
344
-     * loads service classes
345
-     *
346
-     * @param string $class_name - simple class name ie: session
347
-     * @param mixed  $arguments
348
-     * @param bool   $load_only
349
-     * @return mixed
350
-     * @throws EE_Error
351
-     * @throws ReflectionException
352
-     */
353
-    public function load_service($class_name, $arguments = array(), $load_only = false)
354
-    {
355
-        $service_paths = apply_filters(
356
-            'FHEE__EE_Registry__load_service__service_paths',
357
-            array(
358
-                EE_CORE . 'services' . DS,
359
-            )
360
-        );
361
-        // retrieve instantiated class
362
-        return $this->_load(
363
-            $service_paths,
364
-            'EE_',
365
-            $class_name,
366
-            'class',
367
-            $arguments,
368
-            true,
369
-            $load_only
370
-        );
371
-    }
372
-
373
-
374
-
375
-    /**
376
-     * loads data_migration_scripts
377
-     *
378
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
379
-     * @param mixed  $arguments
380
-     * @return EE_Data_Migration_Script_Base|mixed
381
-     * @throws EE_Error
382
-     * @throws ReflectionException
383
-     */
384
-    public function load_dms($class_name, $arguments = array())
385
-    {
386
-        // retrieve instantiated class
387
-        return $this->_load(
388
-            EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
389
-            'EE_DMS_',
390
-            $class_name,
391
-            'dms',
392
-            $arguments,
393
-            false
394
-        );
395
-    }
396
-
397
-
398
-
399
-    /**
400
-     * loads object creating classes - must be singletons
401
-     *
402
-     * @param string $class_name - simple class name ie: attendee
403
-     * @param mixed  $arguments  - an array of arguments to pass to the class
404
-     * @param bool   $from_db    - deprecated
405
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
406
-     *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
407
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
408
-     *                           (default)
409
-     * @return EE_Base_Class | bool
410
-     * @throws EE_Error
411
-     * @throws ReflectionException
412
-     */
413
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
414
-    {
415
-        $paths = apply_filters(
416
-            'FHEE__EE_Registry__load_class__paths', array(
417
-            EE_CORE,
418
-            EE_CLASSES,
419
-            EE_BUSINESS,
420
-        )
421
-        );
422
-        // retrieve instantiated class
423
-        return $this->_load(
424
-            $paths,
425
-            'EE_',
426
-            $class_name,
427
-            'class',
428
-            $arguments,
429
-            $cache,
430
-            $load_only
431
-        );
432
-    }
433
-
434
-
435
-
436
-    /**
437
-     * loads helper classes - must be singletons
438
-     *
439
-     * @param string $class_name - simple class name ie: price
440
-     * @param mixed  $arguments
441
-     * @param bool   $load_only
442
-     * @return EEH_Base | bool
443
-     * @throws EE_Error
444
-     * @throws ReflectionException
445
-     */
446
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
447
-    {
448
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
449
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
450
-        // retrieve instantiated class
451
-        return $this->_load(
452
-            $helper_paths,
453
-            'EEH_',
454
-            $class_name,
455
-            'helper',
456
-            $arguments,
457
-            true,
458
-            $load_only
459
-        );
460
-    }
461
-
462
-
463
-
464
-    /**
465
-     * loads core classes - must be singletons
466
-     *
467
-     * @param string $class_name - simple class name ie: session
468
-     * @param mixed  $arguments
469
-     * @param bool   $load_only
470
-     * @param bool   $cache      whether to cache the object or not.
471
-     * @return mixed
472
-     * @throws EE_Error
473
-     * @throws ReflectionException
474
-     */
475
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
476
-    {
477
-        $paths = array(
478
-            EE_LIBRARIES,
479
-            EE_LIBRARIES . 'messages' . DS,
480
-            EE_LIBRARIES . 'shortcodes' . DS,
481
-            EE_LIBRARIES . 'qtips' . DS,
482
-            EE_LIBRARIES . 'payment_methods' . DS,
483
-        );
484
-        // retrieve instantiated class
485
-        return $this->_load(
486
-            $paths,
487
-            'EE_',
488
-            $class_name,
489
-            'lib',
490
-            $arguments,
491
-            $cache,
492
-            $load_only
493
-        );
494
-    }
495
-
496
-
497
-
498
-    /**
499
-     * loads model classes - must be singletons
500
-     *
501
-     * @param string $class_name - simple class name ie: price
502
-     * @param mixed  $arguments
503
-     * @param bool   $load_only
504
-     * @return EEM_Base | bool
505
-     * @throws EE_Error
506
-     * @throws ReflectionException
507
-     */
508
-    public function load_model($class_name, $arguments = array(), $load_only = false)
509
-    {
510
-        $paths = apply_filters(
511
-            'FHEE__EE_Registry__load_model__paths', array(
512
-            EE_MODELS,
513
-            EE_CORE,
514
-        )
515
-        );
516
-        // retrieve instantiated class
517
-        return $this->_load(
518
-            $paths,
519
-            'EEM_',
520
-            $class_name,
521
-            'model',
522
-            $arguments,
523
-            true,
524
-            $load_only
525
-        );
526
-    }
527
-
528
-
529
-
530
-    /**
531
-     * loads model classes - must be singletons
532
-     *
533
-     * @param string $class_name - simple class name ie: price
534
-     * @param mixed  $arguments
535
-     * @param bool   $load_only
536
-     * @return mixed | bool
537
-     * @throws EE_Error
538
-     * @throws ReflectionException
539
-     */
540
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
541
-    {
542
-        $paths = array(
543
-            EE_MODELS . 'fields' . DS,
544
-            EE_MODELS . 'helpers' . DS,
545
-            EE_MODELS . 'relations' . DS,
546
-            EE_MODELS . 'strategies' . DS,
547
-        );
548
-        // retrieve instantiated class
549
-        return $this->_load(
550
-            $paths,
551
-            'EE_',
552
-            $class_name,
553
-            '',
554
-            $arguments,
555
-            true,
556
-            $load_only
557
-        );
558
-    }
559
-
560
-
561
-
562
-    /**
563
-     * Determines if $model_name is the name of an actual EE model.
564
-     *
565
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
566
-     * @return boolean
567
-     */
568
-    public function is_model_name($model_name)
569
-    {
570
-        return isset($this->models[$model_name]);
571
-    }
572
-
573
-
574
-
575
-    /**
576
-     * generic class loader
577
-     *
578
-     * @param string $path_to_file - directory path to file location, not including filename
579
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
580
-     * @param string $type         - file type - core? class? helper? model?
581
-     * @param mixed  $arguments
582
-     * @param bool   $load_only
583
-     * @return mixed
584
-     * @throws EE_Error
585
-     * @throws ReflectionException
586
-     */
587
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
588
-    {
589
-        // retrieve instantiated class
590
-        return $this->_load(
591
-            $path_to_file,
592
-            '',
593
-            $file_name,
594
-            $type,
595
-            $arguments,
596
-            true,
597
-            $load_only
598
-        );
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * @param string $path_to_file - directory path to file location, not including filename
605
-     * @param string $class_name   - full class name  ie:  My_Class
606
-     * @param string $type         - file type - core? class? helper? model?
607
-     * @param mixed  $arguments
608
-     * @param bool   $load_only
609
-     * @return bool|EE_Addon|object
610
-     * @throws EE_Error
611
-     * @throws ReflectionException
612
-     */
613
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
614
-    {
615
-        // retrieve instantiated class
616
-        return $this->_load(
617
-            $path_to_file,
618
-            'addon',
619
-            $class_name,
620
-            $type,
621
-            $arguments,
622
-            true,
623
-            $load_only
624
-        );
625
-    }
626
-
627
-
628
-
629
-    /**
630
-     * instantiates, caches, and automatically resolves dependencies
631
-     * for classes that use a Fully Qualified Class Name.
632
-     * if the class is not capable of being loaded using PSR-4 autoloading,
633
-     * then you need to use one of the existing load_*() methods
634
-     * which can resolve the classname and filepath from the passed arguments
635
-     *
636
-     * @param bool|string $class_name   Fully Qualified Class Name
637
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
638
-     * @param bool        $cache        whether to cache the instantiated object for reuse
639
-     * @param bool        $from_db      some classes are instantiated from the db
640
-     *                                  and thus call a different method to instantiate
641
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
642
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
643
-     * @return bool|null|object null = failure to load or instantiate class object.
644
-     *                                  object = class loaded and instantiated successfully.
645
-     *                                  bool = fail or success when $load_only is true
646
-     * @throws EE_Error
647
-     * @throws ReflectionException
648
-     */
649
-    public function create(
650
-        $class_name = false,
651
-        $arguments = array(),
652
-        $cache = true,
653
-        $load_only = false,
654
-        $addon = false
655
-    ) {
656
-        $class_name = ltrim($class_name, '\\');
657
-        $class_name = $this->_dependency_map->get_alias($class_name);
658
-        if (! class_exists($class_name)) {
659
-            // maybe the class is registered with a preceding \
660
-            $class_name = strpos($class_name, '\\') !== 0
661
-                ? '\\' . $class_name
662
-                : $class_name;
663
-            // still doesn't exist ?
664
-            if (! class_exists($class_name)) {
665
-                return null;
666
-            }
667
-        }
668
-        // if we're only loading the class and it already exists, then let's just return true immediately
669
-        if ($load_only) {
670
-            return true;
671
-        }
672
-        $addon = $addon
673
-            ? 'addon'
674
-            : '';
675
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
676
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
677
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
678
-        if ($this->_cache_on && $cache && ! $load_only) {
679
-            // return object if it's already cached
680
-            $cached_class = $this->_get_cached_class($class_name, $addon);
681
-            if ($cached_class !== null) {
682
-                return $cached_class;
683
-            }
684
-        }
685
-        // instantiate the requested object
686
-        $class_obj = $this->_create_object($class_name, $arguments, $addon);
687
-        if ($this->_cache_on && $cache) {
688
-            // save it for later... kinda like gum  { : $
689
-            $this->_set_cached_class($class_obj, $class_name, $addon);
690
-        }
691
-        $this->_cache_on = true;
692
-        return $class_obj;
693
-    }
694
-
695
-
696
-
697
-    /**
698
-     * instantiates, caches, and injects dependencies for classes
699
-     *
700
-     * @param array       $file_paths   an array of paths to folders to look in
701
-     * @param string      $class_prefix EE  or EEM or... ???
702
-     * @param bool|string $class_name   $class name
703
-     * @param string      $type         file type - core? class? helper? model?
704
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
705
-     * @param bool        $cache        whether to cache the instantiated object for reuse
706
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
707
-     * @return bool|null|object null = failure to load or instantiate class object.
708
-     *                                  object = class loaded and instantiated successfully.
709
-     *                                  bool = fail or success when $load_only is true
710
-     * @throws EE_Error
711
-     * @throws ReflectionException
712
-     */
713
-    protected function _load(
714
-        $file_paths = array(),
715
-        $class_prefix = 'EE_',
716
-        $class_name = false,
717
-        $type = 'class',
718
-        $arguments = array(),
719
-        $cache = true,
720
-        $load_only = false
721
-    ) {
722
-        $class_name = ltrim($class_name, '\\');
723
-        // strip php file extension
724
-        $class_name = str_replace('.php', '', trim($class_name));
725
-        // does the class have a prefix ?
726
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
727
-            // make sure $class_prefix is uppercase
728
-            $class_prefix = strtoupper(trim($class_prefix));
729
-            // add class prefix ONCE!!!
730
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
731
-        }
732
-        $class_name = $this->_dependency_map->get_alias($class_name);
733
-        $class_exists = class_exists($class_name);
734
-        // if we're only loading the class and it already exists, then let's just return true immediately
735
-        if ($load_only && $class_exists) {
736
-            return true;
737
-        }
738
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
739
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
740
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
741
-        if ($this->_cache_on && $cache && ! $load_only) {
742
-            // return object if it's already cached
743
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix);
744
-            if ($cached_class !== null) {
745
-                return $cached_class;
746
-            }
747
-        }
748
-        // if the class doesn't already exist.. then we need to try and find the file and load it
749
-        if (! $class_exists) {
750
-            // get full path to file
751
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
752
-            // load the file
753
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
754
-            // if loading failed, or we are only loading a file but NOT instantiating an object
755
-            if (! $loaded || $load_only) {
756
-                // return boolean if only loading, or null if an object was expected
757
-                return $load_only
758
-                    ? $loaded
759
-                    : null;
760
-            }
761
-        }
762
-        // instantiate the requested object
763
-        $class_obj = $this->_create_object($class_name, $arguments, $type);
764
-        if ($this->_cache_on && $cache) {
765
-            // save it for later... kinda like gum  { : $
766
-            $this->_set_cached_class($class_obj, $class_name, $class_prefix);
767
-        }
768
-        $this->_cache_on = true;
769
-        return $class_obj;
770
-    }
771
-
772
-
773
-
774
-    /**
775
-     * attempts to find a cached version of the requested class
776
-     * by looking in the following places:
777
-     *        $this->{$class_abbreviation}            ie:    $this->CART
778
-     *        $this->{$class_name}                        ie:    $this->Some_Class
779
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
780
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
781
-     *
782
-     * @param string $class_name
783
-     * @param string $class_prefix
784
-     * @return mixed
785
-     */
786
-    protected function _get_cached_class($class_name, $class_prefix = '')
787
-    {
788
-        if ($class_name === 'EE_Registry') {
789
-            return $this;
790
-        }
791
-        // have to specify something, but not anything that will conflict
792
-        $class_abbreviation = isset($this->_class_abbreviations[$class_name])
793
-            ? $this->_class_abbreviations[$class_name]
794
-            : 'FANCY_BATMAN_PANTS';
795
-        $class_name = str_replace('\\', '_', $class_name);
796
-        // check if class has already been loaded, and return it if it has been
797
-        if (isset($this->{$class_abbreviation})) {
798
-            return $this->{$class_abbreviation};
799
-        }
800
-        if (isset ($this->{$class_name})) {
801
-            return $this->{$class_name};
802
-        }
803
-        if (isset ($this->LIB->{$class_name})) {
804
-            return $this->LIB->{$class_name};
805
-        }
806
-        if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
807
-            return $this->addons->{$class_name};
808
-        }
809
-        return null;
810
-    }
811
-
812
-
813
-
814
-    /**
815
-     * removes a cached version of the requested class
816
-     *
817
-     * @param string  $class_name
818
-     * @param boolean $addon
819
-     * @return boolean
820
-     */
821
-    public function clear_cached_class($class_name, $addon = false)
822
-    {
823
-        // have to specify something, but not anything that will conflict
824
-        $class_abbreviation = isset($this->_class_abbreviations[$class_name])
825
-            ? $this->_class_abbreviations[$class_name]
826
-            : 'FANCY_BATMAN_PANTS';
827
-        $class_name = str_replace('\\', '_', $class_name);
828
-        // check if class has already been loaded, and return it if it has been
829
-        if (isset($this->{$class_abbreviation})) {
830
-            $this->{$class_abbreviation} = null;
831
-            return true;
832
-        }
833
-        if (isset($this->{$class_name})) {
834
-            $this->{$class_name} = null;
835
-            return true;
836
-        }
837
-        if (isset($this->LIB->{$class_name})) {
838
-            unset($this->LIB->{$class_name});
839
-            return true;
840
-        }
841
-        if ($addon && isset($this->addons->{$class_name})) {
842
-            unset($this->addons->{$class_name});
843
-            return true;
844
-        }
845
-        return false;
846
-    }
847
-
848
-
849
-
850
-    /**
851
-     * attempts to find a full valid filepath for the requested class.
852
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
853
-     * then returns that path if the target file has been found and is readable
854
-     *
855
-     * @param string $class_name
856
-     * @param string $type
857
-     * @param array  $file_paths
858
-     * @return string | bool
859
-     */
860
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
861
-    {
862
-        // make sure $file_paths is an array
863
-        $file_paths = is_array($file_paths)
864
-            ? $file_paths
865
-            : array($file_paths);
866
-        // cycle thru paths
867
-        foreach ($file_paths as $key => $file_path) {
868
-            // convert all separators to proper DS, if no filepath, then use EE_CLASSES
869
-            $file_path = $file_path
870
-                ? str_replace(array('/', '\\'), DS, $file_path)
871
-                : EE_CLASSES;
872
-            // prep file type
873
-            $type = ! empty($type)
874
-                ? trim($type, '.') . '.'
875
-                : '';
876
-            // build full file path
877
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
878
-            //does the file exist and can be read ?
879
-            if (is_readable($file_paths[$key])) {
880
-                return $file_paths[$key];
881
-            }
882
-        }
883
-        return false;
884
-    }
885
-
886
-
887
-
888
-    /**
889
-     * basically just performs a require_once()
890
-     * but with some error handling
891
-     *
892
-     * @param  string $path
893
-     * @param  string $class_name
894
-     * @param  string $type
895
-     * @param  array  $file_paths
896
-     * @return bool
897
-     * @throws EE_Error
898
-     * @throws ReflectionException
899
-     */
900
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
901
-    {
902
-        // don't give up! you gotta...
903
-        try {
904
-            //does the file exist and can it be read ?
905
-            if (! $path) {
906
-                // so sorry, can't find the file
907
-                throw new EE_Error (
908
-                    sprintf(
909
-                        esc_html__(
910
-                            'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
911
-                            'event_espresso'
912
-                        ),
913
-                        trim($type, '.'),
914
-                        $class_name,
915
-                        '<br />' . implode(',<br />', $file_paths)
916
-                    )
917
-                );
918
-            }
919
-            // get the file
920
-            require_once($path);
921
-            // if the class isn't already declared somewhere
922
-            if (class_exists($class_name, false) === false) {
923
-                // so sorry, not a class
924
-                throw new EE_Error(
925
-                    sprintf(
926
-                        esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
927
-                        $type,
928
-                        $path,
929
-                        $class_name
930
-                    )
931
-                );
932
-            }
933
-        } catch (EE_Error $e) {
934
-            $e->get_error();
935
-            return false;
936
-        }
937
-        return true;
938
-    }
939
-
940
-
941
-
942
-    /**
943
-     * _create_object
944
-     * Attempts to instantiate the requested class via any of the
945
-     * commonly used instantiation methods employed throughout EE.
946
-     * The priority for instantiation is as follows:
947
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
948
-     *        - model objects via their 'new_instance_from_db' method
949
-     *        - model objects via their 'new_instance' method
950
-     *        - "singleton" classes" via their 'instance' method
951
-     *    - standard instantiable classes via their __constructor
952
-     * Prior to instantiation, if the classname exists in the dependency_map,
953
-     * then the constructor for the requested class will be examined to determine
954
-     * if any dependencies exist, and if they can be injected.
955
-     * If so, then those classes will be added to the array of arguments passed to the constructor
956
-     *
957
-     * @param string $class_name
958
-     * @param array  $arguments
959
-     * @param string $type
960
-     * @param bool   $from_db
961
-     * @return null|object
962
-     * @throws EE_Error
963
-     * @throws ReflectionException
964
-     */
965
-    protected function _create_object($class_name, $arguments = array(), $type = '')
966
-    {
967
-        $class_obj = null;
968
-        $instantiation_mode = '0) none';
969
-        // don't give up! you gotta...
970
-        try {
971
-            // create reflection
972
-            $reflector = $this->get_ReflectionClass($class_name);
973
-            // make sure arguments are an array
974
-            $arguments = is_array($arguments)
975
-                ? $arguments
976
-                : array($arguments);
977
-            // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
978
-            // else wrap it in an additional array so that it doesn't get split into multiple parameters
979
-            $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
980
-                ? $arguments
981
-                : array($arguments);
982
-            // attempt to inject dependencies ?
983
-            if ($this->_dependency_map->has($class_name)) {
984
-                $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
985
-            }
986
-            // instantiate the class if possible
987
-            if ($reflector->isAbstract()) {
988
-                // nothing to instantiate, loading file was enough
989
-                // does not throw an exception so $instantiation_mode is unused
990
-                // $instantiation_mode = "1) no constructor abstract class";
991
-                $class_obj = true;
992
-            } else if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
993
-                // no constructor = static methods only... nothing to instantiate, loading file was enough
994
-                $instantiation_mode = '2) no constructor but instantiable';
995
-                $class_obj = $reflector->newInstance();
996
-            } else if (method_exists($class_name, 'new_instance')) {
997
-                $instantiation_mode = '4) new_instance()';
998
-                $class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
999
-            } else if (method_exists($class_name, 'instance')) {
1000
-                $instantiation_mode = '5) instance()';
1001
-                $class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
1002
-            } else if ($reflector->isInstantiable()) {
1003
-                $instantiation_mode = '6) constructor';
1004
-                $class_obj = $reflector->newInstanceArgs($arguments);
1005
-            } else {
1006
-                // heh ? something's not right !
1007
-                throw new EE_Error(
1008
-                    sprintf(
1009
-                        esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1010
-                        $type,
1011
-                        $class_name
1012
-                    )
1013
-                );
1014
-            }
1015
-        } catch (Exception $e) {
1016
-            if (! $e instanceof EE_Error) {
1017
-                $e = new EE_Error(
1018
-                    sprintf(
1019
-                        esc_html__(
1020
-                            'The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s',
1021
-                            'event_espresso'
1022
-                        ),
1023
-                        $class_name,
1024
-                        '<br />',
1025
-                        $e->getMessage(),
1026
-                        $instantiation_mode
1027
-                    )
1028
-                );
1029
-            }
1030
-            $e->get_error();
1031
-        }
1032
-        return $class_obj;
1033
-    }
1034
-
1035
-
1036
-
1037
-    /**
1038
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1039
-     * @param array $array
1040
-     * @return bool
1041
-     */
1042
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
1043
-    {
1044
-        return ! empty($array)
1045
-            ? array_keys($array) === range(0, count($array) - 1)
1046
-            : true;
1047
-    }
1048
-
1049
-
1050
-
1051
-    /**
1052
-     * getReflectionClass
1053
-     * checks if a ReflectionClass object has already been generated for a class
1054
-     * and returns that instead of creating a new one
1055
-     *
1056
-     * @param string $class_name
1057
-     * @return ReflectionClass
1058
-     * @throws ReflectionException
1059
-     */
1060
-    public function get_ReflectionClass($class_name)
1061
-    {
1062
-        if (
1063
-            ! isset($this->_reflectors[$class_name])
1064
-            || ! $this->_reflectors[$class_name] instanceof ReflectionClass
1065
-        ) {
1066
-            $this->_reflectors[$class_name] = new ReflectionClass($class_name);
1067
-        }
1068
-        return $this->_reflectors[$class_name];
1069
-    }
1070
-
1071
-
1072
-
1073
-    /**
1074
-     * _resolve_dependencies
1075
-     * examines the constructor for the requested class to determine
1076
-     * if any dependencies exist, and if they can be injected.
1077
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1078
-     * PLZ NOTE: this is achieved by type hinting the constructor params
1079
-     * For example:
1080
-     *        if attempting to load a class "Foo" with the following constructor:
1081
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
1082
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1083
-     *        but only IF they are NOT already present in the incoming arguments array,
1084
-     *        and the correct classes can be loaded
1085
-     *
1086
-     * @param ReflectionClass $reflector
1087
-     * @param string          $class_name
1088
-     * @param array           $arguments
1089
-     * @return array
1090
-     * @throws EE_Error
1091
-     * @throws ReflectionException
1092
-     */
1093
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1094
-    {
1095
-        // let's examine the constructor
1096
-        $constructor = $reflector->getConstructor();
1097
-        // whu? huh? nothing?
1098
-        if (! $constructor) {
1099
-            return $arguments;
1100
-        }
1101
-        // get constructor parameters
1102
-        $params = $constructor->getParameters();
1103
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1104
-        $argument_keys = array_keys($arguments);
1105
-        // now loop thru all of the constructors expected parameters
1106
-        foreach ($params as $index => $param) {
1107
-            // is this a dependency for a specific class ?
1108
-            $param_class = $param->getClass()
1109
-                ? $param->getClass()->name
1110
-                : null;
1111
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1112
-            $param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1113
-                ? $this->_dependency_map->get_alias($param_class, $class_name)
1114
-                : $param_class;
1115
-            if (
1116
-                // param is not even a class
1117
-                empty($param_class)
1118
-                // and something already exists in the incoming arguments for this param
1119
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1120
-            ) {
1121
-                // so let's skip this argument and move on to the next
1122
-                continue;
1123
-            }
1124
-            if (
1125
-                // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1126
-                ! empty($param_class)
1127
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1128
-                && $arguments[$argument_keys[$index]] instanceof $param_class
1129
-            ) {
1130
-                // skip this argument and move on to the next
1131
-                continue;
1132
-            }
1133
-            if (
1134
-                // parameter is type hinted as a class, and should be injected
1135
-                ! empty($param_class)
1136
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1137
-            ) {
1138
-                $arguments = $this->_resolve_dependency($class_name, $param_class, $arguments, $index);
1139
-            } else {
1140
-                try {
1141
-                    $arguments[$index] = $param->getDefaultValue();
1142
-                } catch (ReflectionException $e) {
1143
-                    throw new ReflectionException(
1144
-                        sprintf(
1145
-                            esc_html__('%1$s for parameter "$%2$s"', 'event_espresso'),
1146
-                            $e->getMessage(),
1147
-                            $param->getName()
1148
-                        )
1149
-                    );
1150
-                }
1151
-            }
1152
-        }
1153
-        return $arguments;
1154
-    }
1155
-
1156
-
1157
-
1158
-    /**
1159
-     * @param string $class_name
1160
-     * @param string $param_class
1161
-     * @param array  $arguments
1162
-     * @param mixed  $index
1163
-     * @return array
1164
-     * @throws EE_Error
1165
-     * @throws ReflectionException
1166
-     */
1167
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1168
-    {
1169
-        $dependency = null;
1170
-        // should dependency be loaded from cache ?
1171
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency($class_name, $param_class)
1172
-                    !== EE_Dependency_Map::load_new_object;
1173
-        // we might have a dependency...
1174
-        // let's MAYBE try and find it in our cache if that's what's been requested
1175
-        $cached_class = $cache_on
1176
-            ? $this->_get_cached_class($param_class)
1177
-            : null;
1178
-        // and grab it if it exists
1179
-        if ($cached_class instanceof $param_class) {
1180
-            $dependency = $cached_class;
1181
-        } else if ($param_class !== $class_name) {
1182
-            // obtain the loader method from the dependency map
1183
-            $loader = $this->_dependency_map->class_loader($param_class);
1184
-            // is loader a custom closure ?
1185
-            if ($loader instanceof Closure) {
1186
-                $dependency = $loader();
1187
-            } else {
1188
-                // set the cache on property for the recursive loading call
1189
-                $this->_cache_on = $cache_on;
1190
-                // if not, then let's try and load it via the registry
1191
-                if ($loader && method_exists($this, $loader)) {
1192
-                    $dependency = $this->{$loader}($param_class);
1193
-                } else {
1194
-                    $dependency = $this->create($param_class, array(), $cache_on);
1195
-                }
1196
-            }
1197
-        }
1198
-        // did we successfully find the correct dependency ?
1199
-        if ($dependency instanceof $param_class) {
1200
-            // then let's inject it into the incoming array of arguments at the correct location
1201
-            if (isset($argument_keys[$index])) {
1202
-                $arguments[$argument_keys[$index]] = $dependency;
1203
-            } else {
1204
-                $arguments[$index] = $dependency;
1205
-            }
1206
-        }
1207
-        return $arguments;
1208
-    }
1209
-
1210
-
1211
-
1212
-    /**
1213
-     * _set_cached_class
1214
-     * attempts to cache the instantiated class locally
1215
-     * in one of the following places, in the following order:
1216
-     *        $this->{class_abbreviation}   ie:    $this->CART
1217
-     *        $this->{$class_name}          ie:    $this->Some_Class
1218
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1219
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1220
-     *
1221
-     * @param object $class_obj
1222
-     * @param string $class_name
1223
-     * @param string $class_prefix
1224
-     * @return void
1225
-     */
1226
-    protected function _set_cached_class($class_obj, $class_name, $class_prefix = '')
1227
-    {
1228
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1229
-            return;
1230
-        }
1231
-        // return newly instantiated class
1232
-        if (isset($this->_class_abbreviations[$class_name])) {
1233
-            $class_abbreviation = $this->_class_abbreviations[$class_name];
1234
-            $this->{$class_abbreviation} = $class_obj;
1235
-            return;
1236
-        }
1237
-        $class_name = str_replace('\\', '_', $class_name);
1238
-        if (property_exists($this, $class_name)) {
1239
-            $this->{$class_name} = $class_obj;
1240
-            return;
1241
-        }
1242
-        if ($class_prefix === 'addon') {
1243
-            $this->addons->{$class_name} = $class_obj;
1244
-            return;
1245
-        }
1246
-        $this->LIB->{$class_name} = $class_obj;
1247
-    }
1248
-
1249
-
1250
-
1251
-    /**
1252
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1253
-     *
1254
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1255
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1256
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1257
-     * @param array  $arguments
1258
-     * @return object
1259
-     */
1260
-    public static function factory($classname, $arguments = array())
1261
-    {
1262
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1263
-        if ($loader instanceof Closure) {
1264
-            return $loader($arguments);
1265
-        }
1266
-        if (method_exists(self::instance(), $loader)) {
1267
-            return self::instance()->{$loader}($classname, $arguments);
1268
-        }
1269
-        return null;
1270
-    }
1271
-
1272
-
1273
-
1274
-    /**
1275
-     * Gets the addon by its name/slug (not classname. For that, just
1276
-     * use the classname as the property name on EE_Config::instance()->addons)
1277
-     *
1278
-     * @param string $name
1279
-     * @return EE_Addon
1280
-     */
1281
-    public function get_addon_by_name($name)
1282
-    {
1283
-        foreach ($this->addons as $addon) {
1284
-            if ($addon->name() === $name) {
1285
-                return $addon;
1286
-            }
1287
-        }
1288
-        return null;
1289
-    }
1290
-
1291
-
1292
-
1293
-    /**
1294
-     * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their
1295
-     * name() function) They're already available on EE_Config::instance()->addons as properties, where each property's
1296
-     * name is the addon's classname. So if you just want to get the addon by classname, use
1297
-     * EE_Config::instance()->addons->{classname}
1298
-     *
1299
-     * @return EE_Addon[] where the KEYS are the addon's name()
1300
-     */
1301
-    public function get_addons_by_name()
1302
-    {
1303
-        $addons = array();
1304
-        foreach ($this->addons as $addon) {
1305
-            $addons[$addon->name()] = $addon;
1306
-        }
1307
-        return $addons;
1308
-    }
1309
-
1310
-
1311
-
1312
-    /**
1313
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1314
-     * a stale copy of it around
1315
-     *
1316
-     * @param string $model_name
1317
-     * @return \EEM_Base
1318
-     * @throws \EE_Error
1319
-     */
1320
-    public function reset_model($model_name)
1321
-    {
1322
-        $model_class_name = strpos($model_name, 'EEM_') !== 0
1323
-            ? "EEM_{$model_name}"
1324
-            : $model_name;
1325
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1326
-            return null;
1327
-        }
1328
-        //get that model reset it and make sure we nuke the old reference to it
1329
-        if ($this->LIB->{$model_class_name} instanceof $model_class_name
1330
-            && is_callable(
1331
-                array($model_class_name, 'reset')
1332
-            )) {
1333
-            $this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1334
-        } else {
1335
-            throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1336
-        }
1337
-        return $this->LIB->{$model_class_name};
1338
-    }
1339
-
1340
-
1341
-
1342
-    /**
1343
-     * Resets the registry.
1344
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when
1345
-     * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1346
-     * - $_dependency_map
1347
-     * - $_class_abbreviations
1348
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1349
-     * - $REQ:  Still on the same request so no need to change.
1350
-     * - $CAP: There is no site specific state in the EE_Capability class.
1351
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1352
-     * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1353
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1354
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1355
-     *             switch or on the restore.
1356
-     * - $modules
1357
-     * - $shortcodes
1358
-     * - $widgets
1359
-     *
1360
-     * @param boolean $hard             whether to reset data in the database too, or just refresh
1361
-     *                                  the Registry to its state at the beginning of the request
1362
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1363
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1364
-     *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1365
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1366
-     *                                  client
1367
-     *                                  code instead can just change the model context to a different blog id if
1368
-     *                                  necessary
1369
-     * @return EE_Registry
1370
-     * @throws EE_Error
1371
-     * @throws ReflectionException
1372
-     */
1373
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1374
-    {
1375
-        $instance = self::instance();
1376
-        $instance->_cache_on = true;
1377
-        // reset some "special" classes
1378
-        EEH_Activation::reset();
1379
-        $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1380
-        $instance->CART = null;
1381
-        $instance->MRM = null;
1382
-        $instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1383
-        //messages reset
1384
-        EED_Messages::reset();
1385
-        //handle of objects cached on LIB
1386
-        foreach (array('LIB', 'modules') as $cache) {
1387
-            foreach ($instance->{$cache} as $class_name => $class) {
1388
-                if (self::_reset_and_unset_object($class, $reset_models)) {
1389
-                    unset($instance->{$cache}->{$class_name});
1390
-                }
1391
-            }
1392
-        }
1393
-        return $instance;
1394
-    }
1395
-
1396
-
1397
-
1398
-    /**
1399
-     * if passed object implements ResettableInterface, then call it's reset() method
1400
-     * if passed object implements InterminableInterface, then return false,
1401
-     * to indicate that it should NOT be cleared from the Registry cache
1402
-     *
1403
-     * @param      $object
1404
-     * @param bool $reset_models
1405
-     * @return bool returns true if cached object should be unset
1406
-     */
1407
-    private static function _reset_and_unset_object($object, $reset_models)
1408
-    {
1409
-        if (! is_object($object)) {
1410
-            // don't unset anything that's not an object
1411
-            return false;
1412
-        }
1413
-        if ($object instanceof EED_Module) {
1414
-            $object::reset();
1415
-            // don't unset modules
1416
-            return false;
1417
-        }
1418
-        if ($object instanceof ResettableInterface) {
1419
-            if ($object instanceof EEM_Base) {
1420
-                if ($reset_models) {
1421
-                    $object->reset();
1422
-                    return true;
1423
-                }
1424
-                return false;
1425
-            }
1426
-            $object->reset();
1427
-            return true;
1428
-        }
1429
-        if (! $object instanceof InterminableInterface) {
1430
-            return true;
1431
-        }
1432
-        return false;
1433
-    }
1434
-
1435
-
1436
-
1437
-    /**
1438
-     * Gets all the custom post type models defined
1439
-     *
1440
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1441
-     */
1442
-    public function cpt_models()
1443
-    {
1444
-        $cpt_models = array();
1445
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1446
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1447
-                $cpt_models[$short_name] = $classname;
1448
-            }
1449
-        }
1450
-        return $cpt_models;
1451
-    }
1452
-
1453
-
1454
-
1455
-    /**
1456
-     * @return \EE_Config
1457
-     */
1458
-    public static function CFG()
1459
-    {
1460
-        return self::instance()->CFG;
1461
-    }
23
+	/**
24
+	 * @var EE_Registry $_instance
25
+	 */
26
+	private static $_instance;
27
+
28
+	/**
29
+	 * @var EE_Dependency_Map $_dependency_map
30
+	 */
31
+	protected $_dependency_map;
32
+
33
+	/**
34
+	 * @var array $_class_abbreviations
35
+	 */
36
+	protected $_class_abbreviations = array();
37
+
38
+	/**
39
+	 * @var CommandBusInterface $BUS
40
+	 */
41
+	public $BUS;
42
+
43
+	/**
44
+	 * @var EE_Cart $CART
45
+	 */
46
+	public $CART;
47
+
48
+	/**
49
+	 * @var EE_Config $CFG
50
+	 */
51
+	public $CFG;
52
+
53
+	/**
54
+	 * @var EE_Network_Config $NET_CFG
55
+	 */
56
+	public $NET_CFG;
57
+
58
+	/**
59
+	 * StdClass object for storing library classes in
60
+	 *
61
+	 * @var StdClass $LIB
62
+	 */
63
+	public $LIB;
64
+
65
+	/**
66
+	 * @var EE_Request_Handler $REQ
67
+	 */
68
+	public $REQ;
69
+
70
+	/**
71
+	 * @var EE_Session $SSN
72
+	 */
73
+	public $SSN;
74
+
75
+	/**
76
+	 * @since 4.5.0
77
+	 * @var EE_Capabilities $CAP
78
+	 */
79
+	public $CAP;
80
+
81
+	/**
82
+	 * @since 4.9.0
83
+	 * @var EE_Message_Resource_Manager $MRM
84
+	 */
85
+	public $MRM;
86
+
87
+
88
+	/**
89
+	 * @var Registry $AssetsRegistry
90
+	 */
91
+	public $AssetsRegistry;
92
+
93
+	/**
94
+	 * StdClass object for holding addons which have registered themselves to work with EE core
95
+	 *
96
+	 * @var EE_Addon[] $addons
97
+	 */
98
+	public $addons;
99
+
100
+	/**
101
+	 * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
102
+	 *
103
+	 * @var EEM_Base[] $models
104
+	 */
105
+	public $models = array();
106
+
107
+	/**
108
+	 * @var EED_Module[] $modules
109
+	 */
110
+	public $modules;
111
+
112
+	/**
113
+	 * @var EES_Shortcode[] $shortcodes
114
+	 */
115
+	public $shortcodes;
116
+
117
+	/**
118
+	 * @var WP_Widget[] $widgets
119
+	 */
120
+	public $widgets;
121
+
122
+	/**
123
+	 * this is an array of all implemented model names (i.e. not the parent abstract models, or models
124
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
125
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
126
+	 * classnames (eg "EEM_Event")
127
+	 *
128
+	 * @var array $non_abstract_db_models
129
+	 */
130
+	public $non_abstract_db_models = array();
131
+
132
+
133
+	/**
134
+	 * internationalization for JS strings
135
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
136
+	 *    in js file:  var translatedString = eei18n.string_key;
137
+	 *
138
+	 * @var array $i18n_js_strings
139
+	 */
140
+	public static $i18n_js_strings = array();
141
+
142
+
143
+	/**
144
+	 * $main_file - path to espresso.php
145
+	 *
146
+	 * @var array $main_file
147
+	 */
148
+	public $main_file;
149
+
150
+	/**
151
+	 * array of ReflectionClass objects where the key is the class name
152
+	 *
153
+	 * @var ReflectionClass[] $_reflectors
154
+	 */
155
+	public $_reflectors;
156
+
157
+	/**
158
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
159
+	 *
160
+	 * @var boolean $_cache_on
161
+	 */
162
+	protected $_cache_on = true;
163
+
164
+
165
+
166
+	/**
167
+	 * @singleton method used to instantiate class object
168
+	 * @param  EE_Dependency_Map $dependency_map
169
+	 * @return EE_Registry instance
170
+	 */
171
+	public static function instance(EE_Dependency_Map $dependency_map = null)
172
+	{
173
+		// check if class object is instantiated
174
+		if (! self::$_instance instanceof EE_Registry) {
175
+			self::$_instance = new self($dependency_map);
176
+		}
177
+		return self::$_instance;
178
+	}
179
+
180
+
181
+
182
+	/**
183
+	 * protected constructor to prevent direct creation
184
+	 *
185
+	 * @Constructor
186
+	 * @param  EE_Dependency_Map $dependency_map
187
+	 */
188
+	protected function __construct(EE_Dependency_Map $dependency_map)
189
+	{
190
+		$this->_dependency_map = $dependency_map;
191
+		$this->LIB = new stdClass();
192
+		$this->addons = new stdClass();
193
+		$this->modules = new stdClass();
194
+		$this->shortcodes = new stdClass();
195
+		$this->widgets = new stdClass();
196
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
197
+	}
198
+
199
+
200
+
201
+	/**
202
+	 * initialize
203
+	 *
204
+	 * @throws EE_Error
205
+	 * @throws ReflectionException
206
+	 */
207
+	public function initialize()
208
+	{
209
+		$this->_class_abbreviations = apply_filters(
210
+			'FHEE__EE_Registry____construct___class_abbreviations',
211
+			array(
212
+				'EE_Config'                                       => 'CFG',
213
+				'EE_Session'                                      => 'SSN',
214
+				'EE_Capabilities'                                 => 'CAP',
215
+				'EE_Cart'                                         => 'CART',
216
+				'EE_Network_Config'                               => 'NET_CFG',
217
+				'EE_Request_Handler'                              => 'REQ',
218
+				'EE_Message_Resource_Manager'                     => 'MRM',
219
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
220
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
221
+			)
222
+		);
223
+		$this->load_core('Base', array(), true);
224
+		// add our request and response objects to the cache
225
+		$request_loader = $this->_dependency_map->class_loader('EE_Request');
226
+		$this->_set_cached_class(
227
+			$request_loader(),
228
+			'EE_Request'
229
+		);
230
+		$response_loader = $this->_dependency_map->class_loader('EE_Response');
231
+		$this->_set_cached_class(
232
+			$response_loader(),
233
+			'EE_Response'
234
+		);
235
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
236
+	}
237
+
238
+
239
+
240
+	/**
241
+	 * @return void
242
+	 */
243
+	public function init()
244
+	{
245
+		// Get current page protocol
246
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
247
+		// Output admin-ajax.php URL with same protocol as current page
248
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
249
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
250
+	}
251
+
252
+
253
+
254
+	/**
255
+	 * localize_i18n_js_strings
256
+	 *
257
+	 * @return string
258
+	 */
259
+	public static function localize_i18n_js_strings()
260
+	{
261
+		$i18n_js_strings = (array)self::$i18n_js_strings;
262
+		foreach ($i18n_js_strings as $key => $value) {
263
+			if (is_scalar($value)) {
264
+				$i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
265
+			}
266
+		}
267
+		return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
268
+	}
269
+
270
+
271
+
272
+	/**
273
+	 * @param $module
274
+	 * @throws EE_Error
275
+	 * @throws ReflectionException
276
+	 */
277
+	public function add_module($module)
278
+	{
279
+		if ($module instanceof EED_Module) {
280
+			$module_class = get_class($module);
281
+			$this->modules->{$module_class} = $module;
282
+		} else {
283
+			if (! class_exists('EE_Module_Request_Router')) {
284
+				$this->load_core('Module_Request_Router');
285
+			}
286
+			EE_Module_Request_Router::module_factory($module);
287
+		}
288
+	}
289
+
290
+
291
+
292
+	/**
293
+	 * @param string $module_name
294
+	 * @return mixed EED_Module | NULL
295
+	 */
296
+	public function get_module($module_name = '')
297
+	{
298
+		return isset($this->modules->{$module_name})
299
+			? $this->modules->{$module_name}
300
+			: null;
301
+	}
302
+
303
+
304
+
305
+	/**
306
+	 * loads core classes - must be singletons
307
+	 *
308
+	 * @param string $class_name - simple class name ie: session
309
+	 * @param mixed  $arguments
310
+	 * @param bool   $load_only
311
+	 * @return mixed
312
+	 * @throws EE_Error
313
+	 * @throws ReflectionException
314
+	 */
315
+	public function load_core($class_name, $arguments = array(), $load_only = false)
316
+	{
317
+		$core_paths = apply_filters(
318
+			'FHEE__EE_Registry__load_core__core_paths',
319
+			array(
320
+				EE_CORE,
321
+				EE_ADMIN,
322
+				EE_CPTS,
323
+				EE_CORE . 'data_migration_scripts' . DS,
324
+				EE_CORE . 'capabilities' . DS,
325
+				EE_CORE . 'request_stack' . DS,
326
+				EE_CORE . 'middleware' . DS,
327
+			)
328
+		);
329
+		// retrieve instantiated class
330
+		return $this->_load(
331
+			$core_paths,
332
+			'EE_',
333
+			$class_name,
334
+			'core',
335
+			$arguments,
336
+			true,
337
+			$load_only
338
+		);
339
+	}
340
+
341
+
342
+
343
+	/**
344
+	 * loads service classes
345
+	 *
346
+	 * @param string $class_name - simple class name ie: session
347
+	 * @param mixed  $arguments
348
+	 * @param bool   $load_only
349
+	 * @return mixed
350
+	 * @throws EE_Error
351
+	 * @throws ReflectionException
352
+	 */
353
+	public function load_service($class_name, $arguments = array(), $load_only = false)
354
+	{
355
+		$service_paths = apply_filters(
356
+			'FHEE__EE_Registry__load_service__service_paths',
357
+			array(
358
+				EE_CORE . 'services' . DS,
359
+			)
360
+		);
361
+		// retrieve instantiated class
362
+		return $this->_load(
363
+			$service_paths,
364
+			'EE_',
365
+			$class_name,
366
+			'class',
367
+			$arguments,
368
+			true,
369
+			$load_only
370
+		);
371
+	}
372
+
373
+
374
+
375
+	/**
376
+	 * loads data_migration_scripts
377
+	 *
378
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
379
+	 * @param mixed  $arguments
380
+	 * @return EE_Data_Migration_Script_Base|mixed
381
+	 * @throws EE_Error
382
+	 * @throws ReflectionException
383
+	 */
384
+	public function load_dms($class_name, $arguments = array())
385
+	{
386
+		// retrieve instantiated class
387
+		return $this->_load(
388
+			EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
389
+			'EE_DMS_',
390
+			$class_name,
391
+			'dms',
392
+			$arguments,
393
+			false
394
+		);
395
+	}
396
+
397
+
398
+
399
+	/**
400
+	 * loads object creating classes - must be singletons
401
+	 *
402
+	 * @param string $class_name - simple class name ie: attendee
403
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
404
+	 * @param bool   $from_db    - deprecated
405
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
406
+	 *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
407
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
408
+	 *                           (default)
409
+	 * @return EE_Base_Class | bool
410
+	 * @throws EE_Error
411
+	 * @throws ReflectionException
412
+	 */
413
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
414
+	{
415
+		$paths = apply_filters(
416
+			'FHEE__EE_Registry__load_class__paths', array(
417
+			EE_CORE,
418
+			EE_CLASSES,
419
+			EE_BUSINESS,
420
+		)
421
+		);
422
+		// retrieve instantiated class
423
+		return $this->_load(
424
+			$paths,
425
+			'EE_',
426
+			$class_name,
427
+			'class',
428
+			$arguments,
429
+			$cache,
430
+			$load_only
431
+		);
432
+	}
433
+
434
+
435
+
436
+	/**
437
+	 * loads helper classes - must be singletons
438
+	 *
439
+	 * @param string $class_name - simple class name ie: price
440
+	 * @param mixed  $arguments
441
+	 * @param bool   $load_only
442
+	 * @return EEH_Base | bool
443
+	 * @throws EE_Error
444
+	 * @throws ReflectionException
445
+	 */
446
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
447
+	{
448
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
449
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
450
+		// retrieve instantiated class
451
+		return $this->_load(
452
+			$helper_paths,
453
+			'EEH_',
454
+			$class_name,
455
+			'helper',
456
+			$arguments,
457
+			true,
458
+			$load_only
459
+		);
460
+	}
461
+
462
+
463
+
464
+	/**
465
+	 * loads core classes - must be singletons
466
+	 *
467
+	 * @param string $class_name - simple class name ie: session
468
+	 * @param mixed  $arguments
469
+	 * @param bool   $load_only
470
+	 * @param bool   $cache      whether to cache the object or not.
471
+	 * @return mixed
472
+	 * @throws EE_Error
473
+	 * @throws ReflectionException
474
+	 */
475
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
476
+	{
477
+		$paths = array(
478
+			EE_LIBRARIES,
479
+			EE_LIBRARIES . 'messages' . DS,
480
+			EE_LIBRARIES . 'shortcodes' . DS,
481
+			EE_LIBRARIES . 'qtips' . DS,
482
+			EE_LIBRARIES . 'payment_methods' . DS,
483
+		);
484
+		// retrieve instantiated class
485
+		return $this->_load(
486
+			$paths,
487
+			'EE_',
488
+			$class_name,
489
+			'lib',
490
+			$arguments,
491
+			$cache,
492
+			$load_only
493
+		);
494
+	}
495
+
496
+
497
+
498
+	/**
499
+	 * loads model classes - must be singletons
500
+	 *
501
+	 * @param string $class_name - simple class name ie: price
502
+	 * @param mixed  $arguments
503
+	 * @param bool   $load_only
504
+	 * @return EEM_Base | bool
505
+	 * @throws EE_Error
506
+	 * @throws ReflectionException
507
+	 */
508
+	public function load_model($class_name, $arguments = array(), $load_only = false)
509
+	{
510
+		$paths = apply_filters(
511
+			'FHEE__EE_Registry__load_model__paths', array(
512
+			EE_MODELS,
513
+			EE_CORE,
514
+		)
515
+		);
516
+		// retrieve instantiated class
517
+		return $this->_load(
518
+			$paths,
519
+			'EEM_',
520
+			$class_name,
521
+			'model',
522
+			$arguments,
523
+			true,
524
+			$load_only
525
+		);
526
+	}
527
+
528
+
529
+
530
+	/**
531
+	 * loads model classes - must be singletons
532
+	 *
533
+	 * @param string $class_name - simple class name ie: price
534
+	 * @param mixed  $arguments
535
+	 * @param bool   $load_only
536
+	 * @return mixed | bool
537
+	 * @throws EE_Error
538
+	 * @throws ReflectionException
539
+	 */
540
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
541
+	{
542
+		$paths = array(
543
+			EE_MODELS . 'fields' . DS,
544
+			EE_MODELS . 'helpers' . DS,
545
+			EE_MODELS . 'relations' . DS,
546
+			EE_MODELS . 'strategies' . DS,
547
+		);
548
+		// retrieve instantiated class
549
+		return $this->_load(
550
+			$paths,
551
+			'EE_',
552
+			$class_name,
553
+			'',
554
+			$arguments,
555
+			true,
556
+			$load_only
557
+		);
558
+	}
559
+
560
+
561
+
562
+	/**
563
+	 * Determines if $model_name is the name of an actual EE model.
564
+	 *
565
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
566
+	 * @return boolean
567
+	 */
568
+	public function is_model_name($model_name)
569
+	{
570
+		return isset($this->models[$model_name]);
571
+	}
572
+
573
+
574
+
575
+	/**
576
+	 * generic class loader
577
+	 *
578
+	 * @param string $path_to_file - directory path to file location, not including filename
579
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
580
+	 * @param string $type         - file type - core? class? helper? model?
581
+	 * @param mixed  $arguments
582
+	 * @param bool   $load_only
583
+	 * @return mixed
584
+	 * @throws EE_Error
585
+	 * @throws ReflectionException
586
+	 */
587
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
588
+	{
589
+		// retrieve instantiated class
590
+		return $this->_load(
591
+			$path_to_file,
592
+			'',
593
+			$file_name,
594
+			$type,
595
+			$arguments,
596
+			true,
597
+			$load_only
598
+		);
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * @param string $path_to_file - directory path to file location, not including filename
605
+	 * @param string $class_name   - full class name  ie:  My_Class
606
+	 * @param string $type         - file type - core? class? helper? model?
607
+	 * @param mixed  $arguments
608
+	 * @param bool   $load_only
609
+	 * @return bool|EE_Addon|object
610
+	 * @throws EE_Error
611
+	 * @throws ReflectionException
612
+	 */
613
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
614
+	{
615
+		// retrieve instantiated class
616
+		return $this->_load(
617
+			$path_to_file,
618
+			'addon',
619
+			$class_name,
620
+			$type,
621
+			$arguments,
622
+			true,
623
+			$load_only
624
+		);
625
+	}
626
+
627
+
628
+
629
+	/**
630
+	 * instantiates, caches, and automatically resolves dependencies
631
+	 * for classes that use a Fully Qualified Class Name.
632
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
633
+	 * then you need to use one of the existing load_*() methods
634
+	 * which can resolve the classname and filepath from the passed arguments
635
+	 *
636
+	 * @param bool|string $class_name   Fully Qualified Class Name
637
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
638
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
639
+	 * @param bool        $from_db      some classes are instantiated from the db
640
+	 *                                  and thus call a different method to instantiate
641
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
642
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
643
+	 * @return bool|null|object null = failure to load or instantiate class object.
644
+	 *                                  object = class loaded and instantiated successfully.
645
+	 *                                  bool = fail or success when $load_only is true
646
+	 * @throws EE_Error
647
+	 * @throws ReflectionException
648
+	 */
649
+	public function create(
650
+		$class_name = false,
651
+		$arguments = array(),
652
+		$cache = true,
653
+		$load_only = false,
654
+		$addon = false
655
+	) {
656
+		$class_name = ltrim($class_name, '\\');
657
+		$class_name = $this->_dependency_map->get_alias($class_name);
658
+		if (! class_exists($class_name)) {
659
+			// maybe the class is registered with a preceding \
660
+			$class_name = strpos($class_name, '\\') !== 0
661
+				? '\\' . $class_name
662
+				: $class_name;
663
+			// still doesn't exist ?
664
+			if (! class_exists($class_name)) {
665
+				return null;
666
+			}
667
+		}
668
+		// if we're only loading the class and it already exists, then let's just return true immediately
669
+		if ($load_only) {
670
+			return true;
671
+		}
672
+		$addon = $addon
673
+			? 'addon'
674
+			: '';
675
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
676
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
677
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
678
+		if ($this->_cache_on && $cache && ! $load_only) {
679
+			// return object if it's already cached
680
+			$cached_class = $this->_get_cached_class($class_name, $addon);
681
+			if ($cached_class !== null) {
682
+				return $cached_class;
683
+			}
684
+		}
685
+		// instantiate the requested object
686
+		$class_obj = $this->_create_object($class_name, $arguments, $addon);
687
+		if ($this->_cache_on && $cache) {
688
+			// save it for later... kinda like gum  { : $
689
+			$this->_set_cached_class($class_obj, $class_name, $addon);
690
+		}
691
+		$this->_cache_on = true;
692
+		return $class_obj;
693
+	}
694
+
695
+
696
+
697
+	/**
698
+	 * instantiates, caches, and injects dependencies for classes
699
+	 *
700
+	 * @param array       $file_paths   an array of paths to folders to look in
701
+	 * @param string      $class_prefix EE  or EEM or... ???
702
+	 * @param bool|string $class_name   $class name
703
+	 * @param string      $type         file type - core? class? helper? model?
704
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
705
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
706
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
707
+	 * @return bool|null|object null = failure to load or instantiate class object.
708
+	 *                                  object = class loaded and instantiated successfully.
709
+	 *                                  bool = fail or success when $load_only is true
710
+	 * @throws EE_Error
711
+	 * @throws ReflectionException
712
+	 */
713
+	protected function _load(
714
+		$file_paths = array(),
715
+		$class_prefix = 'EE_',
716
+		$class_name = false,
717
+		$type = 'class',
718
+		$arguments = array(),
719
+		$cache = true,
720
+		$load_only = false
721
+	) {
722
+		$class_name = ltrim($class_name, '\\');
723
+		// strip php file extension
724
+		$class_name = str_replace('.php', '', trim($class_name));
725
+		// does the class have a prefix ?
726
+		if (! empty($class_prefix) && $class_prefix !== 'addon') {
727
+			// make sure $class_prefix is uppercase
728
+			$class_prefix = strtoupper(trim($class_prefix));
729
+			// add class prefix ONCE!!!
730
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
731
+		}
732
+		$class_name = $this->_dependency_map->get_alias($class_name);
733
+		$class_exists = class_exists($class_name);
734
+		// if we're only loading the class and it already exists, then let's just return true immediately
735
+		if ($load_only && $class_exists) {
736
+			return true;
737
+		}
738
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
739
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
740
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
741
+		if ($this->_cache_on && $cache && ! $load_only) {
742
+			// return object if it's already cached
743
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix);
744
+			if ($cached_class !== null) {
745
+				return $cached_class;
746
+			}
747
+		}
748
+		// if the class doesn't already exist.. then we need to try and find the file and load it
749
+		if (! $class_exists) {
750
+			// get full path to file
751
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
752
+			// load the file
753
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
754
+			// if loading failed, or we are only loading a file but NOT instantiating an object
755
+			if (! $loaded || $load_only) {
756
+				// return boolean if only loading, or null if an object was expected
757
+				return $load_only
758
+					? $loaded
759
+					: null;
760
+			}
761
+		}
762
+		// instantiate the requested object
763
+		$class_obj = $this->_create_object($class_name, $arguments, $type);
764
+		if ($this->_cache_on && $cache) {
765
+			// save it for later... kinda like gum  { : $
766
+			$this->_set_cached_class($class_obj, $class_name, $class_prefix);
767
+		}
768
+		$this->_cache_on = true;
769
+		return $class_obj;
770
+	}
771
+
772
+
773
+
774
+	/**
775
+	 * attempts to find a cached version of the requested class
776
+	 * by looking in the following places:
777
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
778
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
779
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
780
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
781
+	 *
782
+	 * @param string $class_name
783
+	 * @param string $class_prefix
784
+	 * @return mixed
785
+	 */
786
+	protected function _get_cached_class($class_name, $class_prefix = '')
787
+	{
788
+		if ($class_name === 'EE_Registry') {
789
+			return $this;
790
+		}
791
+		// have to specify something, but not anything that will conflict
792
+		$class_abbreviation = isset($this->_class_abbreviations[$class_name])
793
+			? $this->_class_abbreviations[$class_name]
794
+			: 'FANCY_BATMAN_PANTS';
795
+		$class_name = str_replace('\\', '_', $class_name);
796
+		// check if class has already been loaded, and return it if it has been
797
+		if (isset($this->{$class_abbreviation})) {
798
+			return $this->{$class_abbreviation};
799
+		}
800
+		if (isset ($this->{$class_name})) {
801
+			return $this->{$class_name};
802
+		}
803
+		if (isset ($this->LIB->{$class_name})) {
804
+			return $this->LIB->{$class_name};
805
+		}
806
+		if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
807
+			return $this->addons->{$class_name};
808
+		}
809
+		return null;
810
+	}
811
+
812
+
813
+
814
+	/**
815
+	 * removes a cached version of the requested class
816
+	 *
817
+	 * @param string  $class_name
818
+	 * @param boolean $addon
819
+	 * @return boolean
820
+	 */
821
+	public function clear_cached_class($class_name, $addon = false)
822
+	{
823
+		// have to specify something, but not anything that will conflict
824
+		$class_abbreviation = isset($this->_class_abbreviations[$class_name])
825
+			? $this->_class_abbreviations[$class_name]
826
+			: 'FANCY_BATMAN_PANTS';
827
+		$class_name = str_replace('\\', '_', $class_name);
828
+		// check if class has already been loaded, and return it if it has been
829
+		if (isset($this->{$class_abbreviation})) {
830
+			$this->{$class_abbreviation} = null;
831
+			return true;
832
+		}
833
+		if (isset($this->{$class_name})) {
834
+			$this->{$class_name} = null;
835
+			return true;
836
+		}
837
+		if (isset($this->LIB->{$class_name})) {
838
+			unset($this->LIB->{$class_name});
839
+			return true;
840
+		}
841
+		if ($addon && isset($this->addons->{$class_name})) {
842
+			unset($this->addons->{$class_name});
843
+			return true;
844
+		}
845
+		return false;
846
+	}
847
+
848
+
849
+
850
+	/**
851
+	 * attempts to find a full valid filepath for the requested class.
852
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
853
+	 * then returns that path if the target file has been found and is readable
854
+	 *
855
+	 * @param string $class_name
856
+	 * @param string $type
857
+	 * @param array  $file_paths
858
+	 * @return string | bool
859
+	 */
860
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
861
+	{
862
+		// make sure $file_paths is an array
863
+		$file_paths = is_array($file_paths)
864
+			? $file_paths
865
+			: array($file_paths);
866
+		// cycle thru paths
867
+		foreach ($file_paths as $key => $file_path) {
868
+			// convert all separators to proper DS, if no filepath, then use EE_CLASSES
869
+			$file_path = $file_path
870
+				? str_replace(array('/', '\\'), DS, $file_path)
871
+				: EE_CLASSES;
872
+			// prep file type
873
+			$type = ! empty($type)
874
+				? trim($type, '.') . '.'
875
+				: '';
876
+			// build full file path
877
+			$file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
878
+			//does the file exist and can be read ?
879
+			if (is_readable($file_paths[$key])) {
880
+				return $file_paths[$key];
881
+			}
882
+		}
883
+		return false;
884
+	}
885
+
886
+
887
+
888
+	/**
889
+	 * basically just performs a require_once()
890
+	 * but with some error handling
891
+	 *
892
+	 * @param  string $path
893
+	 * @param  string $class_name
894
+	 * @param  string $type
895
+	 * @param  array  $file_paths
896
+	 * @return bool
897
+	 * @throws EE_Error
898
+	 * @throws ReflectionException
899
+	 */
900
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
901
+	{
902
+		// don't give up! you gotta...
903
+		try {
904
+			//does the file exist and can it be read ?
905
+			if (! $path) {
906
+				// so sorry, can't find the file
907
+				throw new EE_Error (
908
+					sprintf(
909
+						esc_html__(
910
+							'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
911
+							'event_espresso'
912
+						),
913
+						trim($type, '.'),
914
+						$class_name,
915
+						'<br />' . implode(',<br />', $file_paths)
916
+					)
917
+				);
918
+			}
919
+			// get the file
920
+			require_once($path);
921
+			// if the class isn't already declared somewhere
922
+			if (class_exists($class_name, false) === false) {
923
+				// so sorry, not a class
924
+				throw new EE_Error(
925
+					sprintf(
926
+						esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
927
+						$type,
928
+						$path,
929
+						$class_name
930
+					)
931
+				);
932
+			}
933
+		} catch (EE_Error $e) {
934
+			$e->get_error();
935
+			return false;
936
+		}
937
+		return true;
938
+	}
939
+
940
+
941
+
942
+	/**
943
+	 * _create_object
944
+	 * Attempts to instantiate the requested class via any of the
945
+	 * commonly used instantiation methods employed throughout EE.
946
+	 * The priority for instantiation is as follows:
947
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
948
+	 *        - model objects via their 'new_instance_from_db' method
949
+	 *        - model objects via their 'new_instance' method
950
+	 *        - "singleton" classes" via their 'instance' method
951
+	 *    - standard instantiable classes via their __constructor
952
+	 * Prior to instantiation, if the classname exists in the dependency_map,
953
+	 * then the constructor for the requested class will be examined to determine
954
+	 * if any dependencies exist, and if they can be injected.
955
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
956
+	 *
957
+	 * @param string $class_name
958
+	 * @param array  $arguments
959
+	 * @param string $type
960
+	 * @param bool   $from_db
961
+	 * @return null|object
962
+	 * @throws EE_Error
963
+	 * @throws ReflectionException
964
+	 */
965
+	protected function _create_object($class_name, $arguments = array(), $type = '')
966
+	{
967
+		$class_obj = null;
968
+		$instantiation_mode = '0) none';
969
+		// don't give up! you gotta...
970
+		try {
971
+			// create reflection
972
+			$reflector = $this->get_ReflectionClass($class_name);
973
+			// make sure arguments are an array
974
+			$arguments = is_array($arguments)
975
+				? $arguments
976
+				: array($arguments);
977
+			// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
978
+			// else wrap it in an additional array so that it doesn't get split into multiple parameters
979
+			$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
980
+				? $arguments
981
+				: array($arguments);
982
+			// attempt to inject dependencies ?
983
+			if ($this->_dependency_map->has($class_name)) {
984
+				$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
985
+			}
986
+			// instantiate the class if possible
987
+			if ($reflector->isAbstract()) {
988
+				// nothing to instantiate, loading file was enough
989
+				// does not throw an exception so $instantiation_mode is unused
990
+				// $instantiation_mode = "1) no constructor abstract class";
991
+				$class_obj = true;
992
+			} else if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
993
+				// no constructor = static methods only... nothing to instantiate, loading file was enough
994
+				$instantiation_mode = '2) no constructor but instantiable';
995
+				$class_obj = $reflector->newInstance();
996
+			} else if (method_exists($class_name, 'new_instance')) {
997
+				$instantiation_mode = '4) new_instance()';
998
+				$class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
999
+			} else if (method_exists($class_name, 'instance')) {
1000
+				$instantiation_mode = '5) instance()';
1001
+				$class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
1002
+			} else if ($reflector->isInstantiable()) {
1003
+				$instantiation_mode = '6) constructor';
1004
+				$class_obj = $reflector->newInstanceArgs($arguments);
1005
+			} else {
1006
+				// heh ? something's not right !
1007
+				throw new EE_Error(
1008
+					sprintf(
1009
+						esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1010
+						$type,
1011
+						$class_name
1012
+					)
1013
+				);
1014
+			}
1015
+		} catch (Exception $e) {
1016
+			if (! $e instanceof EE_Error) {
1017
+				$e = new EE_Error(
1018
+					sprintf(
1019
+						esc_html__(
1020
+							'The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s',
1021
+							'event_espresso'
1022
+						),
1023
+						$class_name,
1024
+						'<br />',
1025
+						$e->getMessage(),
1026
+						$instantiation_mode
1027
+					)
1028
+				);
1029
+			}
1030
+			$e->get_error();
1031
+		}
1032
+		return $class_obj;
1033
+	}
1034
+
1035
+
1036
+
1037
+	/**
1038
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1039
+	 * @param array $array
1040
+	 * @return bool
1041
+	 */
1042
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
1043
+	{
1044
+		return ! empty($array)
1045
+			? array_keys($array) === range(0, count($array) - 1)
1046
+			: true;
1047
+	}
1048
+
1049
+
1050
+
1051
+	/**
1052
+	 * getReflectionClass
1053
+	 * checks if a ReflectionClass object has already been generated for a class
1054
+	 * and returns that instead of creating a new one
1055
+	 *
1056
+	 * @param string $class_name
1057
+	 * @return ReflectionClass
1058
+	 * @throws ReflectionException
1059
+	 */
1060
+	public function get_ReflectionClass($class_name)
1061
+	{
1062
+		if (
1063
+			! isset($this->_reflectors[$class_name])
1064
+			|| ! $this->_reflectors[$class_name] instanceof ReflectionClass
1065
+		) {
1066
+			$this->_reflectors[$class_name] = new ReflectionClass($class_name);
1067
+		}
1068
+		return $this->_reflectors[$class_name];
1069
+	}
1070
+
1071
+
1072
+
1073
+	/**
1074
+	 * _resolve_dependencies
1075
+	 * examines the constructor for the requested class to determine
1076
+	 * if any dependencies exist, and if they can be injected.
1077
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1078
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
1079
+	 * For example:
1080
+	 *        if attempting to load a class "Foo" with the following constructor:
1081
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
1082
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1083
+	 *        but only IF they are NOT already present in the incoming arguments array,
1084
+	 *        and the correct classes can be loaded
1085
+	 *
1086
+	 * @param ReflectionClass $reflector
1087
+	 * @param string          $class_name
1088
+	 * @param array           $arguments
1089
+	 * @return array
1090
+	 * @throws EE_Error
1091
+	 * @throws ReflectionException
1092
+	 */
1093
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1094
+	{
1095
+		// let's examine the constructor
1096
+		$constructor = $reflector->getConstructor();
1097
+		// whu? huh? nothing?
1098
+		if (! $constructor) {
1099
+			return $arguments;
1100
+		}
1101
+		// get constructor parameters
1102
+		$params = $constructor->getParameters();
1103
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1104
+		$argument_keys = array_keys($arguments);
1105
+		// now loop thru all of the constructors expected parameters
1106
+		foreach ($params as $index => $param) {
1107
+			// is this a dependency for a specific class ?
1108
+			$param_class = $param->getClass()
1109
+				? $param->getClass()->name
1110
+				: null;
1111
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1112
+			$param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1113
+				? $this->_dependency_map->get_alias($param_class, $class_name)
1114
+				: $param_class;
1115
+			if (
1116
+				// param is not even a class
1117
+				empty($param_class)
1118
+				// and something already exists in the incoming arguments for this param
1119
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1120
+			) {
1121
+				// so let's skip this argument and move on to the next
1122
+				continue;
1123
+			}
1124
+			if (
1125
+				// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1126
+				! empty($param_class)
1127
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1128
+				&& $arguments[$argument_keys[$index]] instanceof $param_class
1129
+			) {
1130
+				// skip this argument and move on to the next
1131
+				continue;
1132
+			}
1133
+			if (
1134
+				// parameter is type hinted as a class, and should be injected
1135
+				! empty($param_class)
1136
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1137
+			) {
1138
+				$arguments = $this->_resolve_dependency($class_name, $param_class, $arguments, $index);
1139
+			} else {
1140
+				try {
1141
+					$arguments[$index] = $param->getDefaultValue();
1142
+				} catch (ReflectionException $e) {
1143
+					throw new ReflectionException(
1144
+						sprintf(
1145
+							esc_html__('%1$s for parameter "$%2$s"', 'event_espresso'),
1146
+							$e->getMessage(),
1147
+							$param->getName()
1148
+						)
1149
+					);
1150
+				}
1151
+			}
1152
+		}
1153
+		return $arguments;
1154
+	}
1155
+
1156
+
1157
+
1158
+	/**
1159
+	 * @param string $class_name
1160
+	 * @param string $param_class
1161
+	 * @param array  $arguments
1162
+	 * @param mixed  $index
1163
+	 * @return array
1164
+	 * @throws EE_Error
1165
+	 * @throws ReflectionException
1166
+	 */
1167
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1168
+	{
1169
+		$dependency = null;
1170
+		// should dependency be loaded from cache ?
1171
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency($class_name, $param_class)
1172
+					!== EE_Dependency_Map::load_new_object;
1173
+		// we might have a dependency...
1174
+		// let's MAYBE try and find it in our cache if that's what's been requested
1175
+		$cached_class = $cache_on
1176
+			? $this->_get_cached_class($param_class)
1177
+			: null;
1178
+		// and grab it if it exists
1179
+		if ($cached_class instanceof $param_class) {
1180
+			$dependency = $cached_class;
1181
+		} else if ($param_class !== $class_name) {
1182
+			// obtain the loader method from the dependency map
1183
+			$loader = $this->_dependency_map->class_loader($param_class);
1184
+			// is loader a custom closure ?
1185
+			if ($loader instanceof Closure) {
1186
+				$dependency = $loader();
1187
+			} else {
1188
+				// set the cache on property for the recursive loading call
1189
+				$this->_cache_on = $cache_on;
1190
+				// if not, then let's try and load it via the registry
1191
+				if ($loader && method_exists($this, $loader)) {
1192
+					$dependency = $this->{$loader}($param_class);
1193
+				} else {
1194
+					$dependency = $this->create($param_class, array(), $cache_on);
1195
+				}
1196
+			}
1197
+		}
1198
+		// did we successfully find the correct dependency ?
1199
+		if ($dependency instanceof $param_class) {
1200
+			// then let's inject it into the incoming array of arguments at the correct location
1201
+			if (isset($argument_keys[$index])) {
1202
+				$arguments[$argument_keys[$index]] = $dependency;
1203
+			} else {
1204
+				$arguments[$index] = $dependency;
1205
+			}
1206
+		}
1207
+		return $arguments;
1208
+	}
1209
+
1210
+
1211
+
1212
+	/**
1213
+	 * _set_cached_class
1214
+	 * attempts to cache the instantiated class locally
1215
+	 * in one of the following places, in the following order:
1216
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1217
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1218
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1219
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1220
+	 *
1221
+	 * @param object $class_obj
1222
+	 * @param string $class_name
1223
+	 * @param string $class_prefix
1224
+	 * @return void
1225
+	 */
1226
+	protected function _set_cached_class($class_obj, $class_name, $class_prefix = '')
1227
+	{
1228
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1229
+			return;
1230
+		}
1231
+		// return newly instantiated class
1232
+		if (isset($this->_class_abbreviations[$class_name])) {
1233
+			$class_abbreviation = $this->_class_abbreviations[$class_name];
1234
+			$this->{$class_abbreviation} = $class_obj;
1235
+			return;
1236
+		}
1237
+		$class_name = str_replace('\\', '_', $class_name);
1238
+		if (property_exists($this, $class_name)) {
1239
+			$this->{$class_name} = $class_obj;
1240
+			return;
1241
+		}
1242
+		if ($class_prefix === 'addon') {
1243
+			$this->addons->{$class_name} = $class_obj;
1244
+			return;
1245
+		}
1246
+		$this->LIB->{$class_name} = $class_obj;
1247
+	}
1248
+
1249
+
1250
+
1251
+	/**
1252
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1253
+	 *
1254
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1255
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1256
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1257
+	 * @param array  $arguments
1258
+	 * @return object
1259
+	 */
1260
+	public static function factory($classname, $arguments = array())
1261
+	{
1262
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1263
+		if ($loader instanceof Closure) {
1264
+			return $loader($arguments);
1265
+		}
1266
+		if (method_exists(self::instance(), $loader)) {
1267
+			return self::instance()->{$loader}($classname, $arguments);
1268
+		}
1269
+		return null;
1270
+	}
1271
+
1272
+
1273
+
1274
+	/**
1275
+	 * Gets the addon by its name/slug (not classname. For that, just
1276
+	 * use the classname as the property name on EE_Config::instance()->addons)
1277
+	 *
1278
+	 * @param string $name
1279
+	 * @return EE_Addon
1280
+	 */
1281
+	public function get_addon_by_name($name)
1282
+	{
1283
+		foreach ($this->addons as $addon) {
1284
+			if ($addon->name() === $name) {
1285
+				return $addon;
1286
+			}
1287
+		}
1288
+		return null;
1289
+	}
1290
+
1291
+
1292
+
1293
+	/**
1294
+	 * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their
1295
+	 * name() function) They're already available on EE_Config::instance()->addons as properties, where each property's
1296
+	 * name is the addon's classname. So if you just want to get the addon by classname, use
1297
+	 * EE_Config::instance()->addons->{classname}
1298
+	 *
1299
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1300
+	 */
1301
+	public function get_addons_by_name()
1302
+	{
1303
+		$addons = array();
1304
+		foreach ($this->addons as $addon) {
1305
+			$addons[$addon->name()] = $addon;
1306
+		}
1307
+		return $addons;
1308
+	}
1309
+
1310
+
1311
+
1312
+	/**
1313
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1314
+	 * a stale copy of it around
1315
+	 *
1316
+	 * @param string $model_name
1317
+	 * @return \EEM_Base
1318
+	 * @throws \EE_Error
1319
+	 */
1320
+	public function reset_model($model_name)
1321
+	{
1322
+		$model_class_name = strpos($model_name, 'EEM_') !== 0
1323
+			? "EEM_{$model_name}"
1324
+			: $model_name;
1325
+		if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1326
+			return null;
1327
+		}
1328
+		//get that model reset it and make sure we nuke the old reference to it
1329
+		if ($this->LIB->{$model_class_name} instanceof $model_class_name
1330
+			&& is_callable(
1331
+				array($model_class_name, 'reset')
1332
+			)) {
1333
+			$this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1334
+		} else {
1335
+			throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1336
+		}
1337
+		return $this->LIB->{$model_class_name};
1338
+	}
1339
+
1340
+
1341
+
1342
+	/**
1343
+	 * Resets the registry.
1344
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when
1345
+	 * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1346
+	 * - $_dependency_map
1347
+	 * - $_class_abbreviations
1348
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1349
+	 * - $REQ:  Still on the same request so no need to change.
1350
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1351
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1352
+	 * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1353
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1354
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1355
+	 *             switch or on the restore.
1356
+	 * - $modules
1357
+	 * - $shortcodes
1358
+	 * - $widgets
1359
+	 *
1360
+	 * @param boolean $hard             whether to reset data in the database too, or just refresh
1361
+	 *                                  the Registry to its state at the beginning of the request
1362
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1363
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1364
+	 *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1365
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1366
+	 *                                  client
1367
+	 *                                  code instead can just change the model context to a different blog id if
1368
+	 *                                  necessary
1369
+	 * @return EE_Registry
1370
+	 * @throws EE_Error
1371
+	 * @throws ReflectionException
1372
+	 */
1373
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1374
+	{
1375
+		$instance = self::instance();
1376
+		$instance->_cache_on = true;
1377
+		// reset some "special" classes
1378
+		EEH_Activation::reset();
1379
+		$instance->CFG = EE_Config::reset($hard, $reinstantiate);
1380
+		$instance->CART = null;
1381
+		$instance->MRM = null;
1382
+		$instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1383
+		//messages reset
1384
+		EED_Messages::reset();
1385
+		//handle of objects cached on LIB
1386
+		foreach (array('LIB', 'modules') as $cache) {
1387
+			foreach ($instance->{$cache} as $class_name => $class) {
1388
+				if (self::_reset_and_unset_object($class, $reset_models)) {
1389
+					unset($instance->{$cache}->{$class_name});
1390
+				}
1391
+			}
1392
+		}
1393
+		return $instance;
1394
+	}
1395
+
1396
+
1397
+
1398
+	/**
1399
+	 * if passed object implements ResettableInterface, then call it's reset() method
1400
+	 * if passed object implements InterminableInterface, then return false,
1401
+	 * to indicate that it should NOT be cleared from the Registry cache
1402
+	 *
1403
+	 * @param      $object
1404
+	 * @param bool $reset_models
1405
+	 * @return bool returns true if cached object should be unset
1406
+	 */
1407
+	private static function _reset_and_unset_object($object, $reset_models)
1408
+	{
1409
+		if (! is_object($object)) {
1410
+			// don't unset anything that's not an object
1411
+			return false;
1412
+		}
1413
+		if ($object instanceof EED_Module) {
1414
+			$object::reset();
1415
+			// don't unset modules
1416
+			return false;
1417
+		}
1418
+		if ($object instanceof ResettableInterface) {
1419
+			if ($object instanceof EEM_Base) {
1420
+				if ($reset_models) {
1421
+					$object->reset();
1422
+					return true;
1423
+				}
1424
+				return false;
1425
+			}
1426
+			$object->reset();
1427
+			return true;
1428
+		}
1429
+		if (! $object instanceof InterminableInterface) {
1430
+			return true;
1431
+		}
1432
+		return false;
1433
+	}
1434
+
1435
+
1436
+
1437
+	/**
1438
+	 * Gets all the custom post type models defined
1439
+	 *
1440
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1441
+	 */
1442
+	public function cpt_models()
1443
+	{
1444
+		$cpt_models = array();
1445
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1446
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1447
+				$cpt_models[$short_name] = $classname;
1448
+			}
1449
+		}
1450
+		return $cpt_models;
1451
+	}
1452
+
1453
+
1454
+
1455
+	/**
1456
+	 * @return \EE_Config
1457
+	 */
1458
+	public static function CFG()
1459
+	{
1460
+		return self::instance()->CFG;
1461
+	}
1462 1462
 
1463 1463
 
1464 1464
 }
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
     public static function instance(EE_Dependency_Map $dependency_map = null)
172 172
     {
173 173
         // check if class object is instantiated
174
-        if (! self::$_instance instanceof EE_Registry) {
174
+        if ( ! self::$_instance instanceof EE_Registry) {
175 175
             self::$_instance = new self($dependency_map);
176 176
         }
177 177
         return self::$_instance;
@@ -258,13 +258,13 @@  discard block
 block discarded – undo
258 258
      */
259 259
     public static function localize_i18n_js_strings()
260 260
     {
261
-        $i18n_js_strings = (array)self::$i18n_js_strings;
261
+        $i18n_js_strings = (array) self::$i18n_js_strings;
262 262
         foreach ($i18n_js_strings as $key => $value) {
263 263
             if (is_scalar($value)) {
264
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
264
+                $i18n_js_strings[$key] = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
265 265
             }
266 266
         }
267
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
267
+        return '/* <![CDATA[ */ var eei18n = '.wp_json_encode($i18n_js_strings).'; /* ]]> */';
268 268
     }
269 269
 
270 270
 
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
             $module_class = get_class($module);
281 281
             $this->modules->{$module_class} = $module;
282 282
         } else {
283
-            if (! class_exists('EE_Module_Request_Router')) {
283
+            if ( ! class_exists('EE_Module_Request_Router')) {
284 284
                 $this->load_core('Module_Request_Router');
285 285
             }
286 286
             EE_Module_Request_Router::module_factory($module);
@@ -320,10 +320,10 @@  discard block
 block discarded – undo
320 320
                 EE_CORE,
321 321
                 EE_ADMIN,
322 322
                 EE_CPTS,
323
-                EE_CORE . 'data_migration_scripts' . DS,
324
-                EE_CORE . 'capabilities' . DS,
325
-                EE_CORE . 'request_stack' . DS,
326
-                EE_CORE . 'middleware' . DS,
323
+                EE_CORE.'data_migration_scripts'.DS,
324
+                EE_CORE.'capabilities'.DS,
325
+                EE_CORE.'request_stack'.DS,
326
+                EE_CORE.'middleware'.DS,
327 327
             )
328 328
         );
329 329
         // retrieve instantiated class
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
         $service_paths = apply_filters(
356 356
             'FHEE__EE_Registry__load_service__service_paths',
357 357
             array(
358
-                EE_CORE . 'services' . DS,
358
+                EE_CORE.'services'.DS,
359 359
             )
360 360
         );
361 361
         // retrieve instantiated class
@@ -476,10 +476,10 @@  discard block
 block discarded – undo
476 476
     {
477 477
         $paths = array(
478 478
             EE_LIBRARIES,
479
-            EE_LIBRARIES . 'messages' . DS,
480
-            EE_LIBRARIES . 'shortcodes' . DS,
481
-            EE_LIBRARIES . 'qtips' . DS,
482
-            EE_LIBRARIES . 'payment_methods' . DS,
479
+            EE_LIBRARIES.'messages'.DS,
480
+            EE_LIBRARIES.'shortcodes'.DS,
481
+            EE_LIBRARIES.'qtips'.DS,
482
+            EE_LIBRARIES.'payment_methods'.DS,
483 483
         );
484 484
         // retrieve instantiated class
485 485
         return $this->_load(
@@ -540,10 +540,10 @@  discard block
 block discarded – undo
540 540
     public function load_model_class($class_name, $arguments = array(), $load_only = true)
541 541
     {
542 542
         $paths = array(
543
-            EE_MODELS . 'fields' . DS,
544
-            EE_MODELS . 'helpers' . DS,
545
-            EE_MODELS . 'relations' . DS,
546
-            EE_MODELS . 'strategies' . DS,
543
+            EE_MODELS.'fields'.DS,
544
+            EE_MODELS.'helpers'.DS,
545
+            EE_MODELS.'relations'.DS,
546
+            EE_MODELS.'strategies'.DS,
547 547
         );
548 548
         // retrieve instantiated class
549 549
         return $this->_load(
@@ -655,13 +655,13 @@  discard block
 block discarded – undo
655 655
     ) {
656 656
         $class_name = ltrim($class_name, '\\');
657 657
         $class_name = $this->_dependency_map->get_alias($class_name);
658
-        if (! class_exists($class_name)) {
658
+        if ( ! class_exists($class_name)) {
659 659
             // maybe the class is registered with a preceding \
660 660
             $class_name = strpos($class_name, '\\') !== 0
661
-                ? '\\' . $class_name
661
+                ? '\\'.$class_name
662 662
                 : $class_name;
663 663
             // still doesn't exist ?
664
-            if (! class_exists($class_name)) {
664
+            if ( ! class_exists($class_name)) {
665 665
                 return null;
666 666
             }
667 667
         }
@@ -723,11 +723,11 @@  discard block
 block discarded – undo
723 723
         // strip php file extension
724 724
         $class_name = str_replace('.php', '', trim($class_name));
725 725
         // does the class have a prefix ?
726
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
726
+        if ( ! empty($class_prefix) && $class_prefix !== 'addon') {
727 727
             // make sure $class_prefix is uppercase
728 728
             $class_prefix = strtoupper(trim($class_prefix));
729 729
             // add class prefix ONCE!!!
730
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
730
+            $class_name = $class_prefix.str_replace($class_prefix, '', $class_name);
731 731
         }
732 732
         $class_name = $this->_dependency_map->get_alias($class_name);
733 733
         $class_exists = class_exists($class_name);
@@ -746,13 +746,13 @@  discard block
 block discarded – undo
746 746
             }
747 747
         }
748 748
         // if the class doesn't already exist.. then we need to try and find the file and load it
749
-        if (! $class_exists) {
749
+        if ( ! $class_exists) {
750 750
             // get full path to file
751 751
             $path = $this->_resolve_path($class_name, $type, $file_paths);
752 752
             // load the file
753 753
             $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
754 754
             // if loading failed, or we are only loading a file but NOT instantiating an object
755
-            if (! $loaded || $load_only) {
755
+            if ( ! $loaded || $load_only) {
756 756
                 // return boolean if only loading, or null if an object was expected
757 757
                 return $load_only
758 758
                     ? $loaded
@@ -871,10 +871,10 @@  discard block
 block discarded – undo
871 871
                 : EE_CLASSES;
872 872
             // prep file type
873 873
             $type = ! empty($type)
874
-                ? trim($type, '.') . '.'
874
+                ? trim($type, '.').'.'
875 875
                 : '';
876 876
             // build full file path
877
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
877
+            $file_paths[$key] = rtrim($file_path, DS).DS.$class_name.'.'.$type.'php';
878 878
             //does the file exist and can be read ?
879 879
             if (is_readable($file_paths[$key])) {
880 880
                 return $file_paths[$key];
@@ -902,9 +902,9 @@  discard block
 block discarded – undo
902 902
         // don't give up! you gotta...
903 903
         try {
904 904
             //does the file exist and can it be read ?
905
-            if (! $path) {
905
+            if ( ! $path) {
906 906
                 // so sorry, can't find the file
907
-                throw new EE_Error (
907
+                throw new EE_Error(
908 908
                     sprintf(
909 909
                         esc_html__(
910 910
                             'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
@@ -912,7 +912,7 @@  discard block
 block discarded – undo
912 912
                         ),
913 913
                         trim($type, '.'),
914 914
                         $class_name,
915
-                        '<br />' . implode(',<br />', $file_paths)
915
+                        '<br />'.implode(',<br />', $file_paths)
916 916
                     )
917 917
                 );
918 918
             }
@@ -1013,7 +1013,7 @@  discard block
 block discarded – undo
1013 1013
                 );
1014 1014
             }
1015 1015
         } catch (Exception $e) {
1016
-            if (! $e instanceof EE_Error) {
1016
+            if ( ! $e instanceof EE_Error) {
1017 1017
                 $e = new EE_Error(
1018 1018
                     sprintf(
1019 1019
                         esc_html__(
@@ -1095,7 +1095,7 @@  discard block
 block discarded – undo
1095 1095
         // let's examine the constructor
1096 1096
         $constructor = $reflector->getConstructor();
1097 1097
         // whu? huh? nothing?
1098
-        if (! $constructor) {
1098
+        if ( ! $constructor) {
1099 1099
             return $arguments;
1100 1100
         }
1101 1101
         // get constructor parameters
@@ -1322,7 +1322,7 @@  discard block
 block discarded – undo
1322 1322
         $model_class_name = strpos($model_name, 'EEM_') !== 0
1323 1323
             ? "EEM_{$model_name}"
1324 1324
             : $model_name;
1325
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1325
+        if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1326 1326
             return null;
1327 1327
         }
1328 1328
         //get that model reset it and make sure we nuke the old reference to it
@@ -1406,7 +1406,7 @@  discard block
 block discarded – undo
1406 1406
      */
1407 1407
     private static function _reset_and_unset_object($object, $reset_models)
1408 1408
     {
1409
-        if (! is_object($object)) {
1409
+        if ( ! is_object($object)) {
1410 1410
             // don't unset anything that's not an object
1411 1411
             return false;
1412 1412
         }
@@ -1426,7 +1426,7 @@  discard block
 block discarded – undo
1426 1426
             $object->reset();
1427 1427
             return true;
1428 1428
         }
1429
-        if (! $object instanceof InterminableInterface) {
1429
+        if ( ! $object instanceof InterminableInterface) {
1430 1430
             return true;
1431 1431
         }
1432 1432
         return false;
Please login to merge, or discard this patch.