Completed
Branch 973/fix-visible-recaptcha (0580c7)
by
unknown
03:03 queued 30s
created
core/services/request/sanitizers/AllowedTags.php 1 patch
Indentation   +277 added lines, -277 removed lines patch added patch discarded remove patch
@@ -13,281 +13,281 @@
 block discarded – undo
13 13
 class AllowedTags
14 14
 {
15 15
 
16
-    /**
17
-     * @var array[]
18
-     */
19
-    private static $attributes = [
20
-        'accept-charset'    => 1,
21
-        'action'            => 1,
22
-        'alt'               => 1,
23
-        'allow'             => 1,
24
-        'allowfullscreen'   => 1,
25
-        'align'             => 1,
26
-        'aria-*'            => 1,
27
-        'autocomplete'      => 1,
28
-        'checked'           => 1,
29
-        'class'             => 1,
30
-        'cols'              => 1,
31
-        'content'           => 1,
32
-        'data-*'            => 1,
33
-        'dir'               => 1,
34
-        'disabled'          => 1,
35
-        'enctype'           => 1,
36
-        'for'               => 1,
37
-        'frameborder'       => 1,
38
-        'height'            => 1,
39
-        'href'              => 1,
40
-        'id'                => 1,
41
-        'itemprop'          => 1,
42
-        'itemscope'         => 1,
43
-        'itemtype'          => 1,
44
-        'label'             => 1,
45
-        'lang'              => 1,
46
-        'max'               => 1,
47
-        'maxlength'         => 1,
48
-        'method'            => 1,
49
-        'min'               => 1,
50
-        'multiple'          => 1,
51
-        'name'              => 1,
52
-        'novalidate'        => 1,
53
-        'placeholder'       => 1,
54
-        'readonly'          => 1,
55
-        'rel'               => 1,
56
-        'required'          => 1,
57
-        'rows'              => 1,
58
-        'selected'          => 1,
59
-        'src'               => 1,
60
-        'size'              => 1,
61
-        'style'             => 1,
62
-        'step'              => 1,
63
-        'tabindex'          => 1,
64
-        'target'            => 1,
65
-        'title'             => 1,
66
-        'type'              => 1,
67
-        'value'             => 1,
68
-        'width'             => 1,
69
-        'topmargin'         => 1,
70
-        'leftmargin'        => 1,
71
-        'marginheight'      => 1,
72
-        'marginwidth'       => 1,
73
-        'property'          => 1,
74
-        'bgcolor'           => 1,
75
-        'media'             => 1,
76
-        'cellpadding'       => 1,
77
-        'cellspacing'       => 1,
78
-        'border'            => 1,
79
-    ];
80
-
81
-
82
-    /**
83
-     * @var array
84
-     */
85
-    private static $tags = [
86
-        'a',
87
-        'abbr',
88
-        'b',
89
-        'br',
90
-        'code',
91
-        'div',
92
-        'em',
93
-        'h1',
94
-        'h2',
95
-        'h3',
96
-        'h4',
97
-        'h5',
98
-        'h6',
99
-        'hr',
100
-        'i',
101
-        'img',
102
-        'li',
103
-        'ol',
104
-        'p',
105
-        'pre',
106
-        'small',
107
-        'span',
108
-        'strong',
109
-        'table',
110
-        'td',
111
-        'tr',
112
-        'ul',
113
-    ];
114
-
115
-
116
-    /**
117
-     * @var array
118
-     */
119
-    private static $allowed_tags;
120
-
121
-
122
-    /**
123
-     * @var array
124
-     */
125
-    private static $allowed_with_embed_tags;
126
-
127
-
128
-    /**
129
-     * @var array
130
-     */
131
-    private static $allowed_with_form_tags;
132
-
133
-
134
-    /**
135
-     * @var array
136
-     */
137
-    private static $allowed_with_script_and_style_tags;
138
-
139
-    /**
140
-     * @var array
141
-     */
142
-    private static $allowed_with_full_tags;
143
-
144
-
145
-    /**
146
-     * merges additional tags and attributes into the WP post tags
147
-     */
148
-    private static function initializeAllowedTags()
149
-    {
150
-        $allowed_post_tags = wp_kses_allowed_html('post');
151
-        $allowed_tags = [];
152
-        foreach (AllowedTags::$tags as $tag) {
153
-            $allowed_tags[ $tag ] = AllowedTags::$attributes;
154
-        }
155
-        AllowedTags::$allowed_tags = array_merge_recursive($allowed_post_tags, $allowed_tags);
156
-    }
157
-
158
-
159
-    /**
160
-     * merges embed tags and attributes into the EE all tags
161
-     */
162
-    private static function initializeWithEmbedTags()
163
-    {
164
-        $all_tags = AllowedTags::getAllowedTags();
165
-        $embed_tags = [
166
-            'iframe' => AllowedTags::$attributes
167
-        ];
168
-        AllowedTags::$allowed_with_embed_tags = array_merge_recursive($all_tags, $embed_tags);
169
-    }
170
-
171
-
172
-    /**
173
-     * merges form tags and attributes into the EE all tags
174
-     */
175
-    private static function initializeWithFormTags()
176
-    {
177
-        $all_tags = AllowedTags::getAllowedTags();
178
-        $form_tags = [
179
-            'form'     => AllowedTags::$attributes,
180
-            'label'    => AllowedTags::$attributes,
181
-            'input'    => AllowedTags::$attributes,
182
-            'select'   => AllowedTags::$attributes,
183
-            'option'   => AllowedTags::$attributes,
184
-            'optgroup' => AllowedTags::$attributes,
185
-            'textarea' => AllowedTags::$attributes,
186
-            'button'   => AllowedTags::$attributes,
187
-            'fieldset' => AllowedTags::$attributes,
188
-            'output'   => AllowedTags::$attributes,
189
-        ];
190
-        AllowedTags::$allowed_with_form_tags = array_merge_recursive($all_tags, $form_tags);
191
-    }
192
-
193
-
194
-    /**
195
-     * merges form script and style tags and attributes into the EE all tags
196
-     */
197
-    private static function initializeWithScriptAndStyleTags()
198
-    {
199
-        $all_tags = AllowedTags::getAllowedTags();
200
-        $script_and_style_tags = [
201
-            'script' => AllowedTags::$attributes,
202
-            'style'  => AllowedTags::$attributes,
203
-            'link'   => AllowedTags::$attributes,
204
-        ];
205
-        AllowedTags::$allowed_with_script_and_style_tags = array_merge_recursive($all_tags, $script_and_style_tags);
206
-    }
207
-
208
-    /**
209
-     * merges all head and body tags and attributes into the EE all tags
210
-     */
211
-    private static function initializeWithFullTags()
212
-    {
213
-        $all_tags = AllowedTags::getAllowedTags();
214
-        $full_tags = [
215
-            'script'    => AllowedTags::$attributes,
216
-            'style'     => AllowedTags::$attributes,
217
-            'link'      => AllowedTags::$attributes,
218
-            'title'     => AllowedTags::$attributes,
219
-            'meta'      => AllowedTags::$attributes,
220
-            'iframe'    => AllowedTags::$attributes,
221
-            'form'      => AllowedTags::$attributes,
222
-            'label'     => AllowedTags::$attributes,
223
-            'input'     => AllowedTags::$attributes,
224
-            'select'    => AllowedTags::$attributes,
225
-            'option'    => AllowedTags::$attributes,
226
-            'optgroup'  => AllowedTags::$attributes,
227
-            'textarea'  => AllowedTags::$attributes,
228
-            'button'    => AllowedTags::$attributes,
229
-            'fieldset'  => AllowedTags::$attributes,
230
-            'output'    => AllowedTags::$attributes,
231
-        ];
232
-        AllowedTags::$allowed_with_full_tags = array_merge_recursive($all_tags, $full_tags);
233
-    }
234
-
235
-
236
-    /**
237
-     * @return array[]
238
-     */
239
-    public static function getAllowedTags()
240
-    {
241
-        if (empty(AllowedTags::$allowed_tags)) {
242
-            AllowedTags::initializeAllowedTags();
243
-        }
244
-        return AllowedTags::$allowed_tags;
245
-    }
246
-
247
-
248
-    /**
249
-     * @return array[]
250
-     */
251
-    public static function getWithEmbedTags()
252
-    {
253
-        if (empty(AllowedTags::$allowed_with_embed_tags)) {
254
-            AllowedTags::initializeWithEmbedTags();
255
-        }
256
-        return AllowedTags::$allowed_with_embed_tags;
257
-    }
258
-
259
-
260
-    /**
261
-     * @return array[]
262
-     */
263
-    public static function getWithFormTags()
264
-    {
265
-        if (empty(AllowedTags::$allowed_with_form_tags)) {
266
-            AllowedTags::initializeWithFormTags();
267
-        }
268
-        return AllowedTags::$allowed_with_form_tags;
269
-    }
270
-
271
-
272
-    /**
273
-     * @return array[]
274
-     */
275
-    public static function getWithScriptAndStyleTags()
276
-    {
277
-        if (empty(AllowedTags::$allowed_with_script_and_style_tags)) {
278
-            AllowedTags::initializeWithScriptAndStyleTags();
279
-        }
280
-        return AllowedTags::$allowed_with_script_and_style_tags;
281
-    }
282
-
283
-    /**
284
-     * @return array[]
285
-     */
286
-    public static function getWithFullTags()
287
-    {
288
-        if (empty(AllowedTags::$allowed_with_full_tags)) {
289
-            AllowedTags::initializeWithFullTags();
290
-        }
291
-        return AllowedTags::$allowed_with_full_tags;
292
-    }
16
+	/**
17
+	 * @var array[]
18
+	 */
19
+	private static $attributes = [
20
+		'accept-charset'    => 1,
21
+		'action'            => 1,
22
+		'alt'               => 1,
23
+		'allow'             => 1,
24
+		'allowfullscreen'   => 1,
25
+		'align'             => 1,
26
+		'aria-*'            => 1,
27
+		'autocomplete'      => 1,
28
+		'checked'           => 1,
29
+		'class'             => 1,
30
+		'cols'              => 1,
31
+		'content'           => 1,
32
+		'data-*'            => 1,
33
+		'dir'               => 1,
34
+		'disabled'          => 1,
35
+		'enctype'           => 1,
36
+		'for'               => 1,
37
+		'frameborder'       => 1,
38
+		'height'            => 1,
39
+		'href'              => 1,
40
+		'id'                => 1,
41
+		'itemprop'          => 1,
42
+		'itemscope'         => 1,
43
+		'itemtype'          => 1,
44
+		'label'             => 1,
45
+		'lang'              => 1,
46
+		'max'               => 1,
47
+		'maxlength'         => 1,
48
+		'method'            => 1,
49
+		'min'               => 1,
50
+		'multiple'          => 1,
51
+		'name'              => 1,
52
+		'novalidate'        => 1,
53
+		'placeholder'       => 1,
54
+		'readonly'          => 1,
55
+		'rel'               => 1,
56
+		'required'          => 1,
57
+		'rows'              => 1,
58
+		'selected'          => 1,
59
+		'src'               => 1,
60
+		'size'              => 1,
61
+		'style'             => 1,
62
+		'step'              => 1,
63
+		'tabindex'          => 1,
64
+		'target'            => 1,
65
+		'title'             => 1,
66
+		'type'              => 1,
67
+		'value'             => 1,
68
+		'width'             => 1,
69
+		'topmargin'         => 1,
70
+		'leftmargin'        => 1,
71
+		'marginheight'      => 1,
72
+		'marginwidth'       => 1,
73
+		'property'          => 1,
74
+		'bgcolor'           => 1,
75
+		'media'             => 1,
76
+		'cellpadding'       => 1,
77
+		'cellspacing'       => 1,
78
+		'border'            => 1,
79
+	];
80
+
81
+
82
+	/**
83
+	 * @var array
84
+	 */
85
+	private static $tags = [
86
+		'a',
87
+		'abbr',
88
+		'b',
89
+		'br',
90
+		'code',
91
+		'div',
92
+		'em',
93
+		'h1',
94
+		'h2',
95
+		'h3',
96
+		'h4',
97
+		'h5',
98
+		'h6',
99
+		'hr',
100
+		'i',
101
+		'img',
102
+		'li',
103
+		'ol',
104
+		'p',
105
+		'pre',
106
+		'small',
107
+		'span',
108
+		'strong',
109
+		'table',
110
+		'td',
111
+		'tr',
112
+		'ul',
113
+	];
114
+
115
+
116
+	/**
117
+	 * @var array
118
+	 */
119
+	private static $allowed_tags;
120
+
121
+
122
+	/**
123
+	 * @var array
124
+	 */
125
+	private static $allowed_with_embed_tags;
126
+
127
+
128
+	/**
129
+	 * @var array
130
+	 */
131
+	private static $allowed_with_form_tags;
132
+
133
+
134
+	/**
135
+	 * @var array
136
+	 */
137
+	private static $allowed_with_script_and_style_tags;
138
+
139
+	/**
140
+	 * @var array
141
+	 */
142
+	private static $allowed_with_full_tags;
143
+
144
+
145
+	/**
146
+	 * merges additional tags and attributes into the WP post tags
147
+	 */
148
+	private static function initializeAllowedTags()
149
+	{
150
+		$allowed_post_tags = wp_kses_allowed_html('post');
151
+		$allowed_tags = [];
152
+		foreach (AllowedTags::$tags as $tag) {
153
+			$allowed_tags[ $tag ] = AllowedTags::$attributes;
154
+		}
155
+		AllowedTags::$allowed_tags = array_merge_recursive($allowed_post_tags, $allowed_tags);
156
+	}
157
+
158
+
159
+	/**
160
+	 * merges embed tags and attributes into the EE all tags
161
+	 */
162
+	private static function initializeWithEmbedTags()
163
+	{
164
+		$all_tags = AllowedTags::getAllowedTags();
165
+		$embed_tags = [
166
+			'iframe' => AllowedTags::$attributes
167
+		];
168
+		AllowedTags::$allowed_with_embed_tags = array_merge_recursive($all_tags, $embed_tags);
169
+	}
170
+
171
+
172
+	/**
173
+	 * merges form tags and attributes into the EE all tags
174
+	 */
175
+	private static function initializeWithFormTags()
176
+	{
177
+		$all_tags = AllowedTags::getAllowedTags();
178
+		$form_tags = [
179
+			'form'     => AllowedTags::$attributes,
180
+			'label'    => AllowedTags::$attributes,
181
+			'input'    => AllowedTags::$attributes,
182
+			'select'   => AllowedTags::$attributes,
183
+			'option'   => AllowedTags::$attributes,
184
+			'optgroup' => AllowedTags::$attributes,
185
+			'textarea' => AllowedTags::$attributes,
186
+			'button'   => AllowedTags::$attributes,
187
+			'fieldset' => AllowedTags::$attributes,
188
+			'output'   => AllowedTags::$attributes,
189
+		];
190
+		AllowedTags::$allowed_with_form_tags = array_merge_recursive($all_tags, $form_tags);
191
+	}
192
+
193
+
194
+	/**
195
+	 * merges form script and style tags and attributes into the EE all tags
196
+	 */
197
+	private static function initializeWithScriptAndStyleTags()
198
+	{
199
+		$all_tags = AllowedTags::getAllowedTags();
200
+		$script_and_style_tags = [
201
+			'script' => AllowedTags::$attributes,
202
+			'style'  => AllowedTags::$attributes,
203
+			'link'   => AllowedTags::$attributes,
204
+		];
205
+		AllowedTags::$allowed_with_script_and_style_tags = array_merge_recursive($all_tags, $script_and_style_tags);
206
+	}
207
+
208
+	/**
209
+	 * merges all head and body tags and attributes into the EE all tags
210
+	 */
211
+	private static function initializeWithFullTags()
212
+	{
213
+		$all_tags = AllowedTags::getAllowedTags();
214
+		$full_tags = [
215
+			'script'    => AllowedTags::$attributes,
216
+			'style'     => AllowedTags::$attributes,
217
+			'link'      => AllowedTags::$attributes,
218
+			'title'     => AllowedTags::$attributes,
219
+			'meta'      => AllowedTags::$attributes,
220
+			'iframe'    => AllowedTags::$attributes,
221
+			'form'      => AllowedTags::$attributes,
222
+			'label'     => AllowedTags::$attributes,
223
+			'input'     => AllowedTags::$attributes,
224
+			'select'    => AllowedTags::$attributes,
225
+			'option'    => AllowedTags::$attributes,
226
+			'optgroup'  => AllowedTags::$attributes,
227
+			'textarea'  => AllowedTags::$attributes,
228
+			'button'    => AllowedTags::$attributes,
229
+			'fieldset'  => AllowedTags::$attributes,
230
+			'output'    => AllowedTags::$attributes,
231
+		];
232
+		AllowedTags::$allowed_with_full_tags = array_merge_recursive($all_tags, $full_tags);
233
+	}
234
+
235
+
236
+	/**
237
+	 * @return array[]
238
+	 */
239
+	public static function getAllowedTags()
240
+	{
241
+		if (empty(AllowedTags::$allowed_tags)) {
242
+			AllowedTags::initializeAllowedTags();
243
+		}
244
+		return AllowedTags::$allowed_tags;
245
+	}
246
+
247
+
248
+	/**
249
+	 * @return array[]
250
+	 */
251
+	public static function getWithEmbedTags()
252
+	{
253
+		if (empty(AllowedTags::$allowed_with_embed_tags)) {
254
+			AllowedTags::initializeWithEmbedTags();
255
+		}
256
+		return AllowedTags::$allowed_with_embed_tags;
257
+	}
258
+
259
+
260
+	/**
261
+	 * @return array[]
262
+	 */
263
+	public static function getWithFormTags()
264
+	{
265
+		if (empty(AllowedTags::$allowed_with_form_tags)) {
266
+			AllowedTags::initializeWithFormTags();
267
+		}
268
+		return AllowedTags::$allowed_with_form_tags;
269
+	}
270
+
271
+
272
+	/**
273
+	 * @return array[]
274
+	 */
275
+	public static function getWithScriptAndStyleTags()
276
+	{
277
+		if (empty(AllowedTags::$allowed_with_script_and_style_tags)) {
278
+			AllowedTags::initializeWithScriptAndStyleTags();
279
+		}
280
+		return AllowedTags::$allowed_with_script_and_style_tags;
281
+	}
282
+
283
+	/**
284
+	 * @return array[]
285
+	 */
286
+	public static function getWithFullTags()
287
+	{
288
+		if (empty(AllowedTags::$allowed_with_full_tags)) {
289
+			AllowedTags::initializeWithFullTags();
290
+		}
291
+		return AllowedTags::$allowed_with_full_tags;
292
+	}
293 293
 }
Please login to merge, or discard this patch.
core/EE_Front_Controller.core.php 1 patch
Indentation   +509 added lines, -509 removed lines patch added patch discarded remove patch
@@ -18,513 +18,513 @@
 block discarded – undo
18 18
 final class EE_Front_Controller
19 19
 {
20 20
 
21
-    /**
22
-     * @var string
23
-     */
24
-    private $_template_path;
25
-
26
-    /**
27
-     * @var string
28
-     */
29
-    private $_template;
30
-
31
-    /**
32
-     * @type EE_Registry
33
-     */
34
-    protected $Registry;
35
-
36
-    /**
37
-     * @type EE_Request_Handler
38
-     */
39
-    protected $Request_Handler;
40
-
41
-    /**
42
-     * @type EE_Module_Request_Router
43
-     */
44
-    protected $Module_Request_Router;
45
-
46
-    /**
47
-     * @type CurrentPage
48
-     */
49
-    protected $current_page;
50
-
51
-
52
-    /**
53
-     *    class constructor
54
-     *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
55
-     *
56
-     * @access    public
57
-     * @param EE_Registry              $Registry
58
-     * @param CurrentPage              $EspressoPage
59
-     * @param EE_Module_Request_Router $Module_Request_Router
60
-     */
61
-    public function __construct(
62
-        EE_Registry $Registry,
63
-        CurrentPage $EspressoPage,
64
-        EE_Module_Request_Router $Module_Request_Router
65
-    ) {
66
-        $this->Registry              = $Registry;
67
-        $this->current_page          = $EspressoPage;
68
-        $this->Module_Request_Router = $Module_Request_Router;
69
-        // load other resources and begin to actually run shortcodes and modules
70
-        // analyse the incoming WP request
71
-        add_action('parse_request', array($this, 'get_request'), 1, 1);
72
-        // process request with module factory
73
-        add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
74
-        // before headers sent
75
-        add_action('wp', array($this, 'wp'), 5);
76
-        // primarily used to process any content shortcodes
77
-        add_action('template_redirect', array($this, 'templateRedirect'), 999);
78
-        // header
79
-        add_action('wp_head', array($this, 'header_meta_tag'), 5);
80
-        add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
81
-        add_filter('template_include', array($this, 'template_include'), 1);
82
-        // display errors
83
-        add_action('loop_start', array($this, 'display_errors'), 2);
84
-        // the content
85
-        // add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
86
-        // exclude our private cpt comments
87
-        add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
88
-        // make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
89
-        add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
90
-        // action hook EE
91
-        do_action('AHEE__EE_Front_Controller__construct__done', $this);
92
-    }
93
-
94
-
95
-    /**
96
-     * @return EE_Request_Handler
97
-     * @deprecated 4.10.14.p
98
-     */
99
-    public function Request_Handler()
100
-    {
101
-        if (! $this->Request_Handler instanceof EE_Request_Handler) {
102
-            $this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
103
-        }
104
-        return $this->Request_Handler;
105
-    }
106
-
107
-
108
-    /**
109
-     * @return EE_Module_Request_Router
110
-     */
111
-    public function Module_Request_Router()
112
-    {
113
-        return $this->Module_Request_Router;
114
-    }
115
-
116
-
117
-    /**
118
-     * @return LegacyShortcodesManager
119
-     * @deprecated 4.10.14.p
120
-     */
121
-    public function getLegacyShortcodesManager()
122
-    {
123
-        return EE_Config::getLegacyShortcodesManager();
124
-    }
125
-
126
-
127
-
128
-
129
-
130
-    /***********************************************        INIT ACTION HOOK         ***********************************************/
131
-    /**
132
-     * filter_wp_comments
133
-     * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
134
-     * widgets/queries done on frontend
135
-     *
136
-     * @param  array $clauses array of comment clauses setup by WP_Comment_Query
137
-     * @return array array of comment clauses with modifications.
138
-     * @throws InvalidArgumentException
139
-     * @throws InvalidDataTypeException
140
-     * @throws InvalidInterfaceException
141
-     */
142
-    public function filter_wp_comments($clauses)
143
-    {
144
-        global $wpdb;
145
-        if (strpos($clauses['join'], $wpdb->posts) !== false) {
146
-            /** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
147
-            $custom_post_types = LoaderFactory::getLoader()->getShared(
148
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
149
-            );
150
-            $cpts = $custom_post_types->getPrivateCustomPostTypes();
151
-            foreach ($cpts as $cpt => $details) {
152
-                $clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
153
-            }
154
-        }
155
-        return $clauses;
156
-    }
157
-
158
-
159
-    /**
160
-     * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
161
-     *
162
-     * @param  string $url incoming url
163
-     * @return string         final assembled url
164
-     */
165
-    public function maybe_force_admin_ajax_ssl($url)
166
-    {
167
-        if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
168
-            $url = str_replace('http://', 'https://', $url);
169
-        }
170
-        return $url;
171
-    }
172
-
173
-
174
-
175
-
176
-
177
-
178
-    /***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
179
-
180
-
181
-    /**
182
-     *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
183
-     *    default priority init phases have run
184
-     *
185
-     * @access    public
186
-     * @return    void
187
-     */
188
-    public function wp_loaded()
189
-    {
190
-    }
191
-
192
-
193
-
194
-
195
-
196
-    /***********************************************        PARSE_REQUEST HOOK         ***********************************************/
197
-    /**
198
-     *    _get_request
199
-     *
200
-     * @access public
201
-     * @param WP $WP
202
-     * @return void
203
-     */
204
-    public function get_request(WP $WP)
205
-    {
206
-        do_action('AHEE__EE_Front_Controller__get_request__start');
207
-        $this->current_page->parseQueryVars($WP);
208
-        do_action('AHEE__EE_Front_Controller__get_request__complete');
209
-        remove_action('parse_request', [$this, 'get_request'], 1);
210
-    }
211
-
212
-
213
-    /**
214
-     *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
215
-     *
216
-     * @access    public
217
-     * @param WP_Query $WP_Query
218
-     * @return    void
219
-     * @throws EE_Error
220
-     * @throws ReflectionException
221
-     */
222
-    public function pre_get_posts($WP_Query)
223
-    {
224
-        // only load Module_Request_Router if this is the main query
225
-        if (
226
-            $this->Module_Request_Router instanceof EE_Module_Request_Router
227
-            && $WP_Query->is_main_query()
228
-        ) {
229
-            // cycle thru module routes
230
-            while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
231
-                // determine module and method for route
232
-                $module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
233
-                if ($module instanceof EED_Module) {
234
-                    // get registered view for route
235
-                    $this->_template_path = $this->Module_Request_Router->get_view($route);
236
-                    // grab module name
237
-                    $module_name = $module->module_name();
238
-                    // map the module to the module objects
239
-                    $this->Registry->modules->{$module_name} = $module;
240
-                }
241
-            }
242
-        }
243
-    }
244
-
245
-
246
-
247
-
248
-
249
-    /***********************************************        WP HOOK         ***********************************************/
250
-
251
-
252
-    /**
253
-     *    wp - basically last chance to do stuff before headers sent
254
-     *
255
-     * @access    public
256
-     * @return    void
257
-     */
258
-    public function wp()
259
-    {
260
-    }
261
-
262
-
263
-
264
-    /***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
265
-
266
-
267
-    /**
268
-     * callback for the "template_redirect" hook point
269
-     * checks sidebars for EE widgets
270
-     * loads resources and assets accordingly
271
-     *
272
-     * @return void
273
-     */
274
-    public function templateRedirect()
275
-    {
276
-        global $wp_query;
277
-        if (empty($wp_query->posts)) {
278
-            return;
279
-        }
280
-        // if we already know this is an espresso page, then load assets
281
-        $load_assets = $this->current_page->isEspressoPage();
282
-        // if we are already loading assets then just move along, otherwise check for widgets
283
-        $load_assets = $load_assets || $this->espresso_widgets_in_active_sidebars();
284
-        if ($load_assets) {
285
-            add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
286
-            add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
287
-        }
288
-    }
289
-
290
-
291
-    /**
292
-     * builds list of active widgets then scans active sidebars looking for them
293
-     * returns true is an EE widget is found in an active sidebar
294
-     * Please Note: this does NOT mean that the sidebar or widget
295
-     * is actually in use in a given template, as that is unfortunately not known
296
-     * until a sidebar and it's widgets are actually loaded
297
-     *
298
-     * @return boolean
299
-     */
300
-    private function espresso_widgets_in_active_sidebars()
301
-    {
302
-        $espresso_widgets = array();
303
-        foreach ($this->Registry->widgets as $widget_class => $widget) {
304
-            $id_base = EspressoWidget::getIdBase($widget_class);
305
-            if (is_active_widget(false, false, $id_base)) {
306
-                $espresso_widgets[] = $id_base;
307
-            }
308
-        }
309
-        $all_sidebar_widgets = wp_get_sidebars_widgets();
310
-        foreach ($all_sidebar_widgets as $sidebar_widgets) {
311
-            if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
312
-                foreach ($sidebar_widgets as $sidebar_widget) {
313
-                    foreach ($espresso_widgets as $espresso_widget) {
314
-                        if (strpos($sidebar_widget, $espresso_widget) !== false) {
315
-                            return true;
316
-                        }
317
-                    }
318
-                }
319
-            }
320
-        }
321
-        return false;
322
-    }
323
-
324
-
325
-    /**
326
-     *    header_meta_tag
327
-     *
328
-     * @access    public
329
-     * @return    void
330
-     */
331
-    public function header_meta_tag()
332
-    {
333
-        print(
334
-        apply_filters(
335
-            'FHEE__EE_Front_Controller__header_meta_tag',
336
-            '<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
337
-        )
338
-        );
339
-
340
-        // let's exclude all event type taxonomy term archive pages from search engine indexing
341
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/10249
342
-        // also exclude all critical pages from indexing
343
-        if (
344
-            (
345
-                is_tax('espresso_event_type')
346
-                && get_option('blog_public') !== '0'
347
-            )
348
-            || is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
349
-        ) {
350
-            print(
351
-            apply_filters(
352
-                'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
353
-                '<meta name="robots" content="noindex,follow" />' . "\n"
354
-            )
355
-            );
356
-        }
357
-    }
358
-
359
-
360
-    /**
361
-     * wp_print_scripts
362
-     *
363
-     * @return void
364
-     * @throws EE_Error
365
-     */
366
-    public function wp_print_scripts()
367
-    {
368
-        global $post;
369
-        if (
370
-            isset($post->EE_Event)
371
-            && $post->EE_Event instanceof EE_Event
372
-            && get_post_type() === 'espresso_events'
373
-            && is_singular()
374
-        ) {
375
-            EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
376
-        }
377
-    }
378
-
379
-
380
-    public function enqueueStyle()
381
-    {
382
-        wp_enqueue_style('espresso_default');
383
-        wp_enqueue_style('espresso_custom_css');
384
-    }
385
-
386
-
387
-
388
-    /***********************************************        WP_FOOTER         ***********************************************/
389
-
390
-
391
-    public function enqueueScripts()
392
-    {
393
-        wp_enqueue_script('espresso_core');
394
-    }
395
-
396
-
397
-    /**
398
-     * display_errors
399
-     *
400
-     * @access public
401
-     * @return void
402
-     * @throws DomainException
403
-     */
404
-    public function display_errors()
405
-    {
406
-        static $shown_already = false;
407
-        do_action('AHEE__EE_Front_Controller__display_errors__begin');
408
-        if (
409
-            ! $shown_already
410
-            && apply_filters('FHEE__EE_Front_Controller__display_errors', true)
411
-            && is_main_query()
412
-            && ! is_feed()
413
-            && in_the_loop()
414
-            && $this->current_page->isEspressoPage()
415
-        ) {
416
-            $shown_already = true;
417
-            if (did_action('wp_head')) {
418
-                echo wp_kses($this->printNotices(), AllowedTags::getAllowedTags());
419
-            } else {
420
-                // block enabled themes run their query loop before headers are sent
421
-                // so we need to add our notices onto the beginning of the content
422
-                add_filter('the_content', [$this, 'prependNotices'], 1, 1);
423
-            }
424
-        }
425
-        do_action('AHEE__EE_Front_Controller__display_errors__end');
426
-    }
427
-
428
-
429
-    /**
430
-     * @param string $the_content
431
-     * @return string
432
-     * @since 4.10.30.p
433
-     */
434
-    public function prependNotices($the_content)
435
-    {
436
-        $notices = $this->printNotices();
437
-        return $notices ? $notices . $the_content : $the_content;
438
-    }
439
-
440
-
441
-    /**
442
-     * @return false|string
443
-     * @since 4.10.30.p
444
-     */
445
-    public function printNotices()
446
-    {
447
-        ob_start();
448
-        echo wp_kses(EE_Error::get_notices(), AllowedTags::getWithFormTags());
449
-        EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
450
-        return ob_get_clean();
451
-    }
452
-
453
-
454
-
455
-    /***********************************************        UTILITIES         ***********************************************/
456
-
457
-
458
-    /**
459
-     * @param string $template_include_path
460
-     * @return string
461
-     * @throws EE_Error
462
-     * @throws ReflectionException
463
-     */
464
-    public function template_include($template_include_path = null)
465
-    {
466
-        if ($this->current_page->isEspressoPage()) {
467
-            // despite all helpers having autoloaders set, we need to manually load the template loader
468
-            // because there are some side effects in that class for triggering template tag functions
469
-            $this->Registry->load_helper('EEH_Template');
470
-            $this->_template_path = ! empty($this->_template_path)
471
-                ? basename($this->_template_path)
472
-                : basename(
473
-                    $template_include_path
474
-                );
475
-            $template_path = EEH_Template::locate_template($this->_template_path, array(), false);
476
-            $this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
477
-            $this->_template = basename($this->_template_path);
478
-            return $this->_template_path;
479
-        }
480
-        return $template_include_path;
481
-    }
482
-
483
-
484
-    /**
485
-     * @param bool $with_path
486
-     * @return    string
487
-     */
488
-    public function get_selected_template($with_path = false)
489
-    {
490
-        return $with_path ? $this->_template_path : $this->_template;
491
-    }
492
-
493
-
494
-    /**
495
-     * @param string $shortcode_class
496
-     * @param WP     $wp
497
-     * @throws ReflectionException
498
-     * @deprecated 4.9.26
499
-     */
500
-    public function initialize_shortcode($shortcode_class = '', WP $wp = null)
501
-    {
502
-        EE_Error::doing_it_wrong(
503
-            __METHOD__,
504
-            esc_html__(
505
-                'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
506
-                'event_espresso'
507
-            ),
508
-            '4.9.26'
509
-        );
510
-        $this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
511
-    }
512
-
513
-
514
-    /**
515
-     * @return void
516
-     * @deprecated 4.9.57.p
517
-     */
518
-    public function loadPersistentAdminNoticeManager()
519
-    {
520
-    }
521
-
522
-
523
-    /**
524
-     * @return void
525
-     * @deprecated 4.9.64.p
526
-     */
527
-    public function employ_CPT_Strategy()
528
-    {
529
-    }
21
+	/**
22
+	 * @var string
23
+	 */
24
+	private $_template_path;
25
+
26
+	/**
27
+	 * @var string
28
+	 */
29
+	private $_template;
30
+
31
+	/**
32
+	 * @type EE_Registry
33
+	 */
34
+	protected $Registry;
35
+
36
+	/**
37
+	 * @type EE_Request_Handler
38
+	 */
39
+	protected $Request_Handler;
40
+
41
+	/**
42
+	 * @type EE_Module_Request_Router
43
+	 */
44
+	protected $Module_Request_Router;
45
+
46
+	/**
47
+	 * @type CurrentPage
48
+	 */
49
+	protected $current_page;
50
+
51
+
52
+	/**
53
+	 *    class constructor
54
+	 *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
55
+	 *
56
+	 * @access    public
57
+	 * @param EE_Registry              $Registry
58
+	 * @param CurrentPage              $EspressoPage
59
+	 * @param EE_Module_Request_Router $Module_Request_Router
60
+	 */
61
+	public function __construct(
62
+		EE_Registry $Registry,
63
+		CurrentPage $EspressoPage,
64
+		EE_Module_Request_Router $Module_Request_Router
65
+	) {
66
+		$this->Registry              = $Registry;
67
+		$this->current_page          = $EspressoPage;
68
+		$this->Module_Request_Router = $Module_Request_Router;
69
+		// load other resources and begin to actually run shortcodes and modules
70
+		// analyse the incoming WP request
71
+		add_action('parse_request', array($this, 'get_request'), 1, 1);
72
+		// process request with module factory
73
+		add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
74
+		// before headers sent
75
+		add_action('wp', array($this, 'wp'), 5);
76
+		// primarily used to process any content shortcodes
77
+		add_action('template_redirect', array($this, 'templateRedirect'), 999);
78
+		// header
79
+		add_action('wp_head', array($this, 'header_meta_tag'), 5);
80
+		add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
81
+		add_filter('template_include', array($this, 'template_include'), 1);
82
+		// display errors
83
+		add_action('loop_start', array($this, 'display_errors'), 2);
84
+		// the content
85
+		// add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
86
+		// exclude our private cpt comments
87
+		add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
88
+		// make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
89
+		add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
90
+		// action hook EE
91
+		do_action('AHEE__EE_Front_Controller__construct__done', $this);
92
+	}
93
+
94
+
95
+	/**
96
+	 * @return EE_Request_Handler
97
+	 * @deprecated 4.10.14.p
98
+	 */
99
+	public function Request_Handler()
100
+	{
101
+		if (! $this->Request_Handler instanceof EE_Request_Handler) {
102
+			$this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
103
+		}
104
+		return $this->Request_Handler;
105
+	}
106
+
107
+
108
+	/**
109
+	 * @return EE_Module_Request_Router
110
+	 */
111
+	public function Module_Request_Router()
112
+	{
113
+		return $this->Module_Request_Router;
114
+	}
115
+
116
+
117
+	/**
118
+	 * @return LegacyShortcodesManager
119
+	 * @deprecated 4.10.14.p
120
+	 */
121
+	public function getLegacyShortcodesManager()
122
+	{
123
+		return EE_Config::getLegacyShortcodesManager();
124
+	}
125
+
126
+
127
+
128
+
129
+
130
+	/***********************************************        INIT ACTION HOOK         ***********************************************/
131
+	/**
132
+	 * filter_wp_comments
133
+	 * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
134
+	 * widgets/queries done on frontend
135
+	 *
136
+	 * @param  array $clauses array of comment clauses setup by WP_Comment_Query
137
+	 * @return array array of comment clauses with modifications.
138
+	 * @throws InvalidArgumentException
139
+	 * @throws InvalidDataTypeException
140
+	 * @throws InvalidInterfaceException
141
+	 */
142
+	public function filter_wp_comments($clauses)
143
+	{
144
+		global $wpdb;
145
+		if (strpos($clauses['join'], $wpdb->posts) !== false) {
146
+			/** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
147
+			$custom_post_types = LoaderFactory::getLoader()->getShared(
148
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
149
+			);
150
+			$cpts = $custom_post_types->getPrivateCustomPostTypes();
151
+			foreach ($cpts as $cpt => $details) {
152
+				$clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
153
+			}
154
+		}
155
+		return $clauses;
156
+	}
157
+
158
+
159
+	/**
160
+	 * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
161
+	 *
162
+	 * @param  string $url incoming url
163
+	 * @return string         final assembled url
164
+	 */
165
+	public function maybe_force_admin_ajax_ssl($url)
166
+	{
167
+		if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
168
+			$url = str_replace('http://', 'https://', $url);
169
+		}
170
+		return $url;
171
+	}
172
+
173
+
174
+
175
+
176
+
177
+
178
+	/***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
179
+
180
+
181
+	/**
182
+	 *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
183
+	 *    default priority init phases have run
184
+	 *
185
+	 * @access    public
186
+	 * @return    void
187
+	 */
188
+	public function wp_loaded()
189
+	{
190
+	}
191
+
192
+
193
+
194
+
195
+
196
+	/***********************************************        PARSE_REQUEST HOOK         ***********************************************/
197
+	/**
198
+	 *    _get_request
199
+	 *
200
+	 * @access public
201
+	 * @param WP $WP
202
+	 * @return void
203
+	 */
204
+	public function get_request(WP $WP)
205
+	{
206
+		do_action('AHEE__EE_Front_Controller__get_request__start');
207
+		$this->current_page->parseQueryVars($WP);
208
+		do_action('AHEE__EE_Front_Controller__get_request__complete');
209
+		remove_action('parse_request', [$this, 'get_request'], 1);
210
+	}
211
+
212
+
213
+	/**
214
+	 *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
215
+	 *
216
+	 * @access    public
217
+	 * @param WP_Query $WP_Query
218
+	 * @return    void
219
+	 * @throws EE_Error
220
+	 * @throws ReflectionException
221
+	 */
222
+	public function pre_get_posts($WP_Query)
223
+	{
224
+		// only load Module_Request_Router if this is the main query
225
+		if (
226
+			$this->Module_Request_Router instanceof EE_Module_Request_Router
227
+			&& $WP_Query->is_main_query()
228
+		) {
229
+			// cycle thru module routes
230
+			while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
231
+				// determine module and method for route
232
+				$module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
233
+				if ($module instanceof EED_Module) {
234
+					// get registered view for route
235
+					$this->_template_path = $this->Module_Request_Router->get_view($route);
236
+					// grab module name
237
+					$module_name = $module->module_name();
238
+					// map the module to the module objects
239
+					$this->Registry->modules->{$module_name} = $module;
240
+				}
241
+			}
242
+		}
243
+	}
244
+
245
+
246
+
247
+
248
+
249
+	/***********************************************        WP HOOK         ***********************************************/
250
+
251
+
252
+	/**
253
+	 *    wp - basically last chance to do stuff before headers sent
254
+	 *
255
+	 * @access    public
256
+	 * @return    void
257
+	 */
258
+	public function wp()
259
+	{
260
+	}
261
+
262
+
263
+
264
+	/***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
265
+
266
+
267
+	/**
268
+	 * callback for the "template_redirect" hook point
269
+	 * checks sidebars for EE widgets
270
+	 * loads resources and assets accordingly
271
+	 *
272
+	 * @return void
273
+	 */
274
+	public function templateRedirect()
275
+	{
276
+		global $wp_query;
277
+		if (empty($wp_query->posts)) {
278
+			return;
279
+		}
280
+		// if we already know this is an espresso page, then load assets
281
+		$load_assets = $this->current_page->isEspressoPage();
282
+		// if we are already loading assets then just move along, otherwise check for widgets
283
+		$load_assets = $load_assets || $this->espresso_widgets_in_active_sidebars();
284
+		if ($load_assets) {
285
+			add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
286
+			add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
287
+		}
288
+	}
289
+
290
+
291
+	/**
292
+	 * builds list of active widgets then scans active sidebars looking for them
293
+	 * returns true is an EE widget is found in an active sidebar
294
+	 * Please Note: this does NOT mean that the sidebar or widget
295
+	 * is actually in use in a given template, as that is unfortunately not known
296
+	 * until a sidebar and it's widgets are actually loaded
297
+	 *
298
+	 * @return boolean
299
+	 */
300
+	private function espresso_widgets_in_active_sidebars()
301
+	{
302
+		$espresso_widgets = array();
303
+		foreach ($this->Registry->widgets as $widget_class => $widget) {
304
+			$id_base = EspressoWidget::getIdBase($widget_class);
305
+			if (is_active_widget(false, false, $id_base)) {
306
+				$espresso_widgets[] = $id_base;
307
+			}
308
+		}
309
+		$all_sidebar_widgets = wp_get_sidebars_widgets();
310
+		foreach ($all_sidebar_widgets as $sidebar_widgets) {
311
+			if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
312
+				foreach ($sidebar_widgets as $sidebar_widget) {
313
+					foreach ($espresso_widgets as $espresso_widget) {
314
+						if (strpos($sidebar_widget, $espresso_widget) !== false) {
315
+							return true;
316
+						}
317
+					}
318
+				}
319
+			}
320
+		}
321
+		return false;
322
+	}
323
+
324
+
325
+	/**
326
+	 *    header_meta_tag
327
+	 *
328
+	 * @access    public
329
+	 * @return    void
330
+	 */
331
+	public function header_meta_tag()
332
+	{
333
+		print(
334
+		apply_filters(
335
+			'FHEE__EE_Front_Controller__header_meta_tag',
336
+			'<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
337
+		)
338
+		);
339
+
340
+		// let's exclude all event type taxonomy term archive pages from search engine indexing
341
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/10249
342
+		// also exclude all critical pages from indexing
343
+		if (
344
+			(
345
+				is_tax('espresso_event_type')
346
+				&& get_option('blog_public') !== '0'
347
+			)
348
+			|| is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
349
+		) {
350
+			print(
351
+			apply_filters(
352
+				'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
353
+				'<meta name="robots" content="noindex,follow" />' . "\n"
354
+			)
355
+			);
356
+		}
357
+	}
358
+
359
+
360
+	/**
361
+	 * wp_print_scripts
362
+	 *
363
+	 * @return void
364
+	 * @throws EE_Error
365
+	 */
366
+	public function wp_print_scripts()
367
+	{
368
+		global $post;
369
+		if (
370
+			isset($post->EE_Event)
371
+			&& $post->EE_Event instanceof EE_Event
372
+			&& get_post_type() === 'espresso_events'
373
+			&& is_singular()
374
+		) {
375
+			EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
376
+		}
377
+	}
378
+
379
+
380
+	public function enqueueStyle()
381
+	{
382
+		wp_enqueue_style('espresso_default');
383
+		wp_enqueue_style('espresso_custom_css');
384
+	}
385
+
386
+
387
+
388
+	/***********************************************        WP_FOOTER         ***********************************************/
389
+
390
+
391
+	public function enqueueScripts()
392
+	{
393
+		wp_enqueue_script('espresso_core');
394
+	}
395
+
396
+
397
+	/**
398
+	 * display_errors
399
+	 *
400
+	 * @access public
401
+	 * @return void
402
+	 * @throws DomainException
403
+	 */
404
+	public function display_errors()
405
+	{
406
+		static $shown_already = false;
407
+		do_action('AHEE__EE_Front_Controller__display_errors__begin');
408
+		if (
409
+			! $shown_already
410
+			&& apply_filters('FHEE__EE_Front_Controller__display_errors', true)
411
+			&& is_main_query()
412
+			&& ! is_feed()
413
+			&& in_the_loop()
414
+			&& $this->current_page->isEspressoPage()
415
+		) {
416
+			$shown_already = true;
417
+			if (did_action('wp_head')) {
418
+				echo wp_kses($this->printNotices(), AllowedTags::getAllowedTags());
419
+			} else {
420
+				// block enabled themes run their query loop before headers are sent
421
+				// so we need to add our notices onto the beginning of the content
422
+				add_filter('the_content', [$this, 'prependNotices'], 1, 1);
423
+			}
424
+		}
425
+		do_action('AHEE__EE_Front_Controller__display_errors__end');
426
+	}
427
+
428
+
429
+	/**
430
+	 * @param string $the_content
431
+	 * @return string
432
+	 * @since 4.10.30.p
433
+	 */
434
+	public function prependNotices($the_content)
435
+	{
436
+		$notices = $this->printNotices();
437
+		return $notices ? $notices . $the_content : $the_content;
438
+	}
439
+
440
+
441
+	/**
442
+	 * @return false|string
443
+	 * @since 4.10.30.p
444
+	 */
445
+	public function printNotices()
446
+	{
447
+		ob_start();
448
+		echo wp_kses(EE_Error::get_notices(), AllowedTags::getWithFormTags());
449
+		EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
450
+		return ob_get_clean();
451
+	}
452
+
453
+
454
+
455
+	/***********************************************        UTILITIES         ***********************************************/
456
+
457
+
458
+	/**
459
+	 * @param string $template_include_path
460
+	 * @return string
461
+	 * @throws EE_Error
462
+	 * @throws ReflectionException
463
+	 */
464
+	public function template_include($template_include_path = null)
465
+	{
466
+		if ($this->current_page->isEspressoPage()) {
467
+			// despite all helpers having autoloaders set, we need to manually load the template loader
468
+			// because there are some side effects in that class for triggering template tag functions
469
+			$this->Registry->load_helper('EEH_Template');
470
+			$this->_template_path = ! empty($this->_template_path)
471
+				? basename($this->_template_path)
472
+				: basename(
473
+					$template_include_path
474
+				);
475
+			$template_path = EEH_Template::locate_template($this->_template_path, array(), false);
476
+			$this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
477
+			$this->_template = basename($this->_template_path);
478
+			return $this->_template_path;
479
+		}
480
+		return $template_include_path;
481
+	}
482
+
483
+
484
+	/**
485
+	 * @param bool $with_path
486
+	 * @return    string
487
+	 */
488
+	public function get_selected_template($with_path = false)
489
+	{
490
+		return $with_path ? $this->_template_path : $this->_template;
491
+	}
492
+
493
+
494
+	/**
495
+	 * @param string $shortcode_class
496
+	 * @param WP     $wp
497
+	 * @throws ReflectionException
498
+	 * @deprecated 4.9.26
499
+	 */
500
+	public function initialize_shortcode($shortcode_class = '', WP $wp = null)
501
+	{
502
+		EE_Error::doing_it_wrong(
503
+			__METHOD__,
504
+			esc_html__(
505
+				'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
506
+				'event_espresso'
507
+			),
508
+			'4.9.26'
509
+		);
510
+		$this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
511
+	}
512
+
513
+
514
+	/**
515
+	 * @return void
516
+	 * @deprecated 4.9.57.p
517
+	 */
518
+	public function loadPersistentAdminNoticeManager()
519
+	{
520
+	}
521
+
522
+
523
+	/**
524
+	 * @return void
525
+	 * @deprecated 4.9.64.p
526
+	 */
527
+	public function employ_CPT_Strategy()
528
+	{
529
+	}
530 530
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/base/EE_Form_Section_Proper.form.php 1 patch
Indentation   +1528 added lines, -1528 removed lines patch added patch discarded remove patch
@@ -16,1532 +16,1532 @@
 block discarded – undo
16 16
 class EE_Form_Section_Proper extends EE_Form_Section_Validatable
17 17
 {
18 18
 
19
-    const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
20
-
21
-    /**
22
-     * Subsections
23
-     *
24
-     * @var EE_Form_Section_Validatable[]
25
-     */
26
-    protected $_subsections = array();
27
-
28
-    /**
29
-     * Strategy for laying out the form
30
-     *
31
-     * @var EE_Form_Section_Layout_Base
32
-     */
33
-    protected $_layout_strategy;
34
-
35
-    /**
36
-     * Whether or not this form has received and validated a form submission yet
37
-     *
38
-     * @var boolean
39
-     */
40
-    protected $_received_submission = false;
41
-
42
-    /**
43
-     * message displayed to users upon successful form submission
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_form_submission_success_message = '';
48
-
49
-    /**
50
-     * message displayed to users upon unsuccessful form submission
51
-     *
52
-     * @var string
53
-     */
54
-    protected $_form_submission_error_message = '';
55
-
56
-    /**
57
-     * @var array like post / request
58
-     */
59
-    protected $cached_request_data;
60
-
61
-    /**
62
-     * Stores whether this form (and its sub-sections) were found to be valid or not.
63
-     * Starts off as null, but once the form is validated, it set to either true or false
64
-     * @var boolean|null
65
-     */
66
-    protected $is_valid;
67
-
68
-    /**
69
-     * Stores all the data that will localized for form validation
70
-     *
71
-     * @var array
72
-     */
73
-    protected static $_js_localization = array();
74
-
75
-    /**
76
-     * whether or not the form's localized validation JS vars have been set
77
-     *
78
-     * @type boolean
79
-     */
80
-    protected static $_scripts_localized = false;
81
-
82
-
83
-    /**
84
-     * when constructing a proper form section, calls _construct_finalize on children
85
-     * so that they know who their parent is, and what name they've been given.
86
-     *
87
-     * @param array[] $options_array   {
88
-     * @type          $subsections     EE_Form_Section_Validatable[] where keys are the section's name
89
-     * @type          $include         string[] numerically-indexed where values are section names to be included,
90
-     *                                 and in that order. This is handy if you want
91
-     *                                 the subsections to be ordered differently than the default, and if you override
92
-     *                                 which fields are shown
93
-     * @type          $exclude         string[] values are subsections to be excluded. This is handy if you want
94
-     *                                 to remove certain default subsections (note: if you specify BOTH 'include' AND
95
-     *                                 'exclude', the inclusions will be applied first, and the exclusions will exclude
96
-     *                                 items from that list of inclusions)
97
-     * @type          $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
98
-     *                                 } @see EE_Form_Section_Validatable::__construct()
99
-     * @throws EE_Error
100
-     */
101
-    public function __construct($options_array = array())
102
-    {
103
-        $options_array = (array) apply_filters(
104
-            'FHEE__EE_Form_Section_Proper___construct__options_array',
105
-            $options_array,
106
-            $this
107
-        );
108
-        // call parent first, as it may be setting the name
109
-        parent::__construct($options_array);
110
-        // if they've included subsections in the constructor, add them now
111
-        if (isset($options_array['include'])) {
112
-            // we are going to make sure we ONLY have those subsections to include
113
-            // AND we are going to make sure they're in that specified order
114
-            $reordered_subsections = array();
115
-            foreach ($options_array['include'] as $input_name) {
116
-                if (isset($this->_subsections[ $input_name ])) {
117
-                    $reordered_subsections[ $input_name ] = $this->_subsections[ $input_name ];
118
-                }
119
-            }
120
-            $this->_subsections = $reordered_subsections;
121
-        }
122
-        if (isset($options_array['exclude'])) {
123
-            $exclude            = $options_array['exclude'];
124
-            $this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
125
-        }
126
-        if (isset($options_array['layout_strategy'])) {
127
-            $this->_layout_strategy = $options_array['layout_strategy'];
128
-        }
129
-        if (! $this->_layout_strategy) {
130
-            $this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
131
-        }
132
-        $this->_layout_strategy->_construct_finalize($this);
133
-        // ok so we are definitely going to want the forms JS,
134
-        // so enqueue it or remember to enqueue it during wp_enqueue_scripts
135
-        if (did_action('wp_enqueue_scripts') || did_action('admin_enqueue_scripts')) {
136
-            // ok so they've constructed this object after when they should have.
137
-            // just enqueue the generic form scripts and initialize the form immediately in the JS
138
-            EE_Form_Section_Proper::wp_enqueue_scripts(true);
139
-        } else {
140
-            add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
141
-            add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
142
-        }
143
-        add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
144
-        /**
145
-         * Gives other plugins a chance to hook in before construct finalize is called.
146
-         * The form probably doesn't yet have a parent form section.
147
-         * Since 4.9.32, when this action was introduced, this is the best place to add a subsection onto a form,
148
-         * assuming you don't care what the form section's name, HTML ID, or HTML name etc are.
149
-         * Also see AHEE__EE_Form_Section_Proper___construct_finalize__end
150
-         *
151
-         * @since 4.9.32
152
-         * @param EE_Form_Section_Proper $this          before __construct is done, but all of its logic,
153
-         *                                              except maybe calling _construct_finalize has been done
154
-         * @param array                  $options_array options passed into the constructor
155
-         */
156
-        do_action(
157
-            'AHEE__EE_Form_Input_Base___construct__before_construct_finalize_called',
158
-            $this,
159
-            $options_array
160
-        );
161
-        if (isset($options_array['name'])) {
162
-            $this->_construct_finalize(null, $options_array['name']);
163
-        }
164
-    }
165
-
166
-
167
-    /**
168
-     * Finishes construction given the parent form section and this form section's name
169
-     *
170
-     * @param EE_Form_Section_Proper $parent_form_section
171
-     * @param string                 $name
172
-     * @throws EE_Error
173
-     */
174
-    public function _construct_finalize($parent_form_section, $name)
175
-    {
176
-        parent::_construct_finalize($parent_form_section, $name);
177
-        $this->_set_default_name_if_empty();
178
-        $this->_set_default_html_id_if_empty();
179
-        foreach ($this->_subsections as $subsection_name => $subsection) {
180
-            if ($subsection instanceof EE_Form_Section_Base) {
181
-                $subsection->_construct_finalize($this, $subsection_name);
182
-            } else {
183
-                throw new EE_Error(
184
-                    sprintf(
185
-                        esc_html__(
186
-                            'Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
187
-                            'event_espresso'
188
-                        ),
189
-                        $subsection_name,
190
-                        get_class($this),
191
-                        $subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
192
-                    )
193
-                );
194
-            }
195
-        }
196
-        /**
197
-         * Action performed just after form has been given a name (and HTML ID etc) and is fully constructed.
198
-         * If you have code that should modify the form and needs it and its subsections to have a name, HTML ID
199
-         * (or other attributes derived from the name like the HTML label id, etc), this is where it should be done.
200
-         * This might only happen just before displaying the form, or just before it receives form submission data.
201
-         * If you need to modify the form or its subsections before _construct_finalize is called on it (and we've
202
-         * ensured it has a name, HTML IDs, etc
203
-         *
204
-         * @param EE_Form_Section_Proper      $this
205
-         * @param EE_Form_Section_Proper|null $parent_form_section
206
-         * @param string                      $name
207
-         */
208
-        do_action(
209
-            'AHEE__EE_Form_Section_Proper___construct_finalize__end',
210
-            $this,
211
-            $parent_form_section,
212
-            $name
213
-        );
214
-    }
215
-
216
-
217
-    /**
218
-     * Gets the layout strategy for this form section
219
-     *
220
-     * @return EE_Form_Section_Layout_Base
221
-     */
222
-    public function get_layout_strategy()
223
-    {
224
-        return $this->_layout_strategy;
225
-    }
226
-
227
-
228
-    /**
229
-     * Gets the HTML for a single input for this form section according
230
-     * to the layout strategy
231
-     *
232
-     * @param EE_Form_Input_Base $input
233
-     * @return string
234
-     */
235
-    public function get_html_for_input($input)
236
-    {
237
-        return $this->_layout_strategy->layout_input($input);
238
-    }
239
-
240
-
241
-    /**
242
-     * was_submitted - checks if form inputs are present in request data
243
-     * Basically an alias for form_data_present_in() (which is used by both
244
-     * proper form sections and form inputs)
245
-     *
246
-     * @param null $form_data
247
-     * @return boolean
248
-     * @throws EE_Error
249
-     */
250
-    public function was_submitted($form_data = null)
251
-    {
252
-        return $this->form_data_present_in($form_data);
253
-    }
254
-
255
-    /**
256
-     * Gets the cached request data; but if there is none, or $req_data was set with
257
-     * something different, refresh the cache, and then return it
258
-     * @param null $req_data
259
-     * @return array
260
-     */
261
-    protected function getCachedRequest($req_data = null)
262
-    {
263
-        if (
264
-            $this->cached_request_data === null
265
-            || (
266
-                $req_data !== null
267
-                && $req_data !== $this->cached_request_data
268
-            )
269
-        ) {
270
-            $req_data = apply_filters(
271
-                'FHEE__EE_Form_Section_Proper__receive_form_submission__req_data',
272
-                $req_data,
273
-                $this
274
-            );
275
-            if ($req_data === null) {
276
-                /** @var RequestInterface $request */
277
-                $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
278
-                $req_data = $request->requestParams();
279
-            }
280
-            $req_data = apply_filters(
281
-                'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
282
-                $req_data,
283
-                $this
284
-            );
285
-            $this->cached_request_data = (array) $req_data;
286
-        }
287
-        return $this->cached_request_data;
288
-    }
289
-
290
-
291
-    /**
292
-     * After the form section is initially created, call this to sanitize the data in the submission
293
-     * which relates to this form section, validate it, and set it as properties on the form.
294
-     *
295
-     * @param array|null $req_data should usually be post data (the default).
296
-     *                             However, you CAN supply a different array.
297
-     *                             Consider using set_defaults() instead however.
298
-     *                             (If you rendered the form in the page using $form_x->get_html()
299
-     *                             the inputs will have the correct name in the request data for this function
300
-     *                             to find them and populate the form with them.
301
-     *                             If you have a flat form (with only input subsections),
302
-     *                             you can supply a flat array where keys
303
-     *                             are the form input names and values are their values)
304
-     * @param boolean    $validate whether or not to perform validation on this data. Default is,
305
-     *                             of course, to validate that data, and set errors on the invalid values.
306
-     *                             But if the data has already been validated
307
-     *                             (eg you validated the data then stored it in the DB)
308
-     *                             you may want to skip this step.
309
-     * @throws InvalidArgumentException
310
-     * @throws InvalidInterfaceException
311
-     * @throws InvalidDataTypeException
312
-     * @throws EE_Error
313
-     */
314
-    public function receive_form_submission($req_data = null, $validate = true)
315
-    {
316
-        $req_data = $this->getCachedRequest($req_data);
317
-        $this->_normalize($req_data);
318
-        if ($validate) {
319
-            $this->_validate();
320
-            // if it's invalid, we're going to want to re-display so remember what they submitted
321
-            if (! $this->is_valid()) {
322
-                $this->store_submitted_form_data_in_session();
323
-            }
324
-        }
325
-        if ($this->submission_error_message() === '' && ! $this->is_valid()) {
326
-            $this->set_submission_error_message();
327
-        }
328
-        do_action(
329
-            'AHEE__EE_Form_Section_Proper__receive_form_submission__end',
330
-            $req_data,
331
-            $this,
332
-            $validate
333
-        );
334
-    }
335
-
336
-
337
-    /**
338
-     * caches the originally submitted input values in the session
339
-     * so that they can be used to repopulate the form if it failed validation
340
-     *
341
-     * @return boolean whether or not the data was successfully stored in the session
342
-     * @throws InvalidArgumentException
343
-     * @throws InvalidInterfaceException
344
-     * @throws InvalidDataTypeException
345
-     * @throws EE_Error
346
-     */
347
-    protected function store_submitted_form_data_in_session()
348
-    {
349
-        return EE_Registry::instance()->SSN->set_session_data(
350
-            array(
351
-                EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
352
-            )
353
-        );
354
-    }
355
-
356
-
357
-    /**
358
-     * retrieves the originally submitted input values in the session
359
-     * so that they can be used to repopulate the form if it failed validation
360
-     *
361
-     * @return array
362
-     * @throws InvalidArgumentException
363
-     * @throws InvalidInterfaceException
364
-     * @throws InvalidDataTypeException
365
-     */
366
-    protected function get_submitted_form_data_from_session()
367
-    {
368
-        $session = EE_Registry::instance()->SSN;
369
-        if ($session instanceof EE_Session) {
370
-            return $session->get_session_data(
371
-                EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
372
-            );
373
-        }
374
-        return array();
375
-    }
376
-
377
-
378
-    /**
379
-     * flushed the originally submitted input values from the session
380
-     *
381
-     * @return boolean whether or not the data was successfully removed from the session
382
-     * @throws InvalidArgumentException
383
-     * @throws InvalidInterfaceException
384
-     * @throws InvalidDataTypeException
385
-     */
386
-    public static function flush_submitted_form_data_from_session()
387
-    {
388
-        return EE_Registry::instance()->SSN->reset_data(
389
-            array(EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
390
-        );
391
-    }
392
-
393
-
394
-    /**
395
-     * Populates this form and its subsections with data from the session.
396
-     * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
397
-     * validation errors when displaying too)
398
-     * Returns true if the form was populated from the session, false otherwise
399
-     *
400
-     * @return boolean
401
-     * @throws InvalidArgumentException
402
-     * @throws InvalidInterfaceException
403
-     * @throws InvalidDataTypeException
404
-     * @throws EE_Error
405
-     */
406
-    public function populate_from_session()
407
-    {
408
-        $form_data_in_session = $this->get_submitted_form_data_from_session();
409
-        if (empty($form_data_in_session)) {
410
-            return false;
411
-        }
412
-        $this->receive_form_submission($form_data_in_session);
413
-        add_action('shutdown', array('EE_Form_Section_Proper', 'flush_submitted_form_data_from_session'));
414
-        if ($this->form_data_present_in($form_data_in_session)) {
415
-            return true;
416
-        }
417
-        return false;
418
-    }
419
-
420
-
421
-    /**
422
-     * Populates the default data for the form, given an array where keys are
423
-     * the input names, and values are their values (preferably normalized to be their
424
-     * proper PHP types, not all strings... although that should be ok too).
425
-     * Proper subsections are sub-arrays, the key being the subsection's name, and
426
-     * the value being an array formatted in teh same way
427
-     *
428
-     * @param array $default_data
429
-     * @throws EE_Error
430
-     */
431
-    public function populate_defaults($default_data)
432
-    {
433
-        foreach ($this->subsections(false) as $subsection_name => $subsection) {
434
-            if (isset($default_data[ $subsection_name ])) {
435
-                if ($subsection instanceof EE_Form_Input_Base) {
436
-                    $subsection->set_default($default_data[ $subsection_name ]);
437
-                } elseif ($subsection instanceof EE_Form_Section_Proper) {
438
-                    $subsection->populate_defaults($default_data[ $subsection_name ]);
439
-                }
440
-            }
441
-        }
442
-    }
443
-
444
-
445
-    /**
446
-     * returns true if subsection exists
447
-     *
448
-     * @param string $name
449
-     * @return boolean
450
-     */
451
-    public function subsection_exists($name)
452
-    {
453
-        return isset($this->_subsections[ $name ]) ? true : false;
454
-    }
455
-
456
-
457
-    /**
458
-     * Gets the subsection specified by its name
459
-     *
460
-     * @param string  $name
461
-     * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
462
-     *                                                      so that the inputs will be properly configured.
463
-     *                                                      However, some client code may be ok
464
-     *                                                      with construction finalize being called later
465
-     *                                                      (realizing that the subsections' html names
466
-     *                                                      might not be set yet, etc.)
467
-     * @return EE_Form_Section_Base
468
-     * @throws EE_Error
469
-     */
470
-    public function get_subsection($name, $require_construction_to_be_finalized = true)
471
-    {
472
-        if ($require_construction_to_be_finalized) {
473
-            $this->ensure_construct_finalized_called();
474
-        }
475
-        return $this->subsection_exists($name) ? $this->_subsections[ $name ] : null;
476
-    }
477
-
478
-
479
-    /**
480
-     * Gets all the validatable subsections of this form section
481
-     *
482
-     * @return EE_Form_Section_Validatable[]
483
-     * @throws EE_Error
484
-     */
485
-    public function get_validatable_subsections()
486
-    {
487
-        $validatable_subsections = array();
488
-        foreach ($this->subsections() as $name => $obj) {
489
-            if ($obj instanceof EE_Form_Section_Validatable) {
490
-                $validatable_subsections[ $name ] = $obj;
491
-            }
492
-        }
493
-        return $validatable_subsections;
494
-    }
495
-
496
-
497
-    /**
498
-     * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
499
-     * throw an EE_Error.
500
-     *
501
-     * @param string  $name
502
-     * @param boolean $require_construction_to_be_finalized most client code should
503
-     *                                                      leave this as TRUE so that the inputs will be properly
504
-     *                                                      configured. However, some client code may be ok with
505
-     *                                                      construction finalize being called later
506
-     *                                                      (realizing that the subsections' html names might not be
507
-     *                                                      set yet, etc.)
508
-     * @return EE_Form_Input_Base
509
-     * @throws EE_Error
510
-     */
511
-    public function get_input($name, $require_construction_to_be_finalized = true)
512
-    {
513
-        $subsection = $this->get_subsection(
514
-            $name,
515
-            $require_construction_to_be_finalized
516
-        );
517
-        if (! $subsection instanceof EE_Form_Input_Base) {
518
-            throw new EE_Error(
519
-                sprintf(
520
-                    esc_html__(
521
-                        "Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
522
-                        'event_espresso'
523
-                    ),
524
-                    $name,
525
-                    get_class($this),
526
-                    $subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
527
-                )
528
-            );
529
-        }
530
-        return $subsection;
531
-    }
532
-
533
-
534
-    /**
535
-     * Like get_input(), gets the proper subsection of the form given the name,
536
-     * otherwise throws an EE_Error
537
-     *
538
-     * @param string  $name
539
-     * @param boolean $require_construction_to_be_finalized most client code should
540
-     *                                                      leave this as TRUE so that the inputs will be properly
541
-     *                                                      configured. However, some client code may be ok with
542
-     *                                                      construction finalize being called later
543
-     *                                                      (realizing that the subsections' html names might not be
544
-     *                                                      set yet, etc.)
545
-     * @return EE_Form_Section_Proper
546
-     * @throws EE_Error
547
-     */
548
-    public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
549
-    {
550
-        $subsection = $this->get_subsection(
551
-            $name,
552
-            $require_construction_to_be_finalized
553
-        );
554
-        if (! $subsection instanceof EE_Form_Section_Proper) {
555
-            throw new EE_Error(
556
-                sprintf(
557
-                    esc_html__(
558
-                        "Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'",
559
-                        'event_espresso'
560
-                    ),
561
-                    $name,
562
-                    get_class($this)
563
-                )
564
-            );
565
-        }
566
-        return $subsection;
567
-    }
568
-
569
-
570
-    /**
571
-     * Gets the value of the specified input. Should be called after receive_form_submission()
572
-     * or populate_defaults() on the form, where the normalized value on the input is set.
573
-     *
574
-     * @param string $name
575
-     * @return mixed depending on the input's type and its normalization strategy
576
-     * @throws EE_Error
577
-     */
578
-    public function get_input_value($name)
579
-    {
580
-        $input = $this->get_input($name);
581
-        return $input->normalized_value();
582
-    }
583
-
584
-
585
-    /**
586
-     * Checks if this form section itself is valid, and then checks its subsections
587
-     *
588
-     * @throws EE_Error
589
-     * @return boolean
590
-     */
591
-    public function is_valid()
592
-    {
593
-        if ($this->is_valid === null) {
594
-            if (! $this->has_received_submission()) {
595
-                throw new EE_Error(
596
-                    sprintf(
597
-                        esc_html__(
598
-                            'You cannot check if a form is valid before receiving the form submission using receive_form_submission',
599
-                            'event_espresso'
600
-                        )
601
-                    )
602
-                );
603
-            }
604
-            if (! parent::is_valid()) {
605
-                $this->is_valid = false;
606
-            } else {
607
-                // ok so no general errors to this entire form section.
608
-                // so let's check the subsections, but only set errors if that hasn't been done yet
609
-                $this->is_valid = true;
610
-                foreach ($this->get_validatable_subsections() as $subsection) {
611
-                    if (! $subsection->is_valid()) {
612
-                        $this->is_valid = false;
613
-                    }
614
-                }
615
-            }
616
-        }
617
-        return $this->is_valid;
618
-    }
619
-
620
-
621
-    /**
622
-     * gets the default name of this form section if none is specified
623
-     *
624
-     * @return void
625
-     */
626
-    protected function _set_default_name_if_empty()
627
-    {
628
-        if (! $this->_name) {
629
-            $classname    = get_class($this);
630
-            $default_name = str_replace('EE_', '', $classname);
631
-            $this->_name  = $default_name;
632
-        }
633
-    }
634
-
635
-
636
-    /**
637
-     * Returns the HTML for the form, except for the form opening and closing tags
638
-     * (as the form section doesn't know where you necessarily want to send the information to),
639
-     * and except for a submit button. Enqueues JS and CSS; if called early enough we will
640
-     * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
641
-     * Not doing_it_wrong because theoretically this CAN be used properly,
642
-     * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
643
-     * any CSS.
644
-     *
645
-     * @throws InvalidArgumentException
646
-     * @throws InvalidInterfaceException
647
-     * @throws InvalidDataTypeException
648
-     * @throws EE_Error
649
-     */
650
-    public function get_html_and_js()
651
-    {
652
-        $this->enqueue_js();
653
-        return $this->get_html();
654
-    }
655
-
656
-
657
-    /**
658
-     * returns HTML for displaying this form section. recursively calls display_section() on all subsections
659
-     *
660
-     * @param bool $display_previously_submitted_data
661
-     * @return string
662
-     * @throws InvalidArgumentException
663
-     * @throws InvalidInterfaceException
664
-     * @throws InvalidDataTypeException
665
-     * @throws EE_Error
666
-     * @throws EE_Error
667
-     * @throws EE_Error
668
-     */
669
-    public function get_html($display_previously_submitted_data = true)
670
-    {
671
-        $this->ensure_construct_finalized_called();
672
-        if ($display_previously_submitted_data) {
673
-            $this->populate_from_session();
674
-        }
675
-        return $this->_form_html_filter
676
-            ? $this->_form_html_filter->filterHtml($this->_layout_strategy->layout_form(), $this)
677
-            : $this->_layout_strategy->layout_form();
678
-    }
679
-
680
-
681
-    /**
682
-     * enqueues JS and CSS for the form.
683
-     * It is preferred to call this before wp_enqueue_scripts so the
684
-     * scripts and styles can be put in the header, but if called later
685
-     * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
686
-     * only be in the header; but in HTML5 its ok in the body.
687
-     * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
688
-     * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
689
-     *
690
-     * @return void
691
-     * @throws EE_Error
692
-     */
693
-    public function enqueue_js()
694
-    {
695
-        $this->_enqueue_and_localize_form_js();
696
-        foreach ($this->subsections() as $subsection) {
697
-            $subsection->enqueue_js();
698
-        }
699
-    }
700
-
701
-
702
-    /**
703
-     * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
704
-     * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
705
-     * the wp_enqueue_scripts hook.
706
-     * However, registering the form js and localizing it can happen when we
707
-     * actually output the form (which is preferred, seeing how teh form's fields
708
-     * could change until it's actually outputted)
709
-     *
710
-     * @param boolean $init_form_validation_automatically whether or not we want the form validation
711
-     *                                                    to be triggered automatically or not
712
-     * @return void
713
-     */
714
-    public static function wp_enqueue_scripts($init_form_validation_automatically = true)
715
-    {
716
-        wp_register_script(
717
-            'ee_form_section_validation',
718
-            EE_GLOBAL_ASSETS_URL . 'scripts' . '/form_section_validation.js',
719
-            array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
720
-            EVENT_ESPRESSO_VERSION,
721
-            true
722
-        );
723
-        wp_localize_script(
724
-            'ee_form_section_validation',
725
-            'ee_form_section_validation_init',
726
-            array('init' => $init_form_validation_automatically ? '1' : '0')
727
-        );
728
-    }
729
-
730
-
731
-    /**
732
-     * gets the variables used by form_section_validation.js.
733
-     * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
734
-     * but before the wordpress hook wp_loaded
735
-     *
736
-     * @throws EE_Error
737
-     */
738
-    public function _enqueue_and_localize_form_js()
739
-    {
740
-        $this->ensure_construct_finalized_called();
741
-        // actually, we don't want to localize just yet. There may be other forms on the page.
742
-        // so we need to add our form section data to a static variable accessible by all form sections
743
-        // and localize it just before the footer
744
-        $this->localize_validation_rules();
745
-        add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
746
-        add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
747
-    }
748
-
749
-
750
-    /**
751
-     * add our form section data to a static variable accessible by all form sections
752
-     *
753
-     * @param bool $return_for_subsection
754
-     * @return void
755
-     * @throws EE_Error
756
-     */
757
-    public function localize_validation_rules($return_for_subsection = false)
758
-    {
759
-        // we only want to localize vars ONCE for the entire form,
760
-        // so if the form section doesn't have a parent, then it must be the top dog
761
-        if ($return_for_subsection || ! $this->parent_section()) {
762
-            EE_Form_Section_Proper::$_js_localization['form_data'][ $this->html_id() ] = array(
763
-                'form_section_id'  => $this->html_id(true),
764
-                'validation_rules' => $this->get_jquery_validation_rules(),
765
-                'other_data'       => $this->get_other_js_data(),
766
-                'errors'           => $this->subsection_validation_errors_by_html_name(),
767
-            );
768
-            EE_Form_Section_Proper::$_scripts_localized                                = true;
769
-        }
770
-    }
771
-
772
-
773
-    /**
774
-     * Gets an array of extra data that will be useful for client-side javascript.
775
-     * This is primarily data added by inputs and forms in addition to any
776
-     * scripts they might enqueue
777
-     *
778
-     * @param array $form_other_js_data
779
-     * @return array
780
-     * @throws EE_Error
781
-     */
782
-    public function get_other_js_data($form_other_js_data = array())
783
-    {
784
-        foreach ($this->subsections() as $subsection) {
785
-            $form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
786
-        }
787
-        return $form_other_js_data;
788
-    }
789
-
790
-
791
-    /**
792
-     * Gets a flat array of inputs for this form section and its subsections.
793
-     * Keys are their form names, and values are the inputs themselves
794
-     *
795
-     * @return EE_Form_Input_Base
796
-     * @throws EE_Error
797
-     */
798
-    public function inputs_in_subsections()
799
-    {
800
-        $inputs = array();
801
-        foreach ($this->subsections() as $subsection) {
802
-            if ($subsection instanceof EE_Form_Input_Base) {
803
-                $inputs[ $subsection->html_name() ] = $subsection;
804
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
805
-                $inputs += $subsection->inputs_in_subsections();
806
-            }
807
-        }
808
-        return $inputs;
809
-    }
810
-
811
-
812
-    /**
813
-     * Gets a flat array of all the validation errors.
814
-     * Keys are html names (because those should be unique)
815
-     * and values are a string of all their validation errors
816
-     *
817
-     * @return string[]
818
-     * @throws EE_Error
819
-     */
820
-    public function subsection_validation_errors_by_html_name()
821
-    {
822
-        $inputs = $this->inputs();
823
-        $errors = array();
824
-        foreach ($inputs as $form_input) {
825
-            if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
826
-                $errors[ $form_input->html_name() ] = $form_input->get_validation_error_string();
827
-            }
828
-        }
829
-        return $errors;
830
-    }
831
-
832
-
833
-    /**
834
-     * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
835
-     * Should be setup by each form during the _enqueues_and_localize_form_js
836
-     *
837
-     * @throws InvalidArgumentException
838
-     * @throws InvalidInterfaceException
839
-     * @throws InvalidDataTypeException
840
-     */
841
-    public static function localize_script_for_all_forms()
842
-    {
843
-        // allow inputs and stuff to hook in their JS and stuff here
844
-        do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
845
-        EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
846
-        $email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
847
-            ? EE_Registry::instance()->CFG->registration->email_validation_level
848
-            : 'wp_default';
849
-        EE_Form_Section_Proper::$_js_localization['email_validation_level']   = $email_validation_level;
850
-        wp_enqueue_script('ee_form_section_validation');
851
-        wp_localize_script(
852
-            'ee_form_section_validation',
853
-            'ee_form_section_vars',
854
-            EE_Form_Section_Proper::$_js_localization
855
-        );
856
-    }
857
-
858
-
859
-    /**
860
-     * ensure_scripts_localized
861
-     *
862
-     * @throws EE_Error
863
-     */
864
-    public function ensure_scripts_localized()
865
-    {
866
-        if (! EE_Form_Section_Proper::$_scripts_localized) {
867
-            $this->_enqueue_and_localize_form_js();
868
-        }
869
-    }
870
-
871
-
872
-    /**
873
-     * Gets the hard-coded validation error messages to be used in the JS. The convention
874
-     * is that the key here should be the same as the custom validation rule put in the JS file
875
-     *
876
-     * @return array keys are custom validation rules, and values are internationalized strings
877
-     */
878
-    private static function _get_localized_error_messages()
879
-    {
880
-        return array(
881
-            'validUrl' => wp_strip_all_tags(__('This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg', 'event_espresso')),
882
-            'regex'    => wp_strip_all_tags(__('Please check your input', 'event_espresso'))
883
-        );
884
-    }
885
-
886
-
887
-    /**
888
-     * @return array
889
-     */
890
-    public static function js_localization()
891
-    {
892
-        return self::$_js_localization;
893
-    }
894
-
895
-
896
-    /**
897
-     * @return void
898
-     */
899
-    public static function reset_js_localization()
900
-    {
901
-        self::$_js_localization = array();
902
-    }
903
-
904
-
905
-    /**
906
-     * Gets the JS to put inside the jquery validation rules for subsection of this form section.
907
-     * See parent function for more...
908
-     *
909
-     * @return array
910
-     * @throws EE_Error
911
-     */
912
-    public function get_jquery_validation_rules()
913
-    {
914
-        $jquery_validation_rules = array();
915
-        foreach ($this->get_validatable_subsections() as $subsection) {
916
-            $jquery_validation_rules = array_merge(
917
-                $jquery_validation_rules,
918
-                $subsection->get_jquery_validation_rules()
919
-            );
920
-        }
921
-        return $jquery_validation_rules;
922
-    }
923
-
924
-
925
-    /**
926
-     * Sanitizes all the data and sets the sanitized value of each field
927
-     *
928
-     * @param array $req_data
929
-     * @return void
930
-     * @throws EE_Error
931
-     */
932
-    protected function _normalize($req_data)
933
-    {
934
-        $this->_received_submission = true;
935
-        $this->_validation_errors   = array();
936
-        foreach ($this->get_validatable_subsections() as $subsection) {
937
-            try {
938
-                $subsection->_normalize($req_data);
939
-            } catch (EE_Validation_Error $e) {
940
-                $subsection->add_validation_error($e);
941
-            }
942
-        }
943
-    }
944
-
945
-
946
-    /**
947
-     * Performs validation on this form section and its subsections.
948
-     * For each subsection,
949
-     * calls _validate_{subsection_name} on THIS form (if the function exists)
950
-     * and passes it the subsection, then calls _validate on that subsection.
951
-     * If you need to perform validation on the form as a whole (considering multiple)
952
-     * you would be best to override this _validate method,
953
-     * calling parent::_validate() first.
954
-     *
955
-     * @throws EE_Error
956
-     */
957
-    protected function _validate()
958
-    {
959
-        // reset the cache of whether this form is valid or not- we're re-validating it now
960
-        $this->is_valid = null;
961
-        foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
962
-            if (method_exists($this, '_validate_' . $subsection_name)) {
963
-                call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
964
-            }
965
-            $subsection->_validate();
966
-        }
967
-    }
968
-
969
-
970
-    /**
971
-     * Gets all the validated inputs for the form section
972
-     *
973
-     * @return array
974
-     * @throws EE_Error
975
-     */
976
-    public function valid_data()
977
-    {
978
-        $inputs = array();
979
-        foreach ($this->subsections() as $subsection_name => $subsection) {
980
-            if ($subsection instanceof EE_Form_Section_Proper) {
981
-                $inputs[ $subsection_name ] = $subsection->valid_data();
982
-            } elseif ($subsection instanceof EE_Form_Input_Base) {
983
-                $inputs[ $subsection_name ] = $subsection->normalized_value();
984
-            }
985
-        }
986
-        return $inputs;
987
-    }
988
-
989
-
990
-    /**
991
-     * Gets all the inputs on this form section
992
-     *
993
-     * @return EE_Form_Input_Base[]
994
-     * @throws EE_Error
995
-     */
996
-    public function inputs()
997
-    {
998
-        $inputs = array();
999
-        foreach ($this->subsections() as $subsection_name => $subsection) {
1000
-            if ($subsection instanceof EE_Form_Input_Base) {
1001
-                $inputs[ $subsection_name ] = $subsection;
1002
-            }
1003
-        }
1004
-        return $inputs;
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Gets all the subsections which are a proper form
1010
-     *
1011
-     * @return EE_Form_Section_Proper[]
1012
-     * @throws EE_Error
1013
-     */
1014
-    public function subforms()
1015
-    {
1016
-        $form_sections = array();
1017
-        foreach ($this->subsections() as $name => $obj) {
1018
-            if ($obj instanceof EE_Form_Section_Proper) {
1019
-                $form_sections[ $name ] = $obj;
1020
-            }
1021
-        }
1022
-        return $form_sections;
1023
-    }
1024
-
1025
-
1026
-    /**
1027
-     * Gets all the subsections (inputs, proper subsections, or html-only sections).
1028
-     * Consider using inputs() or subforms()
1029
-     * if you only want form inputs or proper form sections.
1030
-     *
1031
-     * @param boolean $require_construction_to_be_finalized most client code should
1032
-     *                                                      leave this as TRUE so that the inputs will be properly
1033
-     *                                                      configured. However, some client code may be ok with
1034
-     *                                                      construction finalize being called later
1035
-     *                                                      (realizing that the subsections' html names might not be
1036
-     *                                                      set yet, etc.)
1037
-     * @return EE_Form_Section_Proper[]
1038
-     * @throws EE_Error
1039
-     */
1040
-    public function subsections($require_construction_to_be_finalized = true)
1041
-    {
1042
-        if ($require_construction_to_be_finalized) {
1043
-            $this->ensure_construct_finalized_called();
1044
-        }
1045
-        return $this->_subsections;
1046
-    }
1047
-
1048
-
1049
-    /**
1050
-     * Returns whether this form has any subforms or inputs
1051
-     * @return bool
1052
-     */
1053
-    public function hasSubsections()
1054
-    {
1055
-        return ! empty($this->_subsections);
1056
-    }
1057
-
1058
-
1059
-    /**
1060
-     * Returns a simple array where keys are input names, and values are their normalized
1061
-     * values. (Similar to calling get_input_value on inputs)
1062
-     *
1063
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1064
-     *                                        or just this forms' direct children inputs
1065
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1066
-     *                                        or allow multidimensional array
1067
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
1068
-     *                                        with array keys being input names
1069
-     *                                        (regardless of whether they are from a subsection or not),
1070
-     *                                        and if $flatten is FALSE it can be a multidimensional array
1071
-     *                                        where keys are always subsection names and values are either
1072
-     *                                        the input's normalized value, or an array like the top-level array
1073
-     * @throws EE_Error
1074
-     */
1075
-    public function input_values($include_subform_inputs = false, $flatten = false)
1076
-    {
1077
-        return $this->_input_values(false, $include_subform_inputs, $flatten);
1078
-    }
1079
-
1080
-
1081
-    /**
1082
-     * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
1083
-     * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
1084
-     * is not necessarily the value we want to display to users. This creates an array
1085
-     * where keys are the input names, and values are their display values
1086
-     *
1087
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1088
-     *                                        or just this forms' direct children inputs
1089
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1090
-     *                                        or allow multidimensional array
1091
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
1092
-     *                                        with array keys being input names
1093
-     *                                        (regardless of whether they are from a subsection or not),
1094
-     *                                        and if $flatten is FALSE it can be a multidimensional array
1095
-     *                                        where keys are always subsection names and values are either
1096
-     *                                        the input's normalized value, or an array like the top-level array
1097
-     * @throws EE_Error
1098
-     */
1099
-    public function input_pretty_values($include_subform_inputs = false, $flatten = false)
1100
-    {
1101
-        return $this->_input_values(true, $include_subform_inputs, $flatten);
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     * Gets the input values from the form
1107
-     *
1108
-     * @param boolean $pretty                 Whether to retrieve the pretty value,
1109
-     *                                        or just the normalized value
1110
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1111
-     *                                        or just this forms' direct children inputs
1112
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1113
-     *                                        or allow multidimensional array
1114
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
1115
-     *                                        input names (regardless of whether they are from a subsection or not),
1116
-     *                                        and if $flatten is FALSE it can be a multidimensional array
1117
-     *                                        where keys are always subsection names and values are either
1118
-     *                                        the input's normalized value, or an array like the top-level array
1119
-     * @throws EE_Error
1120
-     */
1121
-    public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
1122
-    {
1123
-        $input_values = array();
1124
-        foreach ($this->subsections() as $subsection_name => $subsection) {
1125
-            if ($subsection instanceof EE_Form_Input_Base) {
1126
-                $input_values[ $subsection_name ] = $pretty
1127
-                    ? $subsection->pretty_value()
1128
-                    : $subsection->normalized_value();
1129
-            } elseif ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1130
-                $subform_input_values = $subsection->_input_values(
1131
-                    $pretty,
1132
-                    $include_subform_inputs,
1133
-                    $flatten
1134
-                );
1135
-                if ($flatten) {
1136
-                    $input_values = array_merge($input_values, $subform_input_values);
1137
-                } else {
1138
-                    $input_values[ $subsection_name ] = $subform_input_values;
1139
-                }
1140
-            }
1141
-        }
1142
-        return $input_values;
1143
-    }
1144
-
1145
-
1146
-    /**
1147
-     * Gets the originally submitted input values from the form
1148
-     *
1149
-     * @param boolean $include_subforms  Whether to include inputs from subforms,
1150
-     *                                   or just this forms' direct children inputs
1151
-     * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1152
-     *                                   with array keys being input names
1153
-     *                                   (regardless of whether they are from a subsection or not),
1154
-     *                                   and if $flatten is FALSE it can be a multidimensional array
1155
-     *                                   where keys are always subsection names and values are either
1156
-     *                                   the input's normalized value, or an array like the top-level array
1157
-     * @throws EE_Error
1158
-     */
1159
-    public function submitted_values($include_subforms = false)
1160
-    {
1161
-        $submitted_values = array();
1162
-        foreach ($this->subsections() as $subsection) {
1163
-            if ($subsection instanceof EE_Form_Input_Base) {
1164
-                // is this input part of an array of inputs?
1165
-                if (strpos($subsection->html_name(), '[') !== false) {
1166
-                    $full_input_name  = EEH_Array::convert_array_values_to_keys(
1167
-                        explode(
1168
-                            '[',
1169
-                            str_replace(']', '', $subsection->html_name())
1170
-                        ),
1171
-                        $subsection->raw_value()
1172
-                    );
1173
-                    $submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1174
-                } else {
1175
-                    $submitted_values[ $subsection->html_name() ] = $subsection->raw_value();
1176
-                }
1177
-            } elseif ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1178
-                $subform_input_values = $subsection->submitted_values($include_subforms);
1179
-                $submitted_values     = array_replace_recursive($submitted_values, $subform_input_values);
1180
-            }
1181
-        }
1182
-        return $submitted_values;
1183
-    }
1184
-
1185
-
1186
-    /**
1187
-     * Indicates whether or not this form has received a submission yet
1188
-     * (ie, had receive_form_submission called on it yet)
1189
-     *
1190
-     * @return boolean
1191
-     * @throws EE_Error
1192
-     */
1193
-    public function has_received_submission()
1194
-    {
1195
-        $this->ensure_construct_finalized_called();
1196
-        return $this->_received_submission;
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * Equivalent to passing 'exclude' in the constructor's options array.
1202
-     * Removes the listed inputs from the form
1203
-     *
1204
-     * @param array $inputs_to_exclude values are the input names
1205
-     * @return void
1206
-     */
1207
-    public function exclude(array $inputs_to_exclude = array())
1208
-    {
1209
-        foreach ($inputs_to_exclude as $input_to_exclude_name) {
1210
-            unset($this->_subsections[ $input_to_exclude_name ]);
1211
-        }
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * Changes these inputs' display strategy to be EE_Hidden_Display_Strategy.
1217
-     * @param array $inputs_to_hide
1218
-     * @throws EE_Error
1219
-     */
1220
-    public function hide(array $inputs_to_hide = array())
1221
-    {
1222
-        foreach ($inputs_to_hide as $input_to_hide) {
1223
-            $input = $this->get_input($input_to_hide);
1224
-            $input->set_display_strategy(new EE_Hidden_Display_Strategy());
1225
-        }
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * add_subsections
1231
-     * Adds the listed subsections to the form section.
1232
-     * If $subsection_name_to_target is provided,
1233
-     * then new subsections are added before or after that subsection,
1234
-     * otherwise to the start or end of the entire subsections array.
1235
-     *
1236
-     * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1237
-     *                                                          where keys are their names
1238
-     * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1239
-     *                                                          should be added before or after
1240
-     *                                                          IF $subsection_name_to_target is null,
1241
-     *                                                          then $new_subsections will be added to
1242
-     *                                                          the beginning or end of the entire subsections array
1243
-     * @param boolean                $add_before                whether to add $new_subsections, before or after
1244
-     *                                                          $subsection_name_to_target,
1245
-     *                                                          or if $subsection_name_to_target is null,
1246
-     *                                                          before or after entire subsections array
1247
-     * @return void
1248
-     * @throws EE_Error
1249
-     */
1250
-    public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1251
-    {
1252
-        foreach ($new_subsections as $subsection_name => $subsection) {
1253
-            if (! $subsection instanceof EE_Form_Section_Base) {
1254
-                EE_Error::add_error(
1255
-                    sprintf(
1256
-                        esc_html__(
1257
-                            "Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1258
-                            'event_espresso'
1259
-                        ),
1260
-                        get_class($subsection),
1261
-                        $subsection_name,
1262
-                        $this->name()
1263
-                    )
1264
-                );
1265
-                unset($new_subsections[ $subsection_name ]);
1266
-            }
1267
-        }
1268
-        $this->_subsections = EEH_Array::insert_into_array(
1269
-            $this->_subsections,
1270
-            $new_subsections,
1271
-            $subsection_name_to_target,
1272
-            $add_before
1273
-        );
1274
-        if ($this->_construction_finalized) {
1275
-            foreach ($this->_subsections as $name => $subsection) {
1276
-                $subsection->_construct_finalize($this, $name);
1277
-            }
1278
-        }
1279
-    }
1280
-
1281
-
1282
-    /**
1283
-     * @param string $subsection_name
1284
-     * @param bool   $recursive
1285
-     * @return bool
1286
-     */
1287
-    public function has_subsection($subsection_name, $recursive = false)
1288
-    {
1289
-        foreach ($this->_subsections as $name => $subsection) {
1290
-            if (
1291
-                $name === $subsection_name
1292
-                || (
1293
-                    $recursive
1294
-                    && $subsection instanceof EE_Form_Section_Proper
1295
-                    && $subsection->has_subsection($subsection_name, $recursive)
1296
-                )
1297
-            ) {
1298
-                return true;
1299
-            }
1300
-        }
1301
-        return false;
1302
-    }
1303
-
1304
-
1305
-
1306
-    /**
1307
-     * Just gets all validatable subsections to clean their sensitive data
1308
-     *
1309
-     * @throws EE_Error
1310
-     */
1311
-    public function clean_sensitive_data()
1312
-    {
1313
-        foreach ($this->get_validatable_subsections() as $subsection) {
1314
-            $subsection->clean_sensitive_data();
1315
-        }
1316
-    }
1317
-
1318
-
1319
-    /**
1320
-     * Sets the submission error message (aka validation error message for this form section and all sub-sections)
1321
-     * @param string                           $form_submission_error_message
1322
-     * @param EE_Form_Section_Validatable $form_section unused
1323
-     * @throws EE_Error
1324
-     */
1325
-    public function set_submission_error_message(
1326
-        $form_submission_error_message = ''
1327
-    ) {
1328
-        $this->_form_submission_error_message = ! empty($form_submission_error_message)
1329
-            ? $form_submission_error_message
1330
-            : $this->getAllValidationErrorsString();
1331
-    }
1332
-
1333
-
1334
-    /**
1335
-     * Returns the cached error message. A default value is set for this during _validate(),
1336
-     * (called during receive_form_submission) but it can be explicitly set using
1337
-     * set_submission_error_message
1338
-     *
1339
-     * @return string
1340
-     */
1341
-    public function submission_error_message()
1342
-    {
1343
-        return $this->_form_submission_error_message;
1344
-    }
1345
-
1346
-
1347
-    /**
1348
-     * Sets a message to display if the data submitted to the form was valid.
1349
-     * @param string $form_submission_success_message
1350
-     */
1351
-    public function set_submission_success_message($form_submission_success_message = '')
1352
-    {
1353
-        $this->_form_submission_success_message = ! empty($form_submission_success_message)
1354
-            ? $form_submission_success_message
1355
-            : esc_html__('Form submitted successfully', 'event_espresso');
1356
-    }
1357
-
1358
-
1359
-    /**
1360
-     * Gets a message appropriate for display when the form is correctly submitted
1361
-     * @return string
1362
-     */
1363
-    public function submission_success_message()
1364
-    {
1365
-        return $this->_form_submission_success_message;
1366
-    }
1367
-
1368
-
1369
-    /**
1370
-     * Returns the prefix that should be used on child of this form section for
1371
-     * their html names. If this form section itself has a parent, prepends ITS
1372
-     * prefix onto this form section's prefix. Used primarily by
1373
-     * EE_Form_Input_Base::_set_default_html_name_if_empty
1374
-     *
1375
-     * @return string
1376
-     * @throws EE_Error
1377
-     */
1378
-    public function html_name_prefix()
1379
-    {
1380
-        if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1381
-            return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1382
-        }
1383
-        return $this->name();
1384
-    }
1385
-
1386
-
1387
-    /**
1388
-     * Gets the name, but first checks _construct_finalize has been called. If not,
1389
-     * calls it (assumes there is no parent and that we want the name to be whatever
1390
-     * was set, which is probably nothing, or the classname)
1391
-     *
1392
-     * @return string
1393
-     * @throws EE_Error
1394
-     */
1395
-    public function name()
1396
-    {
1397
-        $this->ensure_construct_finalized_called();
1398
-        return parent::name();
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * @return EE_Form_Section_Proper
1404
-     * @throws EE_Error
1405
-     */
1406
-    public function parent_section()
1407
-    {
1408
-        $this->ensure_construct_finalized_called();
1409
-        return parent::parent_section();
1410
-    }
1411
-
1412
-
1413
-    /**
1414
-     * make sure construction finalized was called, otherwise children might not be ready
1415
-     *
1416
-     * @return void
1417
-     * @throws EE_Error
1418
-     */
1419
-    public function ensure_construct_finalized_called()
1420
-    {
1421
-        if (! $this->_construction_finalized) {
1422
-            $this->_construct_finalize($this->_parent_section, $this->_name);
1423
-        }
1424
-    }
1425
-
1426
-
1427
-    /**
1428
-     * Checks if any of this form section's inputs, or any of its children's inputs,
1429
-     * are in teh form data. If any are found, returns true. Else false
1430
-     *
1431
-     * @param array $req_data
1432
-     * @return boolean
1433
-     * @throws EE_Error
1434
-     */
1435
-    public function form_data_present_in($req_data = null)
1436
-    {
1437
-        $req_data = $this->getCachedRequest($req_data);
1438
-        foreach ($this->subsections() as $subsection) {
1439
-            if ($subsection instanceof EE_Form_Input_Base) {
1440
-                if ($subsection->form_data_present_in($req_data)) {
1441
-                    return true;
1442
-                }
1443
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
1444
-                if ($subsection->form_data_present_in($req_data)) {
1445
-                    return true;
1446
-                }
1447
-            }
1448
-        }
1449
-        return false;
1450
-    }
1451
-
1452
-
1453
-    /**
1454
-     * Gets validation errors for this form section and subsections
1455
-     * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1456
-     * gets the validation errors for ALL subsection
1457
-     *
1458
-     * @return EE_Validation_Error[]
1459
-     * @throws EE_Error
1460
-     */
1461
-    public function get_validation_errors_accumulated()
1462
-    {
1463
-        $validation_errors = $this->get_validation_errors();
1464
-        foreach ($this->get_validatable_subsections() as $subsection) {
1465
-            if ($subsection instanceof EE_Form_Section_Proper) {
1466
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1467
-            } else {
1468
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors();
1469
-            }
1470
-            if ($validation_errors_on_this_subsection) {
1471
-                $validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1472
-            }
1473
-        }
1474
-        return $validation_errors;
1475
-    }
1476
-
1477
-    /**
1478
-     * Fetch validation errors from children and grandchildren and puts them in a single string.
1479
-     * This traverses the form section tree to generate this, but you probably want to instead use
1480
-     * get_form_submission_error_message() which is usually this message cached (or a custom validation error message)
1481
-     *
1482
-     * @return string
1483
-     * @since 4.9.59.p
1484
-     */
1485
-    protected function getAllValidationErrorsString()
1486
-    {
1487
-        $submission_error_messages = array();
1488
-        // bad, bad, bad registrant
1489
-        foreach ($this->get_validation_errors_accumulated() as $validation_error) {
1490
-            if ($validation_error instanceof EE_Validation_Error) {
1491
-                $form_section = $validation_error->get_form_section();
1492
-                if ($form_section instanceof EE_Form_Input_Base) {
1493
-                    $label = $validation_error->get_form_section()->html_label_text();
1494
-                } elseif ($form_section instanceof EE_Form_Section_Validatable) {
1495
-                    $label = $validation_error->get_form_section()->name();
1496
-                } else {
1497
-                    $label = esc_html__('Unknown', 'event_espresso');
1498
-                }
1499
-                $submission_error_messages[] = sprintf(
1500
-                    esc_html__('%s : %s', 'event_espresso'),
1501
-                    $label,
1502
-                    $validation_error->getMessage()
1503
-                );
1504
-            }
1505
-        }
1506
-        return implode('<br>', $submission_error_messages);
1507
-    }
1508
-
1509
-
1510
-    /**
1511
-     * This isn't just the name of an input, it's a path pointing to an input. The
1512
-     * path is similar to a folder path: slash (/) means to descend into a subsection,
1513
-     * dot-dot-slash (../) means to ascend into the parent section.
1514
-     * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1515
-     * which will be returned.
1516
-     * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1517
-     * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1518
-     * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1519
-     * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1520
-     * Etc
1521
-     *
1522
-     * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1523
-     * @return EE_Form_Section_Base
1524
-     * @throws EE_Error
1525
-     */
1526
-    public function find_section_from_path($form_section_path)
1527
-    {
1528
-        // check if we can find the input from purely going straight up the tree
1529
-        $input = parent::find_section_from_path($form_section_path);
1530
-        if ($input instanceof EE_Form_Section_Base) {
1531
-            return $input;
1532
-        }
1533
-        $next_slash_pos = strpos($form_section_path, '/');
1534
-        if ($next_slash_pos !== false) {
1535
-            $child_section_name = substr($form_section_path, 0, $next_slash_pos);
1536
-            $subpath            = substr($form_section_path, $next_slash_pos + 1);
1537
-        } else {
1538
-            $child_section_name = $form_section_path;
1539
-            $subpath            = '';
1540
-        }
1541
-        $child_section = $this->get_subsection($child_section_name);
1542
-        if ($child_section instanceof EE_Form_Section_Base) {
1543
-            return $child_section->find_section_from_path($subpath);
1544
-        }
1545
-        return null;
1546
-    }
19
+	const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
20
+
21
+	/**
22
+	 * Subsections
23
+	 *
24
+	 * @var EE_Form_Section_Validatable[]
25
+	 */
26
+	protected $_subsections = array();
27
+
28
+	/**
29
+	 * Strategy for laying out the form
30
+	 *
31
+	 * @var EE_Form_Section_Layout_Base
32
+	 */
33
+	protected $_layout_strategy;
34
+
35
+	/**
36
+	 * Whether or not this form has received and validated a form submission yet
37
+	 *
38
+	 * @var boolean
39
+	 */
40
+	protected $_received_submission = false;
41
+
42
+	/**
43
+	 * message displayed to users upon successful form submission
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_form_submission_success_message = '';
48
+
49
+	/**
50
+	 * message displayed to users upon unsuccessful form submission
51
+	 *
52
+	 * @var string
53
+	 */
54
+	protected $_form_submission_error_message = '';
55
+
56
+	/**
57
+	 * @var array like post / request
58
+	 */
59
+	protected $cached_request_data;
60
+
61
+	/**
62
+	 * Stores whether this form (and its sub-sections) were found to be valid or not.
63
+	 * Starts off as null, but once the form is validated, it set to either true or false
64
+	 * @var boolean|null
65
+	 */
66
+	protected $is_valid;
67
+
68
+	/**
69
+	 * Stores all the data that will localized for form validation
70
+	 *
71
+	 * @var array
72
+	 */
73
+	protected static $_js_localization = array();
74
+
75
+	/**
76
+	 * whether or not the form's localized validation JS vars have been set
77
+	 *
78
+	 * @type boolean
79
+	 */
80
+	protected static $_scripts_localized = false;
81
+
82
+
83
+	/**
84
+	 * when constructing a proper form section, calls _construct_finalize on children
85
+	 * so that they know who their parent is, and what name they've been given.
86
+	 *
87
+	 * @param array[] $options_array   {
88
+	 * @type          $subsections     EE_Form_Section_Validatable[] where keys are the section's name
89
+	 * @type          $include         string[] numerically-indexed where values are section names to be included,
90
+	 *                                 and in that order. This is handy if you want
91
+	 *                                 the subsections to be ordered differently than the default, and if you override
92
+	 *                                 which fields are shown
93
+	 * @type          $exclude         string[] values are subsections to be excluded. This is handy if you want
94
+	 *                                 to remove certain default subsections (note: if you specify BOTH 'include' AND
95
+	 *                                 'exclude', the inclusions will be applied first, and the exclusions will exclude
96
+	 *                                 items from that list of inclusions)
97
+	 * @type          $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
98
+	 *                                 } @see EE_Form_Section_Validatable::__construct()
99
+	 * @throws EE_Error
100
+	 */
101
+	public function __construct($options_array = array())
102
+	{
103
+		$options_array = (array) apply_filters(
104
+			'FHEE__EE_Form_Section_Proper___construct__options_array',
105
+			$options_array,
106
+			$this
107
+		);
108
+		// call parent first, as it may be setting the name
109
+		parent::__construct($options_array);
110
+		// if they've included subsections in the constructor, add them now
111
+		if (isset($options_array['include'])) {
112
+			// we are going to make sure we ONLY have those subsections to include
113
+			// AND we are going to make sure they're in that specified order
114
+			$reordered_subsections = array();
115
+			foreach ($options_array['include'] as $input_name) {
116
+				if (isset($this->_subsections[ $input_name ])) {
117
+					$reordered_subsections[ $input_name ] = $this->_subsections[ $input_name ];
118
+				}
119
+			}
120
+			$this->_subsections = $reordered_subsections;
121
+		}
122
+		if (isset($options_array['exclude'])) {
123
+			$exclude            = $options_array['exclude'];
124
+			$this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
125
+		}
126
+		if (isset($options_array['layout_strategy'])) {
127
+			$this->_layout_strategy = $options_array['layout_strategy'];
128
+		}
129
+		if (! $this->_layout_strategy) {
130
+			$this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
131
+		}
132
+		$this->_layout_strategy->_construct_finalize($this);
133
+		// ok so we are definitely going to want the forms JS,
134
+		// so enqueue it or remember to enqueue it during wp_enqueue_scripts
135
+		if (did_action('wp_enqueue_scripts') || did_action('admin_enqueue_scripts')) {
136
+			// ok so they've constructed this object after when they should have.
137
+			// just enqueue the generic form scripts and initialize the form immediately in the JS
138
+			EE_Form_Section_Proper::wp_enqueue_scripts(true);
139
+		} else {
140
+			add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
141
+			add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
142
+		}
143
+		add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
144
+		/**
145
+		 * Gives other plugins a chance to hook in before construct finalize is called.
146
+		 * The form probably doesn't yet have a parent form section.
147
+		 * Since 4.9.32, when this action was introduced, this is the best place to add a subsection onto a form,
148
+		 * assuming you don't care what the form section's name, HTML ID, or HTML name etc are.
149
+		 * Also see AHEE__EE_Form_Section_Proper___construct_finalize__end
150
+		 *
151
+		 * @since 4.9.32
152
+		 * @param EE_Form_Section_Proper $this          before __construct is done, but all of its logic,
153
+		 *                                              except maybe calling _construct_finalize has been done
154
+		 * @param array                  $options_array options passed into the constructor
155
+		 */
156
+		do_action(
157
+			'AHEE__EE_Form_Input_Base___construct__before_construct_finalize_called',
158
+			$this,
159
+			$options_array
160
+		);
161
+		if (isset($options_array['name'])) {
162
+			$this->_construct_finalize(null, $options_array['name']);
163
+		}
164
+	}
165
+
166
+
167
+	/**
168
+	 * Finishes construction given the parent form section and this form section's name
169
+	 *
170
+	 * @param EE_Form_Section_Proper $parent_form_section
171
+	 * @param string                 $name
172
+	 * @throws EE_Error
173
+	 */
174
+	public function _construct_finalize($parent_form_section, $name)
175
+	{
176
+		parent::_construct_finalize($parent_form_section, $name);
177
+		$this->_set_default_name_if_empty();
178
+		$this->_set_default_html_id_if_empty();
179
+		foreach ($this->_subsections as $subsection_name => $subsection) {
180
+			if ($subsection instanceof EE_Form_Section_Base) {
181
+				$subsection->_construct_finalize($this, $subsection_name);
182
+			} else {
183
+				throw new EE_Error(
184
+					sprintf(
185
+						esc_html__(
186
+							'Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
187
+							'event_espresso'
188
+						),
189
+						$subsection_name,
190
+						get_class($this),
191
+						$subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
192
+					)
193
+				);
194
+			}
195
+		}
196
+		/**
197
+		 * Action performed just after form has been given a name (and HTML ID etc) and is fully constructed.
198
+		 * If you have code that should modify the form and needs it and its subsections to have a name, HTML ID
199
+		 * (or other attributes derived from the name like the HTML label id, etc), this is where it should be done.
200
+		 * This might only happen just before displaying the form, or just before it receives form submission data.
201
+		 * If you need to modify the form or its subsections before _construct_finalize is called on it (and we've
202
+		 * ensured it has a name, HTML IDs, etc
203
+		 *
204
+		 * @param EE_Form_Section_Proper      $this
205
+		 * @param EE_Form_Section_Proper|null $parent_form_section
206
+		 * @param string                      $name
207
+		 */
208
+		do_action(
209
+			'AHEE__EE_Form_Section_Proper___construct_finalize__end',
210
+			$this,
211
+			$parent_form_section,
212
+			$name
213
+		);
214
+	}
215
+
216
+
217
+	/**
218
+	 * Gets the layout strategy for this form section
219
+	 *
220
+	 * @return EE_Form_Section_Layout_Base
221
+	 */
222
+	public function get_layout_strategy()
223
+	{
224
+		return $this->_layout_strategy;
225
+	}
226
+
227
+
228
+	/**
229
+	 * Gets the HTML for a single input for this form section according
230
+	 * to the layout strategy
231
+	 *
232
+	 * @param EE_Form_Input_Base $input
233
+	 * @return string
234
+	 */
235
+	public function get_html_for_input($input)
236
+	{
237
+		return $this->_layout_strategy->layout_input($input);
238
+	}
239
+
240
+
241
+	/**
242
+	 * was_submitted - checks if form inputs are present in request data
243
+	 * Basically an alias for form_data_present_in() (which is used by both
244
+	 * proper form sections and form inputs)
245
+	 *
246
+	 * @param null $form_data
247
+	 * @return boolean
248
+	 * @throws EE_Error
249
+	 */
250
+	public function was_submitted($form_data = null)
251
+	{
252
+		return $this->form_data_present_in($form_data);
253
+	}
254
+
255
+	/**
256
+	 * Gets the cached request data; but if there is none, or $req_data was set with
257
+	 * something different, refresh the cache, and then return it
258
+	 * @param null $req_data
259
+	 * @return array
260
+	 */
261
+	protected function getCachedRequest($req_data = null)
262
+	{
263
+		if (
264
+			$this->cached_request_data === null
265
+			|| (
266
+				$req_data !== null
267
+				&& $req_data !== $this->cached_request_data
268
+			)
269
+		) {
270
+			$req_data = apply_filters(
271
+				'FHEE__EE_Form_Section_Proper__receive_form_submission__req_data',
272
+				$req_data,
273
+				$this
274
+			);
275
+			if ($req_data === null) {
276
+				/** @var RequestInterface $request */
277
+				$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
278
+				$req_data = $request->requestParams();
279
+			}
280
+			$req_data = apply_filters(
281
+				'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
282
+				$req_data,
283
+				$this
284
+			);
285
+			$this->cached_request_data = (array) $req_data;
286
+		}
287
+		return $this->cached_request_data;
288
+	}
289
+
290
+
291
+	/**
292
+	 * After the form section is initially created, call this to sanitize the data in the submission
293
+	 * which relates to this form section, validate it, and set it as properties on the form.
294
+	 *
295
+	 * @param array|null $req_data should usually be post data (the default).
296
+	 *                             However, you CAN supply a different array.
297
+	 *                             Consider using set_defaults() instead however.
298
+	 *                             (If you rendered the form in the page using $form_x->get_html()
299
+	 *                             the inputs will have the correct name in the request data for this function
300
+	 *                             to find them and populate the form with them.
301
+	 *                             If you have a flat form (with only input subsections),
302
+	 *                             you can supply a flat array where keys
303
+	 *                             are the form input names and values are their values)
304
+	 * @param boolean    $validate whether or not to perform validation on this data. Default is,
305
+	 *                             of course, to validate that data, and set errors on the invalid values.
306
+	 *                             But if the data has already been validated
307
+	 *                             (eg you validated the data then stored it in the DB)
308
+	 *                             you may want to skip this step.
309
+	 * @throws InvalidArgumentException
310
+	 * @throws InvalidInterfaceException
311
+	 * @throws InvalidDataTypeException
312
+	 * @throws EE_Error
313
+	 */
314
+	public function receive_form_submission($req_data = null, $validate = true)
315
+	{
316
+		$req_data = $this->getCachedRequest($req_data);
317
+		$this->_normalize($req_data);
318
+		if ($validate) {
319
+			$this->_validate();
320
+			// if it's invalid, we're going to want to re-display so remember what they submitted
321
+			if (! $this->is_valid()) {
322
+				$this->store_submitted_form_data_in_session();
323
+			}
324
+		}
325
+		if ($this->submission_error_message() === '' && ! $this->is_valid()) {
326
+			$this->set_submission_error_message();
327
+		}
328
+		do_action(
329
+			'AHEE__EE_Form_Section_Proper__receive_form_submission__end',
330
+			$req_data,
331
+			$this,
332
+			$validate
333
+		);
334
+	}
335
+
336
+
337
+	/**
338
+	 * caches the originally submitted input values in the session
339
+	 * so that they can be used to repopulate the form if it failed validation
340
+	 *
341
+	 * @return boolean whether or not the data was successfully stored in the session
342
+	 * @throws InvalidArgumentException
343
+	 * @throws InvalidInterfaceException
344
+	 * @throws InvalidDataTypeException
345
+	 * @throws EE_Error
346
+	 */
347
+	protected function store_submitted_form_data_in_session()
348
+	{
349
+		return EE_Registry::instance()->SSN->set_session_data(
350
+			array(
351
+				EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
352
+			)
353
+		);
354
+	}
355
+
356
+
357
+	/**
358
+	 * retrieves the originally submitted input values in the session
359
+	 * so that they can be used to repopulate the form if it failed validation
360
+	 *
361
+	 * @return array
362
+	 * @throws InvalidArgumentException
363
+	 * @throws InvalidInterfaceException
364
+	 * @throws InvalidDataTypeException
365
+	 */
366
+	protected function get_submitted_form_data_from_session()
367
+	{
368
+		$session = EE_Registry::instance()->SSN;
369
+		if ($session instanceof EE_Session) {
370
+			return $session->get_session_data(
371
+				EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
372
+			);
373
+		}
374
+		return array();
375
+	}
376
+
377
+
378
+	/**
379
+	 * flushed the originally submitted input values from the session
380
+	 *
381
+	 * @return boolean whether or not the data was successfully removed from the session
382
+	 * @throws InvalidArgumentException
383
+	 * @throws InvalidInterfaceException
384
+	 * @throws InvalidDataTypeException
385
+	 */
386
+	public static function flush_submitted_form_data_from_session()
387
+	{
388
+		return EE_Registry::instance()->SSN->reset_data(
389
+			array(EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
390
+		);
391
+	}
392
+
393
+
394
+	/**
395
+	 * Populates this form and its subsections with data from the session.
396
+	 * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
397
+	 * validation errors when displaying too)
398
+	 * Returns true if the form was populated from the session, false otherwise
399
+	 *
400
+	 * @return boolean
401
+	 * @throws InvalidArgumentException
402
+	 * @throws InvalidInterfaceException
403
+	 * @throws InvalidDataTypeException
404
+	 * @throws EE_Error
405
+	 */
406
+	public function populate_from_session()
407
+	{
408
+		$form_data_in_session = $this->get_submitted_form_data_from_session();
409
+		if (empty($form_data_in_session)) {
410
+			return false;
411
+		}
412
+		$this->receive_form_submission($form_data_in_session);
413
+		add_action('shutdown', array('EE_Form_Section_Proper', 'flush_submitted_form_data_from_session'));
414
+		if ($this->form_data_present_in($form_data_in_session)) {
415
+			return true;
416
+		}
417
+		return false;
418
+	}
419
+
420
+
421
+	/**
422
+	 * Populates the default data for the form, given an array where keys are
423
+	 * the input names, and values are their values (preferably normalized to be their
424
+	 * proper PHP types, not all strings... although that should be ok too).
425
+	 * Proper subsections are sub-arrays, the key being the subsection's name, and
426
+	 * the value being an array formatted in teh same way
427
+	 *
428
+	 * @param array $default_data
429
+	 * @throws EE_Error
430
+	 */
431
+	public function populate_defaults($default_data)
432
+	{
433
+		foreach ($this->subsections(false) as $subsection_name => $subsection) {
434
+			if (isset($default_data[ $subsection_name ])) {
435
+				if ($subsection instanceof EE_Form_Input_Base) {
436
+					$subsection->set_default($default_data[ $subsection_name ]);
437
+				} elseif ($subsection instanceof EE_Form_Section_Proper) {
438
+					$subsection->populate_defaults($default_data[ $subsection_name ]);
439
+				}
440
+			}
441
+		}
442
+	}
443
+
444
+
445
+	/**
446
+	 * returns true if subsection exists
447
+	 *
448
+	 * @param string $name
449
+	 * @return boolean
450
+	 */
451
+	public function subsection_exists($name)
452
+	{
453
+		return isset($this->_subsections[ $name ]) ? true : false;
454
+	}
455
+
456
+
457
+	/**
458
+	 * Gets the subsection specified by its name
459
+	 *
460
+	 * @param string  $name
461
+	 * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
462
+	 *                                                      so that the inputs will be properly configured.
463
+	 *                                                      However, some client code may be ok
464
+	 *                                                      with construction finalize being called later
465
+	 *                                                      (realizing that the subsections' html names
466
+	 *                                                      might not be set yet, etc.)
467
+	 * @return EE_Form_Section_Base
468
+	 * @throws EE_Error
469
+	 */
470
+	public function get_subsection($name, $require_construction_to_be_finalized = true)
471
+	{
472
+		if ($require_construction_to_be_finalized) {
473
+			$this->ensure_construct_finalized_called();
474
+		}
475
+		return $this->subsection_exists($name) ? $this->_subsections[ $name ] : null;
476
+	}
477
+
478
+
479
+	/**
480
+	 * Gets all the validatable subsections of this form section
481
+	 *
482
+	 * @return EE_Form_Section_Validatable[]
483
+	 * @throws EE_Error
484
+	 */
485
+	public function get_validatable_subsections()
486
+	{
487
+		$validatable_subsections = array();
488
+		foreach ($this->subsections() as $name => $obj) {
489
+			if ($obj instanceof EE_Form_Section_Validatable) {
490
+				$validatable_subsections[ $name ] = $obj;
491
+			}
492
+		}
493
+		return $validatable_subsections;
494
+	}
495
+
496
+
497
+	/**
498
+	 * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
499
+	 * throw an EE_Error.
500
+	 *
501
+	 * @param string  $name
502
+	 * @param boolean $require_construction_to_be_finalized most client code should
503
+	 *                                                      leave this as TRUE so that the inputs will be properly
504
+	 *                                                      configured. However, some client code may be ok with
505
+	 *                                                      construction finalize being called later
506
+	 *                                                      (realizing that the subsections' html names might not be
507
+	 *                                                      set yet, etc.)
508
+	 * @return EE_Form_Input_Base
509
+	 * @throws EE_Error
510
+	 */
511
+	public function get_input($name, $require_construction_to_be_finalized = true)
512
+	{
513
+		$subsection = $this->get_subsection(
514
+			$name,
515
+			$require_construction_to_be_finalized
516
+		);
517
+		if (! $subsection instanceof EE_Form_Input_Base) {
518
+			throw new EE_Error(
519
+				sprintf(
520
+					esc_html__(
521
+						"Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
522
+						'event_espresso'
523
+					),
524
+					$name,
525
+					get_class($this),
526
+					$subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
527
+				)
528
+			);
529
+		}
530
+		return $subsection;
531
+	}
532
+
533
+
534
+	/**
535
+	 * Like get_input(), gets the proper subsection of the form given the name,
536
+	 * otherwise throws an EE_Error
537
+	 *
538
+	 * @param string  $name
539
+	 * @param boolean $require_construction_to_be_finalized most client code should
540
+	 *                                                      leave this as TRUE so that the inputs will be properly
541
+	 *                                                      configured. However, some client code may be ok with
542
+	 *                                                      construction finalize being called later
543
+	 *                                                      (realizing that the subsections' html names might not be
544
+	 *                                                      set yet, etc.)
545
+	 * @return EE_Form_Section_Proper
546
+	 * @throws EE_Error
547
+	 */
548
+	public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
549
+	{
550
+		$subsection = $this->get_subsection(
551
+			$name,
552
+			$require_construction_to_be_finalized
553
+		);
554
+		if (! $subsection instanceof EE_Form_Section_Proper) {
555
+			throw new EE_Error(
556
+				sprintf(
557
+					esc_html__(
558
+						"Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'",
559
+						'event_espresso'
560
+					),
561
+					$name,
562
+					get_class($this)
563
+				)
564
+			);
565
+		}
566
+		return $subsection;
567
+	}
568
+
569
+
570
+	/**
571
+	 * Gets the value of the specified input. Should be called after receive_form_submission()
572
+	 * or populate_defaults() on the form, where the normalized value on the input is set.
573
+	 *
574
+	 * @param string $name
575
+	 * @return mixed depending on the input's type and its normalization strategy
576
+	 * @throws EE_Error
577
+	 */
578
+	public function get_input_value($name)
579
+	{
580
+		$input = $this->get_input($name);
581
+		return $input->normalized_value();
582
+	}
583
+
584
+
585
+	/**
586
+	 * Checks if this form section itself is valid, and then checks its subsections
587
+	 *
588
+	 * @throws EE_Error
589
+	 * @return boolean
590
+	 */
591
+	public function is_valid()
592
+	{
593
+		if ($this->is_valid === null) {
594
+			if (! $this->has_received_submission()) {
595
+				throw new EE_Error(
596
+					sprintf(
597
+						esc_html__(
598
+							'You cannot check if a form is valid before receiving the form submission using receive_form_submission',
599
+							'event_espresso'
600
+						)
601
+					)
602
+				);
603
+			}
604
+			if (! parent::is_valid()) {
605
+				$this->is_valid = false;
606
+			} else {
607
+				// ok so no general errors to this entire form section.
608
+				// so let's check the subsections, but only set errors if that hasn't been done yet
609
+				$this->is_valid = true;
610
+				foreach ($this->get_validatable_subsections() as $subsection) {
611
+					if (! $subsection->is_valid()) {
612
+						$this->is_valid = false;
613
+					}
614
+				}
615
+			}
616
+		}
617
+		return $this->is_valid;
618
+	}
619
+
620
+
621
+	/**
622
+	 * gets the default name of this form section if none is specified
623
+	 *
624
+	 * @return void
625
+	 */
626
+	protected function _set_default_name_if_empty()
627
+	{
628
+		if (! $this->_name) {
629
+			$classname    = get_class($this);
630
+			$default_name = str_replace('EE_', '', $classname);
631
+			$this->_name  = $default_name;
632
+		}
633
+	}
634
+
635
+
636
+	/**
637
+	 * Returns the HTML for the form, except for the form opening and closing tags
638
+	 * (as the form section doesn't know where you necessarily want to send the information to),
639
+	 * and except for a submit button. Enqueues JS and CSS; if called early enough we will
640
+	 * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
641
+	 * Not doing_it_wrong because theoretically this CAN be used properly,
642
+	 * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
643
+	 * any CSS.
644
+	 *
645
+	 * @throws InvalidArgumentException
646
+	 * @throws InvalidInterfaceException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws EE_Error
649
+	 */
650
+	public function get_html_and_js()
651
+	{
652
+		$this->enqueue_js();
653
+		return $this->get_html();
654
+	}
655
+
656
+
657
+	/**
658
+	 * returns HTML for displaying this form section. recursively calls display_section() on all subsections
659
+	 *
660
+	 * @param bool $display_previously_submitted_data
661
+	 * @return string
662
+	 * @throws InvalidArgumentException
663
+	 * @throws InvalidInterfaceException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws EE_Error
666
+	 * @throws EE_Error
667
+	 * @throws EE_Error
668
+	 */
669
+	public function get_html($display_previously_submitted_data = true)
670
+	{
671
+		$this->ensure_construct_finalized_called();
672
+		if ($display_previously_submitted_data) {
673
+			$this->populate_from_session();
674
+		}
675
+		return $this->_form_html_filter
676
+			? $this->_form_html_filter->filterHtml($this->_layout_strategy->layout_form(), $this)
677
+			: $this->_layout_strategy->layout_form();
678
+	}
679
+
680
+
681
+	/**
682
+	 * enqueues JS and CSS for the form.
683
+	 * It is preferred to call this before wp_enqueue_scripts so the
684
+	 * scripts and styles can be put in the header, but if called later
685
+	 * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
686
+	 * only be in the header; but in HTML5 its ok in the body.
687
+	 * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
688
+	 * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
689
+	 *
690
+	 * @return void
691
+	 * @throws EE_Error
692
+	 */
693
+	public function enqueue_js()
694
+	{
695
+		$this->_enqueue_and_localize_form_js();
696
+		foreach ($this->subsections() as $subsection) {
697
+			$subsection->enqueue_js();
698
+		}
699
+	}
700
+
701
+
702
+	/**
703
+	 * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
704
+	 * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
705
+	 * the wp_enqueue_scripts hook.
706
+	 * However, registering the form js and localizing it can happen when we
707
+	 * actually output the form (which is preferred, seeing how teh form's fields
708
+	 * could change until it's actually outputted)
709
+	 *
710
+	 * @param boolean $init_form_validation_automatically whether or not we want the form validation
711
+	 *                                                    to be triggered automatically or not
712
+	 * @return void
713
+	 */
714
+	public static function wp_enqueue_scripts($init_form_validation_automatically = true)
715
+	{
716
+		wp_register_script(
717
+			'ee_form_section_validation',
718
+			EE_GLOBAL_ASSETS_URL . 'scripts' . '/form_section_validation.js',
719
+			array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
720
+			EVENT_ESPRESSO_VERSION,
721
+			true
722
+		);
723
+		wp_localize_script(
724
+			'ee_form_section_validation',
725
+			'ee_form_section_validation_init',
726
+			array('init' => $init_form_validation_automatically ? '1' : '0')
727
+		);
728
+	}
729
+
730
+
731
+	/**
732
+	 * gets the variables used by form_section_validation.js.
733
+	 * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
734
+	 * but before the wordpress hook wp_loaded
735
+	 *
736
+	 * @throws EE_Error
737
+	 */
738
+	public function _enqueue_and_localize_form_js()
739
+	{
740
+		$this->ensure_construct_finalized_called();
741
+		// actually, we don't want to localize just yet. There may be other forms on the page.
742
+		// so we need to add our form section data to a static variable accessible by all form sections
743
+		// and localize it just before the footer
744
+		$this->localize_validation_rules();
745
+		add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
746
+		add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
747
+	}
748
+
749
+
750
+	/**
751
+	 * add our form section data to a static variable accessible by all form sections
752
+	 *
753
+	 * @param bool $return_for_subsection
754
+	 * @return void
755
+	 * @throws EE_Error
756
+	 */
757
+	public function localize_validation_rules($return_for_subsection = false)
758
+	{
759
+		// we only want to localize vars ONCE for the entire form,
760
+		// so if the form section doesn't have a parent, then it must be the top dog
761
+		if ($return_for_subsection || ! $this->parent_section()) {
762
+			EE_Form_Section_Proper::$_js_localization['form_data'][ $this->html_id() ] = array(
763
+				'form_section_id'  => $this->html_id(true),
764
+				'validation_rules' => $this->get_jquery_validation_rules(),
765
+				'other_data'       => $this->get_other_js_data(),
766
+				'errors'           => $this->subsection_validation_errors_by_html_name(),
767
+			);
768
+			EE_Form_Section_Proper::$_scripts_localized                                = true;
769
+		}
770
+	}
771
+
772
+
773
+	/**
774
+	 * Gets an array of extra data that will be useful for client-side javascript.
775
+	 * This is primarily data added by inputs and forms in addition to any
776
+	 * scripts they might enqueue
777
+	 *
778
+	 * @param array $form_other_js_data
779
+	 * @return array
780
+	 * @throws EE_Error
781
+	 */
782
+	public function get_other_js_data($form_other_js_data = array())
783
+	{
784
+		foreach ($this->subsections() as $subsection) {
785
+			$form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
786
+		}
787
+		return $form_other_js_data;
788
+	}
789
+
790
+
791
+	/**
792
+	 * Gets a flat array of inputs for this form section and its subsections.
793
+	 * Keys are their form names, and values are the inputs themselves
794
+	 *
795
+	 * @return EE_Form_Input_Base
796
+	 * @throws EE_Error
797
+	 */
798
+	public function inputs_in_subsections()
799
+	{
800
+		$inputs = array();
801
+		foreach ($this->subsections() as $subsection) {
802
+			if ($subsection instanceof EE_Form_Input_Base) {
803
+				$inputs[ $subsection->html_name() ] = $subsection;
804
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
805
+				$inputs += $subsection->inputs_in_subsections();
806
+			}
807
+		}
808
+		return $inputs;
809
+	}
810
+
811
+
812
+	/**
813
+	 * Gets a flat array of all the validation errors.
814
+	 * Keys are html names (because those should be unique)
815
+	 * and values are a string of all their validation errors
816
+	 *
817
+	 * @return string[]
818
+	 * @throws EE_Error
819
+	 */
820
+	public function subsection_validation_errors_by_html_name()
821
+	{
822
+		$inputs = $this->inputs();
823
+		$errors = array();
824
+		foreach ($inputs as $form_input) {
825
+			if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
826
+				$errors[ $form_input->html_name() ] = $form_input->get_validation_error_string();
827
+			}
828
+		}
829
+		return $errors;
830
+	}
831
+
832
+
833
+	/**
834
+	 * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
835
+	 * Should be setup by each form during the _enqueues_and_localize_form_js
836
+	 *
837
+	 * @throws InvalidArgumentException
838
+	 * @throws InvalidInterfaceException
839
+	 * @throws InvalidDataTypeException
840
+	 */
841
+	public static function localize_script_for_all_forms()
842
+	{
843
+		// allow inputs and stuff to hook in their JS and stuff here
844
+		do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
845
+		EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
846
+		$email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
847
+			? EE_Registry::instance()->CFG->registration->email_validation_level
848
+			: 'wp_default';
849
+		EE_Form_Section_Proper::$_js_localization['email_validation_level']   = $email_validation_level;
850
+		wp_enqueue_script('ee_form_section_validation');
851
+		wp_localize_script(
852
+			'ee_form_section_validation',
853
+			'ee_form_section_vars',
854
+			EE_Form_Section_Proper::$_js_localization
855
+		);
856
+	}
857
+
858
+
859
+	/**
860
+	 * ensure_scripts_localized
861
+	 *
862
+	 * @throws EE_Error
863
+	 */
864
+	public function ensure_scripts_localized()
865
+	{
866
+		if (! EE_Form_Section_Proper::$_scripts_localized) {
867
+			$this->_enqueue_and_localize_form_js();
868
+		}
869
+	}
870
+
871
+
872
+	/**
873
+	 * Gets the hard-coded validation error messages to be used in the JS. The convention
874
+	 * is that the key here should be the same as the custom validation rule put in the JS file
875
+	 *
876
+	 * @return array keys are custom validation rules, and values are internationalized strings
877
+	 */
878
+	private static function _get_localized_error_messages()
879
+	{
880
+		return array(
881
+			'validUrl' => wp_strip_all_tags(__('This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg', 'event_espresso')),
882
+			'regex'    => wp_strip_all_tags(__('Please check your input', 'event_espresso'))
883
+		);
884
+	}
885
+
886
+
887
+	/**
888
+	 * @return array
889
+	 */
890
+	public static function js_localization()
891
+	{
892
+		return self::$_js_localization;
893
+	}
894
+
895
+
896
+	/**
897
+	 * @return void
898
+	 */
899
+	public static function reset_js_localization()
900
+	{
901
+		self::$_js_localization = array();
902
+	}
903
+
904
+
905
+	/**
906
+	 * Gets the JS to put inside the jquery validation rules for subsection of this form section.
907
+	 * See parent function for more...
908
+	 *
909
+	 * @return array
910
+	 * @throws EE_Error
911
+	 */
912
+	public function get_jquery_validation_rules()
913
+	{
914
+		$jquery_validation_rules = array();
915
+		foreach ($this->get_validatable_subsections() as $subsection) {
916
+			$jquery_validation_rules = array_merge(
917
+				$jquery_validation_rules,
918
+				$subsection->get_jquery_validation_rules()
919
+			);
920
+		}
921
+		return $jquery_validation_rules;
922
+	}
923
+
924
+
925
+	/**
926
+	 * Sanitizes all the data and sets the sanitized value of each field
927
+	 *
928
+	 * @param array $req_data
929
+	 * @return void
930
+	 * @throws EE_Error
931
+	 */
932
+	protected function _normalize($req_data)
933
+	{
934
+		$this->_received_submission = true;
935
+		$this->_validation_errors   = array();
936
+		foreach ($this->get_validatable_subsections() as $subsection) {
937
+			try {
938
+				$subsection->_normalize($req_data);
939
+			} catch (EE_Validation_Error $e) {
940
+				$subsection->add_validation_error($e);
941
+			}
942
+		}
943
+	}
944
+
945
+
946
+	/**
947
+	 * Performs validation on this form section and its subsections.
948
+	 * For each subsection,
949
+	 * calls _validate_{subsection_name} on THIS form (if the function exists)
950
+	 * and passes it the subsection, then calls _validate on that subsection.
951
+	 * If you need to perform validation on the form as a whole (considering multiple)
952
+	 * you would be best to override this _validate method,
953
+	 * calling parent::_validate() first.
954
+	 *
955
+	 * @throws EE_Error
956
+	 */
957
+	protected function _validate()
958
+	{
959
+		// reset the cache of whether this form is valid or not- we're re-validating it now
960
+		$this->is_valid = null;
961
+		foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
962
+			if (method_exists($this, '_validate_' . $subsection_name)) {
963
+				call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
964
+			}
965
+			$subsection->_validate();
966
+		}
967
+	}
968
+
969
+
970
+	/**
971
+	 * Gets all the validated inputs for the form section
972
+	 *
973
+	 * @return array
974
+	 * @throws EE_Error
975
+	 */
976
+	public function valid_data()
977
+	{
978
+		$inputs = array();
979
+		foreach ($this->subsections() as $subsection_name => $subsection) {
980
+			if ($subsection instanceof EE_Form_Section_Proper) {
981
+				$inputs[ $subsection_name ] = $subsection->valid_data();
982
+			} elseif ($subsection instanceof EE_Form_Input_Base) {
983
+				$inputs[ $subsection_name ] = $subsection->normalized_value();
984
+			}
985
+		}
986
+		return $inputs;
987
+	}
988
+
989
+
990
+	/**
991
+	 * Gets all the inputs on this form section
992
+	 *
993
+	 * @return EE_Form_Input_Base[]
994
+	 * @throws EE_Error
995
+	 */
996
+	public function inputs()
997
+	{
998
+		$inputs = array();
999
+		foreach ($this->subsections() as $subsection_name => $subsection) {
1000
+			if ($subsection instanceof EE_Form_Input_Base) {
1001
+				$inputs[ $subsection_name ] = $subsection;
1002
+			}
1003
+		}
1004
+		return $inputs;
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Gets all the subsections which are a proper form
1010
+	 *
1011
+	 * @return EE_Form_Section_Proper[]
1012
+	 * @throws EE_Error
1013
+	 */
1014
+	public function subforms()
1015
+	{
1016
+		$form_sections = array();
1017
+		foreach ($this->subsections() as $name => $obj) {
1018
+			if ($obj instanceof EE_Form_Section_Proper) {
1019
+				$form_sections[ $name ] = $obj;
1020
+			}
1021
+		}
1022
+		return $form_sections;
1023
+	}
1024
+
1025
+
1026
+	/**
1027
+	 * Gets all the subsections (inputs, proper subsections, or html-only sections).
1028
+	 * Consider using inputs() or subforms()
1029
+	 * if you only want form inputs or proper form sections.
1030
+	 *
1031
+	 * @param boolean $require_construction_to_be_finalized most client code should
1032
+	 *                                                      leave this as TRUE so that the inputs will be properly
1033
+	 *                                                      configured. However, some client code may be ok with
1034
+	 *                                                      construction finalize being called later
1035
+	 *                                                      (realizing that the subsections' html names might not be
1036
+	 *                                                      set yet, etc.)
1037
+	 * @return EE_Form_Section_Proper[]
1038
+	 * @throws EE_Error
1039
+	 */
1040
+	public function subsections($require_construction_to_be_finalized = true)
1041
+	{
1042
+		if ($require_construction_to_be_finalized) {
1043
+			$this->ensure_construct_finalized_called();
1044
+		}
1045
+		return $this->_subsections;
1046
+	}
1047
+
1048
+
1049
+	/**
1050
+	 * Returns whether this form has any subforms or inputs
1051
+	 * @return bool
1052
+	 */
1053
+	public function hasSubsections()
1054
+	{
1055
+		return ! empty($this->_subsections);
1056
+	}
1057
+
1058
+
1059
+	/**
1060
+	 * Returns a simple array where keys are input names, and values are their normalized
1061
+	 * values. (Similar to calling get_input_value on inputs)
1062
+	 *
1063
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1064
+	 *                                        or just this forms' direct children inputs
1065
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1066
+	 *                                        or allow multidimensional array
1067
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
1068
+	 *                                        with array keys being input names
1069
+	 *                                        (regardless of whether they are from a subsection or not),
1070
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
1071
+	 *                                        where keys are always subsection names and values are either
1072
+	 *                                        the input's normalized value, or an array like the top-level array
1073
+	 * @throws EE_Error
1074
+	 */
1075
+	public function input_values($include_subform_inputs = false, $flatten = false)
1076
+	{
1077
+		return $this->_input_values(false, $include_subform_inputs, $flatten);
1078
+	}
1079
+
1080
+
1081
+	/**
1082
+	 * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
1083
+	 * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
1084
+	 * is not necessarily the value we want to display to users. This creates an array
1085
+	 * where keys are the input names, and values are their display values
1086
+	 *
1087
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1088
+	 *                                        or just this forms' direct children inputs
1089
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1090
+	 *                                        or allow multidimensional array
1091
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
1092
+	 *                                        with array keys being input names
1093
+	 *                                        (regardless of whether they are from a subsection or not),
1094
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
1095
+	 *                                        where keys are always subsection names and values are either
1096
+	 *                                        the input's normalized value, or an array like the top-level array
1097
+	 * @throws EE_Error
1098
+	 */
1099
+	public function input_pretty_values($include_subform_inputs = false, $flatten = false)
1100
+	{
1101
+		return $this->_input_values(true, $include_subform_inputs, $flatten);
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 * Gets the input values from the form
1107
+	 *
1108
+	 * @param boolean $pretty                 Whether to retrieve the pretty value,
1109
+	 *                                        or just the normalized value
1110
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1111
+	 *                                        or just this forms' direct children inputs
1112
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1113
+	 *                                        or allow multidimensional array
1114
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
1115
+	 *                                        input names (regardless of whether they are from a subsection or not),
1116
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
1117
+	 *                                        where keys are always subsection names and values are either
1118
+	 *                                        the input's normalized value, or an array like the top-level array
1119
+	 * @throws EE_Error
1120
+	 */
1121
+	public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
1122
+	{
1123
+		$input_values = array();
1124
+		foreach ($this->subsections() as $subsection_name => $subsection) {
1125
+			if ($subsection instanceof EE_Form_Input_Base) {
1126
+				$input_values[ $subsection_name ] = $pretty
1127
+					? $subsection->pretty_value()
1128
+					: $subsection->normalized_value();
1129
+			} elseif ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1130
+				$subform_input_values = $subsection->_input_values(
1131
+					$pretty,
1132
+					$include_subform_inputs,
1133
+					$flatten
1134
+				);
1135
+				if ($flatten) {
1136
+					$input_values = array_merge($input_values, $subform_input_values);
1137
+				} else {
1138
+					$input_values[ $subsection_name ] = $subform_input_values;
1139
+				}
1140
+			}
1141
+		}
1142
+		return $input_values;
1143
+	}
1144
+
1145
+
1146
+	/**
1147
+	 * Gets the originally submitted input values from the form
1148
+	 *
1149
+	 * @param boolean $include_subforms  Whether to include inputs from subforms,
1150
+	 *                                   or just this forms' direct children inputs
1151
+	 * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1152
+	 *                                   with array keys being input names
1153
+	 *                                   (regardless of whether they are from a subsection or not),
1154
+	 *                                   and if $flatten is FALSE it can be a multidimensional array
1155
+	 *                                   where keys are always subsection names and values are either
1156
+	 *                                   the input's normalized value, or an array like the top-level array
1157
+	 * @throws EE_Error
1158
+	 */
1159
+	public function submitted_values($include_subforms = false)
1160
+	{
1161
+		$submitted_values = array();
1162
+		foreach ($this->subsections() as $subsection) {
1163
+			if ($subsection instanceof EE_Form_Input_Base) {
1164
+				// is this input part of an array of inputs?
1165
+				if (strpos($subsection->html_name(), '[') !== false) {
1166
+					$full_input_name  = EEH_Array::convert_array_values_to_keys(
1167
+						explode(
1168
+							'[',
1169
+							str_replace(']', '', $subsection->html_name())
1170
+						),
1171
+						$subsection->raw_value()
1172
+					);
1173
+					$submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1174
+				} else {
1175
+					$submitted_values[ $subsection->html_name() ] = $subsection->raw_value();
1176
+				}
1177
+			} elseif ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1178
+				$subform_input_values = $subsection->submitted_values($include_subforms);
1179
+				$submitted_values     = array_replace_recursive($submitted_values, $subform_input_values);
1180
+			}
1181
+		}
1182
+		return $submitted_values;
1183
+	}
1184
+
1185
+
1186
+	/**
1187
+	 * Indicates whether or not this form has received a submission yet
1188
+	 * (ie, had receive_form_submission called on it yet)
1189
+	 *
1190
+	 * @return boolean
1191
+	 * @throws EE_Error
1192
+	 */
1193
+	public function has_received_submission()
1194
+	{
1195
+		$this->ensure_construct_finalized_called();
1196
+		return $this->_received_submission;
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * Equivalent to passing 'exclude' in the constructor's options array.
1202
+	 * Removes the listed inputs from the form
1203
+	 *
1204
+	 * @param array $inputs_to_exclude values are the input names
1205
+	 * @return void
1206
+	 */
1207
+	public function exclude(array $inputs_to_exclude = array())
1208
+	{
1209
+		foreach ($inputs_to_exclude as $input_to_exclude_name) {
1210
+			unset($this->_subsections[ $input_to_exclude_name ]);
1211
+		}
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * Changes these inputs' display strategy to be EE_Hidden_Display_Strategy.
1217
+	 * @param array $inputs_to_hide
1218
+	 * @throws EE_Error
1219
+	 */
1220
+	public function hide(array $inputs_to_hide = array())
1221
+	{
1222
+		foreach ($inputs_to_hide as $input_to_hide) {
1223
+			$input = $this->get_input($input_to_hide);
1224
+			$input->set_display_strategy(new EE_Hidden_Display_Strategy());
1225
+		}
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * add_subsections
1231
+	 * Adds the listed subsections to the form section.
1232
+	 * If $subsection_name_to_target is provided,
1233
+	 * then new subsections are added before or after that subsection,
1234
+	 * otherwise to the start or end of the entire subsections array.
1235
+	 *
1236
+	 * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1237
+	 *                                                          where keys are their names
1238
+	 * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1239
+	 *                                                          should be added before or after
1240
+	 *                                                          IF $subsection_name_to_target is null,
1241
+	 *                                                          then $new_subsections will be added to
1242
+	 *                                                          the beginning or end of the entire subsections array
1243
+	 * @param boolean                $add_before                whether to add $new_subsections, before or after
1244
+	 *                                                          $subsection_name_to_target,
1245
+	 *                                                          or if $subsection_name_to_target is null,
1246
+	 *                                                          before or after entire subsections array
1247
+	 * @return void
1248
+	 * @throws EE_Error
1249
+	 */
1250
+	public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1251
+	{
1252
+		foreach ($new_subsections as $subsection_name => $subsection) {
1253
+			if (! $subsection instanceof EE_Form_Section_Base) {
1254
+				EE_Error::add_error(
1255
+					sprintf(
1256
+						esc_html__(
1257
+							"Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1258
+							'event_espresso'
1259
+						),
1260
+						get_class($subsection),
1261
+						$subsection_name,
1262
+						$this->name()
1263
+					)
1264
+				);
1265
+				unset($new_subsections[ $subsection_name ]);
1266
+			}
1267
+		}
1268
+		$this->_subsections = EEH_Array::insert_into_array(
1269
+			$this->_subsections,
1270
+			$new_subsections,
1271
+			$subsection_name_to_target,
1272
+			$add_before
1273
+		);
1274
+		if ($this->_construction_finalized) {
1275
+			foreach ($this->_subsections as $name => $subsection) {
1276
+				$subsection->_construct_finalize($this, $name);
1277
+			}
1278
+		}
1279
+	}
1280
+
1281
+
1282
+	/**
1283
+	 * @param string $subsection_name
1284
+	 * @param bool   $recursive
1285
+	 * @return bool
1286
+	 */
1287
+	public function has_subsection($subsection_name, $recursive = false)
1288
+	{
1289
+		foreach ($this->_subsections as $name => $subsection) {
1290
+			if (
1291
+				$name === $subsection_name
1292
+				|| (
1293
+					$recursive
1294
+					&& $subsection instanceof EE_Form_Section_Proper
1295
+					&& $subsection->has_subsection($subsection_name, $recursive)
1296
+				)
1297
+			) {
1298
+				return true;
1299
+			}
1300
+		}
1301
+		return false;
1302
+	}
1303
+
1304
+
1305
+
1306
+	/**
1307
+	 * Just gets all validatable subsections to clean their sensitive data
1308
+	 *
1309
+	 * @throws EE_Error
1310
+	 */
1311
+	public function clean_sensitive_data()
1312
+	{
1313
+		foreach ($this->get_validatable_subsections() as $subsection) {
1314
+			$subsection->clean_sensitive_data();
1315
+		}
1316
+	}
1317
+
1318
+
1319
+	/**
1320
+	 * Sets the submission error message (aka validation error message for this form section and all sub-sections)
1321
+	 * @param string                           $form_submission_error_message
1322
+	 * @param EE_Form_Section_Validatable $form_section unused
1323
+	 * @throws EE_Error
1324
+	 */
1325
+	public function set_submission_error_message(
1326
+		$form_submission_error_message = ''
1327
+	) {
1328
+		$this->_form_submission_error_message = ! empty($form_submission_error_message)
1329
+			? $form_submission_error_message
1330
+			: $this->getAllValidationErrorsString();
1331
+	}
1332
+
1333
+
1334
+	/**
1335
+	 * Returns the cached error message. A default value is set for this during _validate(),
1336
+	 * (called during receive_form_submission) but it can be explicitly set using
1337
+	 * set_submission_error_message
1338
+	 *
1339
+	 * @return string
1340
+	 */
1341
+	public function submission_error_message()
1342
+	{
1343
+		return $this->_form_submission_error_message;
1344
+	}
1345
+
1346
+
1347
+	/**
1348
+	 * Sets a message to display if the data submitted to the form was valid.
1349
+	 * @param string $form_submission_success_message
1350
+	 */
1351
+	public function set_submission_success_message($form_submission_success_message = '')
1352
+	{
1353
+		$this->_form_submission_success_message = ! empty($form_submission_success_message)
1354
+			? $form_submission_success_message
1355
+			: esc_html__('Form submitted successfully', 'event_espresso');
1356
+	}
1357
+
1358
+
1359
+	/**
1360
+	 * Gets a message appropriate for display when the form is correctly submitted
1361
+	 * @return string
1362
+	 */
1363
+	public function submission_success_message()
1364
+	{
1365
+		return $this->_form_submission_success_message;
1366
+	}
1367
+
1368
+
1369
+	/**
1370
+	 * Returns the prefix that should be used on child of this form section for
1371
+	 * their html names. If this form section itself has a parent, prepends ITS
1372
+	 * prefix onto this form section's prefix. Used primarily by
1373
+	 * EE_Form_Input_Base::_set_default_html_name_if_empty
1374
+	 *
1375
+	 * @return string
1376
+	 * @throws EE_Error
1377
+	 */
1378
+	public function html_name_prefix()
1379
+	{
1380
+		if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1381
+			return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1382
+		}
1383
+		return $this->name();
1384
+	}
1385
+
1386
+
1387
+	/**
1388
+	 * Gets the name, but first checks _construct_finalize has been called. If not,
1389
+	 * calls it (assumes there is no parent and that we want the name to be whatever
1390
+	 * was set, which is probably nothing, or the classname)
1391
+	 *
1392
+	 * @return string
1393
+	 * @throws EE_Error
1394
+	 */
1395
+	public function name()
1396
+	{
1397
+		$this->ensure_construct_finalized_called();
1398
+		return parent::name();
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * @return EE_Form_Section_Proper
1404
+	 * @throws EE_Error
1405
+	 */
1406
+	public function parent_section()
1407
+	{
1408
+		$this->ensure_construct_finalized_called();
1409
+		return parent::parent_section();
1410
+	}
1411
+
1412
+
1413
+	/**
1414
+	 * make sure construction finalized was called, otherwise children might not be ready
1415
+	 *
1416
+	 * @return void
1417
+	 * @throws EE_Error
1418
+	 */
1419
+	public function ensure_construct_finalized_called()
1420
+	{
1421
+		if (! $this->_construction_finalized) {
1422
+			$this->_construct_finalize($this->_parent_section, $this->_name);
1423
+		}
1424
+	}
1425
+
1426
+
1427
+	/**
1428
+	 * Checks if any of this form section's inputs, or any of its children's inputs,
1429
+	 * are in teh form data. If any are found, returns true. Else false
1430
+	 *
1431
+	 * @param array $req_data
1432
+	 * @return boolean
1433
+	 * @throws EE_Error
1434
+	 */
1435
+	public function form_data_present_in($req_data = null)
1436
+	{
1437
+		$req_data = $this->getCachedRequest($req_data);
1438
+		foreach ($this->subsections() as $subsection) {
1439
+			if ($subsection instanceof EE_Form_Input_Base) {
1440
+				if ($subsection->form_data_present_in($req_data)) {
1441
+					return true;
1442
+				}
1443
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
1444
+				if ($subsection->form_data_present_in($req_data)) {
1445
+					return true;
1446
+				}
1447
+			}
1448
+		}
1449
+		return false;
1450
+	}
1451
+
1452
+
1453
+	/**
1454
+	 * Gets validation errors for this form section and subsections
1455
+	 * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1456
+	 * gets the validation errors for ALL subsection
1457
+	 *
1458
+	 * @return EE_Validation_Error[]
1459
+	 * @throws EE_Error
1460
+	 */
1461
+	public function get_validation_errors_accumulated()
1462
+	{
1463
+		$validation_errors = $this->get_validation_errors();
1464
+		foreach ($this->get_validatable_subsections() as $subsection) {
1465
+			if ($subsection instanceof EE_Form_Section_Proper) {
1466
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1467
+			} else {
1468
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors();
1469
+			}
1470
+			if ($validation_errors_on_this_subsection) {
1471
+				$validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1472
+			}
1473
+		}
1474
+		return $validation_errors;
1475
+	}
1476
+
1477
+	/**
1478
+	 * Fetch validation errors from children and grandchildren and puts them in a single string.
1479
+	 * This traverses the form section tree to generate this, but you probably want to instead use
1480
+	 * get_form_submission_error_message() which is usually this message cached (or a custom validation error message)
1481
+	 *
1482
+	 * @return string
1483
+	 * @since 4.9.59.p
1484
+	 */
1485
+	protected function getAllValidationErrorsString()
1486
+	{
1487
+		$submission_error_messages = array();
1488
+		// bad, bad, bad registrant
1489
+		foreach ($this->get_validation_errors_accumulated() as $validation_error) {
1490
+			if ($validation_error instanceof EE_Validation_Error) {
1491
+				$form_section = $validation_error->get_form_section();
1492
+				if ($form_section instanceof EE_Form_Input_Base) {
1493
+					$label = $validation_error->get_form_section()->html_label_text();
1494
+				} elseif ($form_section instanceof EE_Form_Section_Validatable) {
1495
+					$label = $validation_error->get_form_section()->name();
1496
+				} else {
1497
+					$label = esc_html__('Unknown', 'event_espresso');
1498
+				}
1499
+				$submission_error_messages[] = sprintf(
1500
+					esc_html__('%s : %s', 'event_espresso'),
1501
+					$label,
1502
+					$validation_error->getMessage()
1503
+				);
1504
+			}
1505
+		}
1506
+		return implode('<br>', $submission_error_messages);
1507
+	}
1508
+
1509
+
1510
+	/**
1511
+	 * This isn't just the name of an input, it's a path pointing to an input. The
1512
+	 * path is similar to a folder path: slash (/) means to descend into a subsection,
1513
+	 * dot-dot-slash (../) means to ascend into the parent section.
1514
+	 * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1515
+	 * which will be returned.
1516
+	 * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1517
+	 * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1518
+	 * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1519
+	 * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1520
+	 * Etc
1521
+	 *
1522
+	 * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1523
+	 * @return EE_Form_Section_Base
1524
+	 * @throws EE_Error
1525
+	 */
1526
+	public function find_section_from_path($form_section_path)
1527
+	{
1528
+		// check if we can find the input from purely going straight up the tree
1529
+		$input = parent::find_section_from_path($form_section_path);
1530
+		if ($input instanceof EE_Form_Section_Base) {
1531
+			return $input;
1532
+		}
1533
+		$next_slash_pos = strpos($form_section_path, '/');
1534
+		if ($next_slash_pos !== false) {
1535
+			$child_section_name = substr($form_section_path, 0, $next_slash_pos);
1536
+			$subpath            = substr($form_section_path, $next_slash_pos + 1);
1537
+		} else {
1538
+			$child_section_name = $form_section_path;
1539
+			$subpath            = '';
1540
+		}
1541
+		$child_section = $this->get_subsection($child_section_name);
1542
+		if ($child_section instanceof EE_Form_Section_Base) {
1543
+			return $child_section->find_section_from_path($subpath);
1544
+		}
1545
+		return null;
1546
+	}
1547 1547
 }
Please login to merge, or discard this patch.
core/libraries/messages/messenger/EE_Html_messenger.class.php 1 patch
Indentation   +546 added lines, -546 removed lines patch added patch discarded remove patch
@@ -14,550 +14,550 @@
 block discarded – undo
14 14
 {
15 15
 
16 16
 
17
-    /**
18
-     * The following are the properties that this messenger requires for displaying the html
19
-     */
20
-    /**
21
-     * This is the html body generated by the template via the message type.
22
-     *
23
-     * @var string
24
-     */
25
-    protected $_content;
26
-
27
-
28
-    /**
29
-     * This is for the page title that gets displayed.  (Why use "subject"?  Because the "title" tag in html is
30
-     * equivalent to the "subject" of the page.
31
-     *
32
-     * @var string
33
-     */
34
-    protected $_subject;
35
-
36
-
37
-    /**
38
-     * EE_Html_messenger constructor.
39
-     */
40
-    public function __construct()
41
-    {
42
-        // set properties
43
-        $this->name = 'html';
44
-        $this->description = esc_html__('This messenger outputs a message to a browser for display.', 'event_espresso');
45
-        $this->label = array(
46
-            'singular' => esc_html__('html', 'event_espresso'),
47
-            'plural' => esc_html__('html', 'event_espresso'),
48
-        );
49
-        $this->activate_on_install = true;
50
-        // add the "powered by EE" credit link to the HTML receipt and invoice
51
-        add_filter(
52
-            'FHEE__EE_Html_messenger___send_message__main_body',
53
-            array($this, 'add_powered_by_credit_link_to_receipt_and_invoice'),
54
-            10,
55
-            3
56
-        );
57
-        parent::__construct();
58
-    }
59
-
60
-
61
-    /**
62
-     * HTML Messenger desires execution immediately.
63
-     *
64
-     * @see    parent::send_now() for documentation.
65
-     * @since  4.9.0
66
-     * @return bool
67
-     */
68
-    public function send_now()
69
-    {
70
-        return true;
71
-    }
72
-
73
-
74
-    /**
75
-     * HTML Messenger allows an empty to field.
76
-     *
77
-     * @see    parent::allow_empty_to_field() for documentation
78
-     * @since  4.9.0
79
-     * @return bool
80
-     */
81
-    public function allow_empty_to_field()
82
-    {
83
-        return true;
84
-    }
85
-
86
-
87
-    /**
88
-     * @see abstract declaration in EE_messenger for details.
89
-     */
90
-    protected function _set_admin_pages()
91
-    {
92
-        $this->admin_registered_pages = array('events_edit' => true);
93
-    }
94
-
95
-
96
-    /**
97
-     * @see abstract declaration in EE_messenger for details.
98
-     */
99
-    protected function _set_valid_shortcodes()
100
-    {
101
-        $this->_valid_shortcodes = array();
102
-    }
103
-
104
-
105
-    /**
106
-     * @see abstract declaration in EE_messenger for details.
107
-     */
108
-    protected function _set_validator_config()
109
-    {
110
-        $this->_validator_config = array(
111
-            'subject' => array(
112
-                'shortcodes' => array('organization', 'primary_registration_details', 'email', 'transaction'),
113
-            ),
114
-            'content' => array(
115
-                'shortcodes' => array(
116
-                    'organization',
117
-                    'primary_registration_list',
118
-                    'primary_registration_details',
119
-                    'email',
120
-                    'transaction',
121
-                    'event_list',
122
-                    'payment_list',
123
-                    'venue',
124
-                    'line_item_list',
125
-                    'messenger',
126
-                    'ticket_list',
127
-                ),
128
-            ),
129
-            'event_list' => array(
130
-                'shortcodes' => array(
131
-                    'event',
132
-                    'ticket_list',
133
-                    'venue',
134
-                    'primary_registration_details',
135
-                    'primary_registration_list',
136
-                    'event_author',
137
-                ),
138
-                'required' => array('[EVENT_LIST]'),
139
-            ),
140
-            'ticket_list' => array(
141
-                'shortcodes' => array(
142
-                    'attendee_list',
143
-                    'ticket',
144
-                    'datetime_list',
145
-                    'primary_registration_details',
146
-                    'line_item_list',
147
-                    'venue',
148
-                ),
149
-                'required' => array('[TICKET_LIST]'),
150
-            ),
151
-            'ticket_line_item_no_pms' => array(
152
-                'shortcodes' => array('line_item', 'ticket'),
153
-                'required' => array('[TICKET_LINE_ITEM_LIST]'),
154
-            ),
155
-            'ticket_line_item_pms' => array(
156
-                'shortcodes' => array('line_item', 'ticket', 'line_item_list'),
157
-                'required' => array('[TICKET_LINE_ITEM_LIST]'),
158
-            ),
159
-            'price_modifier_line_item_list' => array(
160
-                'shortcodes' => array('line_item'),
161
-                'required' => array('[PRICE_MODIFIER_LINE_ITEM_LIST]'),
162
-            ),
163
-            'datetime_list' => array(
164
-                'shortcodes' => array('datetime'),
165
-                'required' => array('[DATETIME_LIST]'),
166
-            ),
167
-            'attendee_list' => array(
168
-                'shortcodes' => array('attendee'),
169
-                'required' => array('[ATTENDEE_LIST]'),
170
-            ),
171
-            'tax_line_item_list' => array(
172
-                'shortcodes' => array('line_item'),
173
-                'required' => array('[TAX_LINE_ITEM_LIST]'),
174
-            ),
175
-            'additional_line_item_list' => array(
176
-                'shortcodes' => array('line_item'),
177
-                'required' => array('[ADDITIONAL_LINE_ITEM_LIST]'),
178
-            ),
179
-            'payment_list' => array(
180
-                'shortcodes' => array('payment'),
181
-                'required' => array('[PAYMENT_LIST_*]'),
182
-            ),
183
-        );
184
-    }
185
-
186
-
187
-    /**
188
-     * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger
189
-     * is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary
190
-     * (i.e. swap out css files or something else).
191
-     *
192
-     * @since 4.5.0
193
-     * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
194
-     * @return void
195
-     */
196
-    public function do_secondary_messenger_hooks($sending_messenger_name)
197
-    {
198
-        if ($sending_messenger_name === 'pdf') {
199
-            add_filter('EE_messenger__get_variation__variation', array($this, 'add_html_css'), 10, 8);
200
-        }
201
-    }
202
-
203
-
204
-    /**
205
-     * @param                            $variation_path
206
-     * @param \EE_Messages_Template_Pack $template_pack
207
-     * @param                            $messenger_name
208
-     * @param                            $message_type_name
209
-     * @param                            $url
210
-     * @param                            $type
211
-     * @param                            $variation
212
-     * @param                            $skip_filters
213
-     * @return string
214
-     */
215
-    public function add_html_css(
216
-        $variation_path,
217
-        EE_Messages_Template_Pack $template_pack,
218
-        $messenger_name,
219
-        $message_type_name,
220
-        $url,
221
-        $type,
222
-        $variation,
223
-        $skip_filters
224
-    ) {
225
-        $variation = $template_pack->get_variation(
226
-            $this->name,
227
-            $message_type_name,
228
-            $type,
229
-            $variation,
230
-            $url,
231
-            '.css',
232
-            $skip_filters
233
-        );
234
-        return $variation;
235
-    }
236
-
237
-
238
-    /**
239
-     * Takes care of enqueuing any necessary scripts or styles for the page.  A do_action() so message types using this
240
-     * messenger can add their own js.
241
-     *
242
-     * @return void.
243
-     */
244
-    public function enqueue_scripts_styles()
245
-    {
246
-        parent::enqueue_scripts_styles();
247
-        do_action('AHEE__EE_Html_messenger__enqueue_scripts_styles');
248
-    }
249
-
250
-
251
-    /**
252
-     * _set_template_fields
253
-     * This sets up the fields that a messenger requires for the message to go out.
254
-     *
255
-     * @access  protected
256
-     * @return void
257
-     */
258
-    protected function _set_template_fields()
259
-    {
260
-        // any extra template fields that are NOT used by the messenger
261
-        // but will get used by a messenger field for shortcode replacement
262
-        // get added to the 'extra' key in an associated array
263
-        // indexed by the messenger field they relate to.
264
-        // This is important for the Messages_admin to know what fields to display to the user.
265
-        // Also, notice that the "values" are equal to the field type
266
-        // that messages admin will use to know what kind of field to display.
267
-        // The values ALSO have one index labeled "shortcode".
268
-        // The values in that array indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE])
269
-        // is required in order for this extra field to be displayed.
270
-        //  If the required shortcode isn't part of the shortcodes array
271
-        // then the field is not needed and will not be displayed/parsed.
272
-        $this->_template_fields = array(
273
-            'subject' => array(
274
-                'input' => 'text',
275
-                'label' => esc_html__('Page Title', 'event_espresso'),
276
-                'type' => 'string',
277
-                'required' => true,
278
-                'validation' => true,
279
-                'css_class' => 'large-text',
280
-                'format' => '%s',
281
-            ),
282
-            'content' => '',
283
-            // left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
284
-            'extra' => array(
285
-                'content' => array(
286
-                    'main' => array(
287
-                        'input' => 'wp_editor',
288
-                        'label' => esc_html__('Main Content', 'event_espresso'),
289
-                        'type' => 'string',
290
-                        'required' => true,
291
-                        'validation' => true,
292
-                        'format' => '%s',
293
-                        'rows' => '15',
294
-                    ),
295
-                    'event_list' => array(
296
-                        'input' => 'wp_editor',
297
-                        'label' => '[EVENT_LIST]',
298
-                        'type' => 'string',
299
-                        'required' => true,
300
-                        'validation' => true,
301
-                        'format' => '%s',
302
-                        'rows' => '15',
303
-                        'shortcodes_required' => array('[EVENT_LIST]'),
304
-                    ),
305
-                    'ticket_list' => array(
306
-                        'input' => 'textarea',
307
-                        'label' => '[TICKET_LIST]',
308
-                        'type' => 'string',
309
-                        'required' => true,
310
-                        'validation' => true,
311
-                        'format' => '%s',
312
-                        'css_class' => 'large-text',
313
-                        'rows' => '10',
314
-                        'shortcodes_required' => array('[TICKET_LIST]'),
315
-                    ),
316
-                    'ticket_line_item_no_pms' => array(
317
-                        'input' => 'textarea',
318
-                        'label' => '[TICKET_LINE_ITEM_LIST] <br>' . esc_html__(
319
-                            'Ticket Line Item List with no Price Modifiers',
320
-                            'event_espresso'
321
-                        ),
322
-                        'type' => 'string',
323
-                        'required' => false,
324
-                        'validation' => true,
325
-                        'format' => '%s',
326
-                        'css_class' => 'large-text',
327
-                        'rows' => '5',
328
-                        'shortcodes_required' => array('[TICKET_LINE_ITEM_LIST]'),
329
-                    ),
330
-                    'ticket_line_item_pms' => array(
331
-                        'input' => 'textarea',
332
-                        'label' => '[TICKET_LINE_ITEM_LIST] <br>' . esc_html__(
333
-                            'Ticket Line Item List with Price Modifiers',
334
-                            'event_espresso'
335
-                        ),
336
-                        'type' => 'string',
337
-                        'required' => false,
338
-                        'validation' => true,
339
-                        'format' => '%s',
340
-                        'css_class' => 'large-text',
341
-                        'rows' => '5',
342
-                        'shortcodes_required' => array('[TICKET_LINE_ITEM_LIST]'),
343
-                    ),
344
-                    'price_modifier_line_item_list' => array(
345
-                        'input' => 'textarea',
346
-                        'label' => '[PRICE_MODIFIER_LINE_ITEM_LIST]',
347
-                        'type' => 'string',
348
-                        'required' => false,
349
-                        'validation' => true,
350
-                        'format' => '%s',
351
-                        'css_class' => 'large-text',
352
-                        'rows' => '5',
353
-                        'shortcodes_required' => array('[PRICE_MODIFIER_LINE_ITEM_LIST]'),
354
-                    ),
355
-                    'datetime_list' => array(
356
-                        'input' => 'textarea',
357
-                        'label' => '[DATETIME_LIST]',
358
-                        'type' => 'string',
359
-                        'required' => true,
360
-                        'validation' => true,
361
-                        'format' => '%s',
362
-                        'css_class' => 'large-text',
363
-                        'rows' => '5',
364
-                        'shortcodes_required' => array('[DATETIME_LIST]'),
365
-                    ),
366
-                    'attendee_list' => array(
367
-                        'input' => 'textarea',
368
-                        'label' => '[ATTENDEE_LIST]',
369
-                        'type' => 'string',
370
-                        'required' => true,
371
-                        'validation' => true,
372
-                        'format' => '%s',
373
-                        'css_class' => 'large-text',
374
-                        'rows' => '5',
375
-                        'shortcodes_required' => array('[ATTENDEE_LIST]'),
376
-                    ),
377
-                    'tax_line_item_list' => array(
378
-                        'input' => 'textarea',
379
-                        'label' => '[TAX_LINE_ITEM_LIST]',
380
-                        'type' => 'string',
381
-                        'required' => false,
382
-                        'validation' => true,
383
-                        'format' => '%s',
384
-                        'css_class' => 'large-text',
385
-                        'rows' => '5',
386
-                        'shortcodes_required' => array('[TAX_LINE_ITEM_LIST]'),
387
-                    ),
388
-                    'additional_line_item_list' => array(
389
-                        'input' => 'textarea',
390
-                        'label' => '[ADDITIONAL_LINE_ITEM_LIST]',
391
-                        'type' => 'string',
392
-                        'required' => false,
393
-                        'validation' => true,
394
-                        'format' => '%s',
395
-                        'css_class' => 'large-text',
396
-                        'rows' => '5',
397
-                        'shortcodes_required' => array('[ADDITIONAL_LINE_ITEM_LIST]'),
398
-                    ),
399
-                    'payment_list' => array(
400
-                        'input' => 'textarea',
401
-                        'label' => '[PAYMENT_LIST]',
402
-                        'type' => 'string',
403
-                        'required' => true,
404
-                        'validation' => true,
405
-                        'format' => '%s',
406
-                        'css_class' => 'large-text',
407
-                        'rows' => '5',
408
-                        'shortcodes_required' => array('[PAYMENT_LIST_*]'),
409
-                    ),
410
-                ),
411
-            ),
412
-        );
413
-    }
414
-
415
-
416
-    /**
417
-     * @see   definition of this method in parent
418
-     * @since 4.5.0
419
-     */
420
-    protected function _set_default_message_types()
421
-    {
422
-        $this->_default_message_types = array('receipt', 'invoice');
423
-    }
424
-
425
-
426
-    /**
427
-     * @see   definition of this method in parent
428
-     * @since 4.5.0
429
-     */
430
-    protected function _set_valid_message_types()
431
-    {
432
-        $this->_valid_message_types = array('receipt', 'invoice');
433
-    }
434
-
435
-
436
-    /**
437
-     * Displays the message in the browser.
438
-     *
439
-     * @since 4.5.0
440
-     * @return string.
441
-     */
442
-    protected function _send_message()
443
-    {
444
-        $this->_template_args = array(
445
-            'page_title' => $this->_subject,
446
-            'base_css' => $this->get_variation(
447
-                $this->_tmp_pack,
448
-                $this->_incoming_message_type->name,
449
-                true,
450
-                'base',
451
-                $this->_variation
452
-            ),
453
-            'print_css' => $this->get_variation(
454
-                $this->_tmp_pack,
455
-                $this->_incoming_message_type->name,
456
-                true,
457
-                'print',
458
-                $this->_variation
459
-            ),
460
-            'main_css' => $this->get_variation(
461
-                $this->_tmp_pack,
462
-                $this->_incoming_message_type->name,
463
-                true,
464
-                'main',
465
-                $this->_variation
466
-            ),
467
-            'main_body' => wpautop(
468
-                apply_filters(
469
-                    'FHEE__EE_Html_messenger___send_message__main_body',
470
-                    $this->_content,
471
-                    $this->_content,
472
-                    $this->_incoming_message_type
473
-                )
474
-            )
475
-        );
476
-        $this->_deregister_wp_hooks();
477
-        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts_styles'));
478
-
479
-        echo $this->_get_main_template();
480
-        exit();
481
-    }
482
-
483
-
484
-    /**
485
-     * The purpose of this function is to de register all actions hooked into wp_head and wp_footer so that it doesn't
486
-     * interfere with our templates.  If users want to add any custom styles or scripts they must use the
487
-     * AHEE__EE_Html_messenger__enqueue_scripts_styles hook.
488
-     *
489
-     * @since 4.5.0
490
-     * @return void
491
-     */
492
-    protected function _deregister_wp_hooks()
493
-    {
494
-        remove_all_actions('wp_head');
495
-        remove_all_actions('wp_footer');
496
-        remove_all_actions('wp_print_footer_scripts');
497
-        remove_all_actions('wp_enqueue_scripts');
498
-        global $wp_scripts, $wp_styles;
499
-        $wp_scripts = $wp_styles = array();
500
-        // just add back in wp_enqueue_scripts and wp_print_footer_scripts cause that's all we want to load.
501
-        add_action('wp_footer', 'wp_print_footer_scripts');
502
-        add_action('wp_print_footer_scripts', '_wp_footer_scripts');
503
-        add_action('wp_head', 'wp_enqueue_scripts');
504
-    }
505
-
506
-
507
-    /**
508
-     * Overwrite parent _get_main_template for display_html purposes.
509
-     *
510
-     * @since  4.5.0
511
-     * @param bool $preview
512
-     * @return string
513
-     */
514
-    protected function _get_main_template($preview = false)
515
-    {
516
-        $wrapper_template = $this->_tmp_pack->get_wrapper($this->name, 'main');
517
-        // include message type as a template arg
518
-        $this->_template_args['message_type'] = $this->_incoming_message_type;
519
-        return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
520
-    }
521
-
522
-
523
-    /**
524
-     * @return string
525
-     */
526
-    protected function _preview()
527
-    {
528
-        return $this->_send_message();
529
-    }
530
-
531
-
532
-    protected function _set_admin_settings_fields()
533
-    {
534
-    }
535
-
536
-
537
-    /**
538
-     * add the "powered by EE" credit link to the HTML receipt and invoice
539
-     *
540
-     * @param string $content
541
-     * @param string $content_again
542
-     * @param \EE_message_type $incoming_message_type
543
-     * @return string
544
-     */
545
-    public function add_powered_by_credit_link_to_receipt_and_invoice(
546
-        $content = '',
547
-        $content_again = '',
548
-        EE_message_type $incoming_message_type
549
-    ) {
550
-        if (
551
-            ($incoming_message_type->name === 'invoice' || $incoming_message_type->name === 'receipt')
552
-            && apply_filters('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', true)
553
-        ) {
554
-            $content .= \EEH_Template::powered_by_event_espresso(
555
-                'aln-cntr',
556
-                '',
557
-                array('utm_content' => 'messages_system')
558
-            )
559
-                . EEH_HTML::div(EEH_HTML::p('&nbsp;'));
560
-        }
561
-        return $content;
562
-    }
17
+	/**
18
+	 * The following are the properties that this messenger requires for displaying the html
19
+	 */
20
+	/**
21
+	 * This is the html body generated by the template via the message type.
22
+	 *
23
+	 * @var string
24
+	 */
25
+	protected $_content;
26
+
27
+
28
+	/**
29
+	 * This is for the page title that gets displayed.  (Why use "subject"?  Because the "title" tag in html is
30
+	 * equivalent to the "subject" of the page.
31
+	 *
32
+	 * @var string
33
+	 */
34
+	protected $_subject;
35
+
36
+
37
+	/**
38
+	 * EE_Html_messenger constructor.
39
+	 */
40
+	public function __construct()
41
+	{
42
+		// set properties
43
+		$this->name = 'html';
44
+		$this->description = esc_html__('This messenger outputs a message to a browser for display.', 'event_espresso');
45
+		$this->label = array(
46
+			'singular' => esc_html__('html', 'event_espresso'),
47
+			'plural' => esc_html__('html', 'event_espresso'),
48
+		);
49
+		$this->activate_on_install = true;
50
+		// add the "powered by EE" credit link to the HTML receipt and invoice
51
+		add_filter(
52
+			'FHEE__EE_Html_messenger___send_message__main_body',
53
+			array($this, 'add_powered_by_credit_link_to_receipt_and_invoice'),
54
+			10,
55
+			3
56
+		);
57
+		parent::__construct();
58
+	}
59
+
60
+
61
+	/**
62
+	 * HTML Messenger desires execution immediately.
63
+	 *
64
+	 * @see    parent::send_now() for documentation.
65
+	 * @since  4.9.0
66
+	 * @return bool
67
+	 */
68
+	public function send_now()
69
+	{
70
+		return true;
71
+	}
72
+
73
+
74
+	/**
75
+	 * HTML Messenger allows an empty to field.
76
+	 *
77
+	 * @see    parent::allow_empty_to_field() for documentation
78
+	 * @since  4.9.0
79
+	 * @return bool
80
+	 */
81
+	public function allow_empty_to_field()
82
+	{
83
+		return true;
84
+	}
85
+
86
+
87
+	/**
88
+	 * @see abstract declaration in EE_messenger for details.
89
+	 */
90
+	protected function _set_admin_pages()
91
+	{
92
+		$this->admin_registered_pages = array('events_edit' => true);
93
+	}
94
+
95
+
96
+	/**
97
+	 * @see abstract declaration in EE_messenger for details.
98
+	 */
99
+	protected function _set_valid_shortcodes()
100
+	{
101
+		$this->_valid_shortcodes = array();
102
+	}
103
+
104
+
105
+	/**
106
+	 * @see abstract declaration in EE_messenger for details.
107
+	 */
108
+	protected function _set_validator_config()
109
+	{
110
+		$this->_validator_config = array(
111
+			'subject' => array(
112
+				'shortcodes' => array('organization', 'primary_registration_details', 'email', 'transaction'),
113
+			),
114
+			'content' => array(
115
+				'shortcodes' => array(
116
+					'organization',
117
+					'primary_registration_list',
118
+					'primary_registration_details',
119
+					'email',
120
+					'transaction',
121
+					'event_list',
122
+					'payment_list',
123
+					'venue',
124
+					'line_item_list',
125
+					'messenger',
126
+					'ticket_list',
127
+				),
128
+			),
129
+			'event_list' => array(
130
+				'shortcodes' => array(
131
+					'event',
132
+					'ticket_list',
133
+					'venue',
134
+					'primary_registration_details',
135
+					'primary_registration_list',
136
+					'event_author',
137
+				),
138
+				'required' => array('[EVENT_LIST]'),
139
+			),
140
+			'ticket_list' => array(
141
+				'shortcodes' => array(
142
+					'attendee_list',
143
+					'ticket',
144
+					'datetime_list',
145
+					'primary_registration_details',
146
+					'line_item_list',
147
+					'venue',
148
+				),
149
+				'required' => array('[TICKET_LIST]'),
150
+			),
151
+			'ticket_line_item_no_pms' => array(
152
+				'shortcodes' => array('line_item', 'ticket'),
153
+				'required' => array('[TICKET_LINE_ITEM_LIST]'),
154
+			),
155
+			'ticket_line_item_pms' => array(
156
+				'shortcodes' => array('line_item', 'ticket', 'line_item_list'),
157
+				'required' => array('[TICKET_LINE_ITEM_LIST]'),
158
+			),
159
+			'price_modifier_line_item_list' => array(
160
+				'shortcodes' => array('line_item'),
161
+				'required' => array('[PRICE_MODIFIER_LINE_ITEM_LIST]'),
162
+			),
163
+			'datetime_list' => array(
164
+				'shortcodes' => array('datetime'),
165
+				'required' => array('[DATETIME_LIST]'),
166
+			),
167
+			'attendee_list' => array(
168
+				'shortcodes' => array('attendee'),
169
+				'required' => array('[ATTENDEE_LIST]'),
170
+			),
171
+			'tax_line_item_list' => array(
172
+				'shortcodes' => array('line_item'),
173
+				'required' => array('[TAX_LINE_ITEM_LIST]'),
174
+			),
175
+			'additional_line_item_list' => array(
176
+				'shortcodes' => array('line_item'),
177
+				'required' => array('[ADDITIONAL_LINE_ITEM_LIST]'),
178
+			),
179
+			'payment_list' => array(
180
+				'shortcodes' => array('payment'),
181
+				'required' => array('[PAYMENT_LIST_*]'),
182
+			),
183
+		);
184
+	}
185
+
186
+
187
+	/**
188
+	 * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger
189
+	 * is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary
190
+	 * (i.e. swap out css files or something else).
191
+	 *
192
+	 * @since 4.5.0
193
+	 * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
194
+	 * @return void
195
+	 */
196
+	public function do_secondary_messenger_hooks($sending_messenger_name)
197
+	{
198
+		if ($sending_messenger_name === 'pdf') {
199
+			add_filter('EE_messenger__get_variation__variation', array($this, 'add_html_css'), 10, 8);
200
+		}
201
+	}
202
+
203
+
204
+	/**
205
+	 * @param                            $variation_path
206
+	 * @param \EE_Messages_Template_Pack $template_pack
207
+	 * @param                            $messenger_name
208
+	 * @param                            $message_type_name
209
+	 * @param                            $url
210
+	 * @param                            $type
211
+	 * @param                            $variation
212
+	 * @param                            $skip_filters
213
+	 * @return string
214
+	 */
215
+	public function add_html_css(
216
+		$variation_path,
217
+		EE_Messages_Template_Pack $template_pack,
218
+		$messenger_name,
219
+		$message_type_name,
220
+		$url,
221
+		$type,
222
+		$variation,
223
+		$skip_filters
224
+	) {
225
+		$variation = $template_pack->get_variation(
226
+			$this->name,
227
+			$message_type_name,
228
+			$type,
229
+			$variation,
230
+			$url,
231
+			'.css',
232
+			$skip_filters
233
+		);
234
+		return $variation;
235
+	}
236
+
237
+
238
+	/**
239
+	 * Takes care of enqueuing any necessary scripts or styles for the page.  A do_action() so message types using this
240
+	 * messenger can add their own js.
241
+	 *
242
+	 * @return void.
243
+	 */
244
+	public function enqueue_scripts_styles()
245
+	{
246
+		parent::enqueue_scripts_styles();
247
+		do_action('AHEE__EE_Html_messenger__enqueue_scripts_styles');
248
+	}
249
+
250
+
251
+	/**
252
+	 * _set_template_fields
253
+	 * This sets up the fields that a messenger requires for the message to go out.
254
+	 *
255
+	 * @access  protected
256
+	 * @return void
257
+	 */
258
+	protected function _set_template_fields()
259
+	{
260
+		// any extra template fields that are NOT used by the messenger
261
+		// but will get used by a messenger field for shortcode replacement
262
+		// get added to the 'extra' key in an associated array
263
+		// indexed by the messenger field they relate to.
264
+		// This is important for the Messages_admin to know what fields to display to the user.
265
+		// Also, notice that the "values" are equal to the field type
266
+		// that messages admin will use to know what kind of field to display.
267
+		// The values ALSO have one index labeled "shortcode".
268
+		// The values in that array indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE])
269
+		// is required in order for this extra field to be displayed.
270
+		//  If the required shortcode isn't part of the shortcodes array
271
+		// then the field is not needed and will not be displayed/parsed.
272
+		$this->_template_fields = array(
273
+			'subject' => array(
274
+				'input' => 'text',
275
+				'label' => esc_html__('Page Title', 'event_espresso'),
276
+				'type' => 'string',
277
+				'required' => true,
278
+				'validation' => true,
279
+				'css_class' => 'large-text',
280
+				'format' => '%s',
281
+			),
282
+			'content' => '',
283
+			// left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
284
+			'extra' => array(
285
+				'content' => array(
286
+					'main' => array(
287
+						'input' => 'wp_editor',
288
+						'label' => esc_html__('Main Content', 'event_espresso'),
289
+						'type' => 'string',
290
+						'required' => true,
291
+						'validation' => true,
292
+						'format' => '%s',
293
+						'rows' => '15',
294
+					),
295
+					'event_list' => array(
296
+						'input' => 'wp_editor',
297
+						'label' => '[EVENT_LIST]',
298
+						'type' => 'string',
299
+						'required' => true,
300
+						'validation' => true,
301
+						'format' => '%s',
302
+						'rows' => '15',
303
+						'shortcodes_required' => array('[EVENT_LIST]'),
304
+					),
305
+					'ticket_list' => array(
306
+						'input' => 'textarea',
307
+						'label' => '[TICKET_LIST]',
308
+						'type' => 'string',
309
+						'required' => true,
310
+						'validation' => true,
311
+						'format' => '%s',
312
+						'css_class' => 'large-text',
313
+						'rows' => '10',
314
+						'shortcodes_required' => array('[TICKET_LIST]'),
315
+					),
316
+					'ticket_line_item_no_pms' => array(
317
+						'input' => 'textarea',
318
+						'label' => '[TICKET_LINE_ITEM_LIST] <br>' . esc_html__(
319
+							'Ticket Line Item List with no Price Modifiers',
320
+							'event_espresso'
321
+						),
322
+						'type' => 'string',
323
+						'required' => false,
324
+						'validation' => true,
325
+						'format' => '%s',
326
+						'css_class' => 'large-text',
327
+						'rows' => '5',
328
+						'shortcodes_required' => array('[TICKET_LINE_ITEM_LIST]'),
329
+					),
330
+					'ticket_line_item_pms' => array(
331
+						'input' => 'textarea',
332
+						'label' => '[TICKET_LINE_ITEM_LIST] <br>' . esc_html__(
333
+							'Ticket Line Item List with Price Modifiers',
334
+							'event_espresso'
335
+						),
336
+						'type' => 'string',
337
+						'required' => false,
338
+						'validation' => true,
339
+						'format' => '%s',
340
+						'css_class' => 'large-text',
341
+						'rows' => '5',
342
+						'shortcodes_required' => array('[TICKET_LINE_ITEM_LIST]'),
343
+					),
344
+					'price_modifier_line_item_list' => array(
345
+						'input' => 'textarea',
346
+						'label' => '[PRICE_MODIFIER_LINE_ITEM_LIST]',
347
+						'type' => 'string',
348
+						'required' => false,
349
+						'validation' => true,
350
+						'format' => '%s',
351
+						'css_class' => 'large-text',
352
+						'rows' => '5',
353
+						'shortcodes_required' => array('[PRICE_MODIFIER_LINE_ITEM_LIST]'),
354
+					),
355
+					'datetime_list' => array(
356
+						'input' => 'textarea',
357
+						'label' => '[DATETIME_LIST]',
358
+						'type' => 'string',
359
+						'required' => true,
360
+						'validation' => true,
361
+						'format' => '%s',
362
+						'css_class' => 'large-text',
363
+						'rows' => '5',
364
+						'shortcodes_required' => array('[DATETIME_LIST]'),
365
+					),
366
+					'attendee_list' => array(
367
+						'input' => 'textarea',
368
+						'label' => '[ATTENDEE_LIST]',
369
+						'type' => 'string',
370
+						'required' => true,
371
+						'validation' => true,
372
+						'format' => '%s',
373
+						'css_class' => 'large-text',
374
+						'rows' => '5',
375
+						'shortcodes_required' => array('[ATTENDEE_LIST]'),
376
+					),
377
+					'tax_line_item_list' => array(
378
+						'input' => 'textarea',
379
+						'label' => '[TAX_LINE_ITEM_LIST]',
380
+						'type' => 'string',
381
+						'required' => false,
382
+						'validation' => true,
383
+						'format' => '%s',
384
+						'css_class' => 'large-text',
385
+						'rows' => '5',
386
+						'shortcodes_required' => array('[TAX_LINE_ITEM_LIST]'),
387
+					),
388
+					'additional_line_item_list' => array(
389
+						'input' => 'textarea',
390
+						'label' => '[ADDITIONAL_LINE_ITEM_LIST]',
391
+						'type' => 'string',
392
+						'required' => false,
393
+						'validation' => true,
394
+						'format' => '%s',
395
+						'css_class' => 'large-text',
396
+						'rows' => '5',
397
+						'shortcodes_required' => array('[ADDITIONAL_LINE_ITEM_LIST]'),
398
+					),
399
+					'payment_list' => array(
400
+						'input' => 'textarea',
401
+						'label' => '[PAYMENT_LIST]',
402
+						'type' => 'string',
403
+						'required' => true,
404
+						'validation' => true,
405
+						'format' => '%s',
406
+						'css_class' => 'large-text',
407
+						'rows' => '5',
408
+						'shortcodes_required' => array('[PAYMENT_LIST_*]'),
409
+					),
410
+				),
411
+			),
412
+		);
413
+	}
414
+
415
+
416
+	/**
417
+	 * @see   definition of this method in parent
418
+	 * @since 4.5.0
419
+	 */
420
+	protected function _set_default_message_types()
421
+	{
422
+		$this->_default_message_types = array('receipt', 'invoice');
423
+	}
424
+
425
+
426
+	/**
427
+	 * @see   definition of this method in parent
428
+	 * @since 4.5.0
429
+	 */
430
+	protected function _set_valid_message_types()
431
+	{
432
+		$this->_valid_message_types = array('receipt', 'invoice');
433
+	}
434
+
435
+
436
+	/**
437
+	 * Displays the message in the browser.
438
+	 *
439
+	 * @since 4.5.0
440
+	 * @return string.
441
+	 */
442
+	protected function _send_message()
443
+	{
444
+		$this->_template_args = array(
445
+			'page_title' => $this->_subject,
446
+			'base_css' => $this->get_variation(
447
+				$this->_tmp_pack,
448
+				$this->_incoming_message_type->name,
449
+				true,
450
+				'base',
451
+				$this->_variation
452
+			),
453
+			'print_css' => $this->get_variation(
454
+				$this->_tmp_pack,
455
+				$this->_incoming_message_type->name,
456
+				true,
457
+				'print',
458
+				$this->_variation
459
+			),
460
+			'main_css' => $this->get_variation(
461
+				$this->_tmp_pack,
462
+				$this->_incoming_message_type->name,
463
+				true,
464
+				'main',
465
+				$this->_variation
466
+			),
467
+			'main_body' => wpautop(
468
+				apply_filters(
469
+					'FHEE__EE_Html_messenger___send_message__main_body',
470
+					$this->_content,
471
+					$this->_content,
472
+					$this->_incoming_message_type
473
+				)
474
+			)
475
+		);
476
+		$this->_deregister_wp_hooks();
477
+		add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts_styles'));
478
+
479
+		echo $this->_get_main_template();
480
+		exit();
481
+	}
482
+
483
+
484
+	/**
485
+	 * The purpose of this function is to de register all actions hooked into wp_head and wp_footer so that it doesn't
486
+	 * interfere with our templates.  If users want to add any custom styles or scripts they must use the
487
+	 * AHEE__EE_Html_messenger__enqueue_scripts_styles hook.
488
+	 *
489
+	 * @since 4.5.0
490
+	 * @return void
491
+	 */
492
+	protected function _deregister_wp_hooks()
493
+	{
494
+		remove_all_actions('wp_head');
495
+		remove_all_actions('wp_footer');
496
+		remove_all_actions('wp_print_footer_scripts');
497
+		remove_all_actions('wp_enqueue_scripts');
498
+		global $wp_scripts, $wp_styles;
499
+		$wp_scripts = $wp_styles = array();
500
+		// just add back in wp_enqueue_scripts and wp_print_footer_scripts cause that's all we want to load.
501
+		add_action('wp_footer', 'wp_print_footer_scripts');
502
+		add_action('wp_print_footer_scripts', '_wp_footer_scripts');
503
+		add_action('wp_head', 'wp_enqueue_scripts');
504
+	}
505
+
506
+
507
+	/**
508
+	 * Overwrite parent _get_main_template for display_html purposes.
509
+	 *
510
+	 * @since  4.5.0
511
+	 * @param bool $preview
512
+	 * @return string
513
+	 */
514
+	protected function _get_main_template($preview = false)
515
+	{
516
+		$wrapper_template = $this->_tmp_pack->get_wrapper($this->name, 'main');
517
+		// include message type as a template arg
518
+		$this->_template_args['message_type'] = $this->_incoming_message_type;
519
+		return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
520
+	}
521
+
522
+
523
+	/**
524
+	 * @return string
525
+	 */
526
+	protected function _preview()
527
+	{
528
+		return $this->_send_message();
529
+	}
530
+
531
+
532
+	protected function _set_admin_settings_fields()
533
+	{
534
+	}
535
+
536
+
537
+	/**
538
+	 * add the "powered by EE" credit link to the HTML receipt and invoice
539
+	 *
540
+	 * @param string $content
541
+	 * @param string $content_again
542
+	 * @param \EE_message_type $incoming_message_type
543
+	 * @return string
544
+	 */
545
+	public function add_powered_by_credit_link_to_receipt_and_invoice(
546
+		$content = '',
547
+		$content_again = '',
548
+		EE_message_type $incoming_message_type
549
+	) {
550
+		if (
551
+			($incoming_message_type->name === 'invoice' || $incoming_message_type->name === 'receipt')
552
+			&& apply_filters('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', true)
553
+		) {
554
+			$content .= \EEH_Template::powered_by_event_espresso(
555
+				'aln-cntr',
556
+				'',
557
+				array('utm_content' => 'messages_system')
558
+			)
559
+				. EEH_HTML::div(EEH_HTML::p('&nbsp;'));
560
+		}
561
+		return $content;
562
+	}
563 563
 }
Please login to merge, or discard this patch.
core/EE_Addon.core.php 1 patch
Indentation   +848 added lines, -848 removed lines patch added patch discarded remove patch
@@ -20,859 +20,859 @@
 block discarded – undo
20 20
 {
21 21
 
22 22
 
23
-    /**
24
-     * prefix to be added onto an addon's plugin slug to make a wp option name
25
-     * which will be used to store the plugin's activation history
26
-     */
27
-    const ee_addon_version_history_option_prefix = 'ee_version_history_';
28
-
29
-    /**
30
-     * @var $_version
31
-     * @type string
32
-     */
33
-    protected $_version = '';
34
-
35
-    /**
36
-     * @var $_min_core_version
37
-     * @type string
38
-     */
39
-    protected $_min_core_version = '';
40
-
41
-    /**
42
-     * derived from plugin 'main_file_path using plugin_basename()
43
-     *
44
-     * @type string $_plugin_basename
45
-     */
46
-    protected $_plugin_basename = '';
47
-
48
-    /**
49
-     * A non-internationalized name to identify this addon for use in URLs, etc
50
-     *
51
-     * @type string $_plugin_slug
52
-     */
53
-    protected $_plugin_slug = '';
54
-
55
-    /**
56
-     * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
57
-     *
58
-     * @type string _addon_name
59
-     */
60
-    protected $_addon_name = '';
61
-
62
-    /**
63
-     * one of the EE_System::req_type_* constants
64
-     *
65
-     * @type int $_req_type
66
-     */
67
-    protected $_req_type;
68
-
69
-    /**
70
-     * page slug to be used when generating the "Settings" link on the WP plugin page
71
-     *
72
-     * @type string $_plugin_action_slug
73
-     */
74
-    protected $_plugin_action_slug = '';
75
-
76
-    /**
77
-     * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
78
-     * that can be used for adding upgrading/marketing info
79
-     *
80
-     * @type array $_plugins_page_row
81
-     */
82
-    protected $_plugins_page_row = array();
83
-
84
-
85
-    /**
86
-     *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
87
-     *
88
-     * @type string
89
-     */
90
-    protected $_main_plugin_file;
91
-
92
-    /**
93
-     *    This is the slug used to identify this add-on within the plugin update engine.
94
-     *
95
-     * @type string
96
-     */
97
-    protected $pue_slug;
98
-
99
-
100
-    /**
101
-     * @var EE_Dependency_Map $dependency_map
102
-     */
103
-    private $dependency_map;
104
-
105
-
106
-    /**
107
-     * @var DomainInterface $domain
108
-     */
109
-    private $domain;
110
-
111
-
112
-    /**
113
-     * @param EE_Dependency_Map $dependency_map [optional]
114
-     * @param DomainInterface   $domain         [optional]
115
-     */
116
-    public function __construct(EE_Dependency_Map $dependency_map = null, DomainInterface $domain = null)
117
-    {
118
-        if ($dependency_map instanceof EE_Dependency_Map) {
119
-            $this->setDependencyMap($dependency_map);
120
-        }
121
-        if ($domain instanceof DomainInterface) {
122
-            $this->setDomain($domain);
123
-        }
124
-        add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
125
-    }
126
-
127
-
128
-    /**
129
-     * @param EE_Dependency_Map $dependency_map
130
-     */
131
-    public function setDependencyMap($dependency_map)
132
-    {
133
-        $this->dependency_map = $dependency_map;
134
-    }
135
-
136
-
137
-    /**
138
-     * @return EE_Dependency_Map
139
-     */
140
-    public function dependencyMap()
141
-    {
142
-        return $this->dependency_map;
143
-    }
144
-
145
-
146
-    /**
147
-     * @param DomainInterface $domain
148
-     */
149
-    public function setDomain(DomainInterface $domain)
150
-    {
151
-        $this->domain = $domain;
152
-    }
153
-
154
-    /**
155
-     * @return DomainInterface
156
-     */
157
-    public function domain()
158
-    {
159
-        return $this->domain;
160
-    }
161
-
162
-
163
-    /**
164
-     * @param mixed $version
165
-     */
166
-    public function set_version($version = null)
167
-    {
168
-        $this->_version = $version;
169
-    }
170
-
171
-
172
-    /**
173
-     * get__version
174
-     *
175
-     * @return string
176
-     */
177
-    public function version()
178
-    {
179
-        return $this->_version;
180
-    }
181
-
182
-
183
-    /**
184
-     * @param mixed $min_core_version
185
-     */
186
-    public function set_min_core_version($min_core_version = null)
187
-    {
188
-        $this->_min_core_version = $min_core_version;
189
-    }
190
-
191
-
192
-    /**
193
-     * get__min_core_version
194
-     *
195
-     * @return string
196
-     */
197
-    public function min_core_version()
198
-    {
199
-        return $this->_min_core_version;
200
-    }
201
-
202
-
203
-    /**
204
-     * Sets addon_name
205
-     *
206
-     * @param string $addon_name
207
-     * @return bool
208
-     */
209
-    public function set_name($addon_name)
210
-    {
211
-        return $this->_addon_name = $addon_name;
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets addon_name
217
-     *
218
-     * @return string
219
-     */
220
-    public function name()
221
-    {
222
-        return $this->_addon_name;
223
-    }
224
-
225
-
226
-    /**
227
-     * @return string
228
-     */
229
-    public function plugin_basename()
230
-    {
231
-
232
-        return $this->_plugin_basename;
233
-    }
234
-
235
-
236
-    /**
237
-     * @param string $plugin_basename
238
-     */
239
-    public function set_plugin_basename($plugin_basename)
240
-    {
241
-
242
-        $this->_plugin_basename = $plugin_basename;
243
-    }
244
-
245
-
246
-    /**
247
-     * @return string
248
-     */
249
-    public function plugin_slug()
250
-    {
251
-
252
-        return $this->_plugin_slug;
253
-    }
254
-
255
-
256
-    /**
257
-     * @param string $plugin_slug
258
-     */
259
-    public function set_plugin_slug($plugin_slug)
260
-    {
261
-
262
-        $this->_plugin_slug = $plugin_slug;
263
-    }
264
-
265
-
266
-    /**
267
-     * @return string
268
-     */
269
-    public function plugin_action_slug()
270
-    {
271
-
272
-        return $this->_plugin_action_slug;
273
-    }
274
-
275
-
276
-    /**
277
-     * @param string $plugin_action_slug
278
-     */
279
-    public function set_plugin_action_slug($plugin_action_slug)
280
-    {
281
-
282
-        $this->_plugin_action_slug = $plugin_action_slug;
283
-    }
284
-
285
-
286
-    /**
287
-     * @return array
288
-     */
289
-    public function get_plugins_page_row()
290
-    {
291
-
292
-        return $this->_plugins_page_row;
293
-    }
294
-
295
-
296
-    /**
297
-     * @param array $plugins_page_row
298
-     */
299
-    public function set_plugins_page_row($plugins_page_row = array())
300
-    {
301
-        // sigh.... check for example content that I stupidly merged to master and remove it if found
302
-        if (
303
-            ! is_array($plugins_page_row)
304
-            && strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
305
-        ) {
306
-            $plugins_page_row = array();
307
-        }
308
-        $this->_plugins_page_row = (array) $plugins_page_row;
309
-    }
310
-
311
-
312
-    /**
313
-     * Called when EE core detects this addon has been activated for the first time.
314
-     * If the site isn't in maintenance mode, should setup the addon's database
315
-     *
316
-     * @return void
317
-     * @throws EE_Error
318
-     */
319
-    public function new_install()
320
-    {
321
-        $classname = get_class($this);
322
-        do_action("AHEE__{$classname}__new_install");
323
-        do_action('AHEE__EE_Addon__new_install', $this);
324
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
325
-        add_action(
326
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
327
-            array($this, 'initialize_db_if_no_migrations_required')
328
-        );
329
-    }
330
-
331
-
332
-    /**
333
-     * Called when EE core detects this addon has been reactivated. When this happens,
334
-     * it's good to just check that your data is still intact
335
-     *
336
-     * @return void
337
-     * @throws EE_Error
338
-     */
339
-    public function reactivation()
340
-    {
341
-        $classname = get_class($this);
342
-        do_action("AHEE__{$classname}__reactivation");
343
-        do_action('AHEE__EE_Addon__reactivation', $this);
344
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
345
-        add_action(
346
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
347
-            array($this, 'initialize_db_if_no_migrations_required')
348
-        );
349
-    }
350
-
351
-
352
-    /**
353
-     * Called when the registered deactivation hook for this addon fires.
354
-     *
355
-     * @throws EE_Error
356
-     */
357
-    public function deactivation()
358
-    {
359
-        $classname = get_class($this);
360
-        do_action("AHEE__{$classname}__deactivation");
361
-        do_action('AHEE__EE_Addon__deactivation', $this);
362
-        // check if the site no longer needs to be in maintenance mode
363
-        EE_Register_Addon::deregister($this->name());
364
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
365
-    }
366
-
367
-
368
-    /**
369
-     * Takes care of double-checking that we're not in maintenance mode, and then
370
-     * initializing this addon's necessary initial data. This is called by default on new activations
371
-     * and reactivations.
372
-     *
373
-     * @param bool $verify_schema whether to verify the database's schema for this addon, or just its data.
374
-     *                               This is a resource-intensive job so we prefer to only do it when necessary
375
-     * @return void
376
-     * @throws EE_Error
377
-     * @throws InvalidInterfaceException
378
-     * @throws InvalidDataTypeException
379
-     * @throws InvalidArgumentException
380
-     * @throws ReflectionException
381
-     */
382
-    public function initialize_db_if_no_migrations_required($verify_schema = true)
383
-    {
384
-        if ($verify_schema === '') {
385
-            // wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
386
-            // (ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
387
-            // calls them with an argument of an empty string (ie ""), which evaluates to false
388
-            // so we need to treat the empty string as if nothing had been passed, and should instead use the default
389
-            $verify_schema = true;
390
-        }
391
-        if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
392
-            if ($verify_schema) {
393
-                $this->initialize_db();
394
-            }
395
-            $this->initialize_default_data();
396
-            // @todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
397
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to(
398
-                array(
399
-                    'slug'    => $this->name(),
400
-                    'version' => $this->version(),
401
-                )
402
-            );
403
-            /* make sure core's data is a-ok
23
+	/**
24
+	 * prefix to be added onto an addon's plugin slug to make a wp option name
25
+	 * which will be used to store the plugin's activation history
26
+	 */
27
+	const ee_addon_version_history_option_prefix = 'ee_version_history_';
28
+
29
+	/**
30
+	 * @var $_version
31
+	 * @type string
32
+	 */
33
+	protected $_version = '';
34
+
35
+	/**
36
+	 * @var $_min_core_version
37
+	 * @type string
38
+	 */
39
+	protected $_min_core_version = '';
40
+
41
+	/**
42
+	 * derived from plugin 'main_file_path using plugin_basename()
43
+	 *
44
+	 * @type string $_plugin_basename
45
+	 */
46
+	protected $_plugin_basename = '';
47
+
48
+	/**
49
+	 * A non-internationalized name to identify this addon for use in URLs, etc
50
+	 *
51
+	 * @type string $_plugin_slug
52
+	 */
53
+	protected $_plugin_slug = '';
54
+
55
+	/**
56
+	 * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
57
+	 *
58
+	 * @type string _addon_name
59
+	 */
60
+	protected $_addon_name = '';
61
+
62
+	/**
63
+	 * one of the EE_System::req_type_* constants
64
+	 *
65
+	 * @type int $_req_type
66
+	 */
67
+	protected $_req_type;
68
+
69
+	/**
70
+	 * page slug to be used when generating the "Settings" link on the WP plugin page
71
+	 *
72
+	 * @type string $_plugin_action_slug
73
+	 */
74
+	protected $_plugin_action_slug = '';
75
+
76
+	/**
77
+	 * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
78
+	 * that can be used for adding upgrading/marketing info
79
+	 *
80
+	 * @type array $_plugins_page_row
81
+	 */
82
+	protected $_plugins_page_row = array();
83
+
84
+
85
+	/**
86
+	 *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
87
+	 *
88
+	 * @type string
89
+	 */
90
+	protected $_main_plugin_file;
91
+
92
+	/**
93
+	 *    This is the slug used to identify this add-on within the plugin update engine.
94
+	 *
95
+	 * @type string
96
+	 */
97
+	protected $pue_slug;
98
+
99
+
100
+	/**
101
+	 * @var EE_Dependency_Map $dependency_map
102
+	 */
103
+	private $dependency_map;
104
+
105
+
106
+	/**
107
+	 * @var DomainInterface $domain
108
+	 */
109
+	private $domain;
110
+
111
+
112
+	/**
113
+	 * @param EE_Dependency_Map $dependency_map [optional]
114
+	 * @param DomainInterface   $domain         [optional]
115
+	 */
116
+	public function __construct(EE_Dependency_Map $dependency_map = null, DomainInterface $domain = null)
117
+	{
118
+		if ($dependency_map instanceof EE_Dependency_Map) {
119
+			$this->setDependencyMap($dependency_map);
120
+		}
121
+		if ($domain instanceof DomainInterface) {
122
+			$this->setDomain($domain);
123
+		}
124
+		add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
125
+	}
126
+
127
+
128
+	/**
129
+	 * @param EE_Dependency_Map $dependency_map
130
+	 */
131
+	public function setDependencyMap($dependency_map)
132
+	{
133
+		$this->dependency_map = $dependency_map;
134
+	}
135
+
136
+
137
+	/**
138
+	 * @return EE_Dependency_Map
139
+	 */
140
+	public function dependencyMap()
141
+	{
142
+		return $this->dependency_map;
143
+	}
144
+
145
+
146
+	/**
147
+	 * @param DomainInterface $domain
148
+	 */
149
+	public function setDomain(DomainInterface $domain)
150
+	{
151
+		$this->domain = $domain;
152
+	}
153
+
154
+	/**
155
+	 * @return DomainInterface
156
+	 */
157
+	public function domain()
158
+	{
159
+		return $this->domain;
160
+	}
161
+
162
+
163
+	/**
164
+	 * @param mixed $version
165
+	 */
166
+	public function set_version($version = null)
167
+	{
168
+		$this->_version = $version;
169
+	}
170
+
171
+
172
+	/**
173
+	 * get__version
174
+	 *
175
+	 * @return string
176
+	 */
177
+	public function version()
178
+	{
179
+		return $this->_version;
180
+	}
181
+
182
+
183
+	/**
184
+	 * @param mixed $min_core_version
185
+	 */
186
+	public function set_min_core_version($min_core_version = null)
187
+	{
188
+		$this->_min_core_version = $min_core_version;
189
+	}
190
+
191
+
192
+	/**
193
+	 * get__min_core_version
194
+	 *
195
+	 * @return string
196
+	 */
197
+	public function min_core_version()
198
+	{
199
+		return $this->_min_core_version;
200
+	}
201
+
202
+
203
+	/**
204
+	 * Sets addon_name
205
+	 *
206
+	 * @param string $addon_name
207
+	 * @return bool
208
+	 */
209
+	public function set_name($addon_name)
210
+	{
211
+		return $this->_addon_name = $addon_name;
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets addon_name
217
+	 *
218
+	 * @return string
219
+	 */
220
+	public function name()
221
+	{
222
+		return $this->_addon_name;
223
+	}
224
+
225
+
226
+	/**
227
+	 * @return string
228
+	 */
229
+	public function plugin_basename()
230
+	{
231
+
232
+		return $this->_plugin_basename;
233
+	}
234
+
235
+
236
+	/**
237
+	 * @param string $plugin_basename
238
+	 */
239
+	public function set_plugin_basename($plugin_basename)
240
+	{
241
+
242
+		$this->_plugin_basename = $plugin_basename;
243
+	}
244
+
245
+
246
+	/**
247
+	 * @return string
248
+	 */
249
+	public function plugin_slug()
250
+	{
251
+
252
+		return $this->_plugin_slug;
253
+	}
254
+
255
+
256
+	/**
257
+	 * @param string $plugin_slug
258
+	 */
259
+	public function set_plugin_slug($plugin_slug)
260
+	{
261
+
262
+		$this->_plugin_slug = $plugin_slug;
263
+	}
264
+
265
+
266
+	/**
267
+	 * @return string
268
+	 */
269
+	public function plugin_action_slug()
270
+	{
271
+
272
+		return $this->_plugin_action_slug;
273
+	}
274
+
275
+
276
+	/**
277
+	 * @param string $plugin_action_slug
278
+	 */
279
+	public function set_plugin_action_slug($plugin_action_slug)
280
+	{
281
+
282
+		$this->_plugin_action_slug = $plugin_action_slug;
283
+	}
284
+
285
+
286
+	/**
287
+	 * @return array
288
+	 */
289
+	public function get_plugins_page_row()
290
+	{
291
+
292
+		return $this->_plugins_page_row;
293
+	}
294
+
295
+
296
+	/**
297
+	 * @param array $plugins_page_row
298
+	 */
299
+	public function set_plugins_page_row($plugins_page_row = array())
300
+	{
301
+		// sigh.... check for example content that I stupidly merged to master and remove it if found
302
+		if (
303
+			! is_array($plugins_page_row)
304
+			&& strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
305
+		) {
306
+			$plugins_page_row = array();
307
+		}
308
+		$this->_plugins_page_row = (array) $plugins_page_row;
309
+	}
310
+
311
+
312
+	/**
313
+	 * Called when EE core detects this addon has been activated for the first time.
314
+	 * If the site isn't in maintenance mode, should setup the addon's database
315
+	 *
316
+	 * @return void
317
+	 * @throws EE_Error
318
+	 */
319
+	public function new_install()
320
+	{
321
+		$classname = get_class($this);
322
+		do_action("AHEE__{$classname}__new_install");
323
+		do_action('AHEE__EE_Addon__new_install', $this);
324
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
325
+		add_action(
326
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
327
+			array($this, 'initialize_db_if_no_migrations_required')
328
+		);
329
+	}
330
+
331
+
332
+	/**
333
+	 * Called when EE core detects this addon has been reactivated. When this happens,
334
+	 * it's good to just check that your data is still intact
335
+	 *
336
+	 * @return void
337
+	 * @throws EE_Error
338
+	 */
339
+	public function reactivation()
340
+	{
341
+		$classname = get_class($this);
342
+		do_action("AHEE__{$classname}__reactivation");
343
+		do_action('AHEE__EE_Addon__reactivation', $this);
344
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
345
+		add_action(
346
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
347
+			array($this, 'initialize_db_if_no_migrations_required')
348
+		);
349
+	}
350
+
351
+
352
+	/**
353
+	 * Called when the registered deactivation hook for this addon fires.
354
+	 *
355
+	 * @throws EE_Error
356
+	 */
357
+	public function deactivation()
358
+	{
359
+		$classname = get_class($this);
360
+		do_action("AHEE__{$classname}__deactivation");
361
+		do_action('AHEE__EE_Addon__deactivation', $this);
362
+		// check if the site no longer needs to be in maintenance mode
363
+		EE_Register_Addon::deregister($this->name());
364
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
365
+	}
366
+
367
+
368
+	/**
369
+	 * Takes care of double-checking that we're not in maintenance mode, and then
370
+	 * initializing this addon's necessary initial data. This is called by default on new activations
371
+	 * and reactivations.
372
+	 *
373
+	 * @param bool $verify_schema whether to verify the database's schema for this addon, or just its data.
374
+	 *                               This is a resource-intensive job so we prefer to only do it when necessary
375
+	 * @return void
376
+	 * @throws EE_Error
377
+	 * @throws InvalidInterfaceException
378
+	 * @throws InvalidDataTypeException
379
+	 * @throws InvalidArgumentException
380
+	 * @throws ReflectionException
381
+	 */
382
+	public function initialize_db_if_no_migrations_required($verify_schema = true)
383
+	{
384
+		if ($verify_schema === '') {
385
+			// wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
386
+			// (ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
387
+			// calls them with an argument of an empty string (ie ""), which evaluates to false
388
+			// so we need to treat the empty string as if nothing had been passed, and should instead use the default
389
+			$verify_schema = true;
390
+		}
391
+		if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
392
+			if ($verify_schema) {
393
+				$this->initialize_db();
394
+			}
395
+			$this->initialize_default_data();
396
+			// @todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
397
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to(
398
+				array(
399
+					'slug'    => $this->name(),
400
+					'version' => $this->version(),
401
+				)
402
+			);
403
+			/* make sure core's data is a-ok
404 404
              * (at the time of writing, we especially want to verify all the caps are present
405 405
              * because payment method type capabilities are added dynamically, and it's
406 406
              * possible this addon added a payment method. But it's also possible
407 407
              * other data needs to be verified)
408 408
              */
409
-            EEH_Activation::initialize_db_content();
410
-            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
411
-            $rewrite_rules = LoaderFactory::getLoader()->getShared(
412
-                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
413
-            );
414
-            $rewrite_rules->flushRewriteRules();
415
-            // in case there are lots of addons being activated at once, let's force garbage collection
416
-            // to help avoid memory limit errors
417
-            // EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
418
-            gc_collect_cycles();
419
-        } else {
420
-            // ask the data migration manager to init this addon's data
421
-            // when migrations are finished because we can't do it now
422
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
423
-        }
424
-    }
425
-
426
-
427
-    /**
428
-     * Used to setup this addon's database tables, but not necessarily any default
429
-     * data in them. The default is to actually use the most up-to-date data migration script
430
-     * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
431
-     * methods to setup the db.
432
-     */
433
-    public function initialize_db()
434
-    {
435
-        // find the migration script that sets the database to be compatible with the code
436
-        $current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
437
-        if ($current_dms_name) {
438
-            $current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
439
-            $current_data_migration_script->set_migrating(false);
440
-            $current_data_migration_script->schema_changes_before_migration();
441
-            $current_data_migration_script->schema_changes_after_migration();
442
-            if ($current_data_migration_script->get_errors()) {
443
-                foreach ($current_data_migration_script->get_errors() as $error) {
444
-                    EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
445
-                }
446
-            }
447
-        }
448
-        // if not DMS was found that should be ok. This addon just doesn't require any database changes
449
-        EE_Data_Migration_Manager::instance()->update_current_database_state_to(
450
-            array(
451
-                'slug'    => $this->name(),
452
-                'version' => $this->version(),
453
-            )
454
-        );
455
-    }
456
-
457
-
458
-    /**
459
-     * If you want to setup default data for the addon, override this method, and call
460
-     * parent::initialize_default_data() from within it. This is normally called
461
-     * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
462
-     * and should verify default data is present (but this is also called
463
-     * on reactivations and just after migrations, so please verify you actually want
464
-     * to ADD default data, because it may already be present).
465
-     * However, please call this parent (currently it just fires a hook which other
466
-     * addons may be depending on)
467
-     */
468
-    public function initialize_default_data()
469
-    {
470
-        /**
471
-         * Called when an addon is ensuring its default data is set (possibly called
472
-         * on a reactivation, so first check for the absence of other data before setting
473
-         * default data)
474
-         *
475
-         * @param EE_Addon $addon the addon that called this
476
-         */
477
-        do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
478
-        // override to insert default data. It is safe to use the models here
479
-        // because the site should not be in maintenance mode
480
-    }
481
-
482
-
483
-    /**
484
-     * EE Core detected that this addon has been upgraded. We should check if there
485
-     * are any new migration scripts, and if so put the site into maintenance mode until
486
-     * they're ran
487
-     *
488
-     * @return void
489
-     * @throws EE_Error
490
-     */
491
-    public function upgrade()
492
-    {
493
-        $classname = get_class($this);
494
-        do_action("AHEE__{$classname}__upgrade");
495
-        do_action('AHEE__EE_Addon__upgrade', $this);
496
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
497
-        // also it's possible there is new default data that needs to be added
498
-        add_action(
499
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
500
-            array($this, 'initialize_db_if_no_migrations_required')
501
-        );
502
-    }
503
-
504
-
505
-    /**
506
-     * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
507
-     */
508
-    public function downgrade()
509
-    {
510
-        $classname = get_class($this);
511
-        do_action("AHEE__{$classname}__downgrade");
512
-        do_action('AHEE__EE_Addon__downgrade', $this);
513
-        // it's possible there's old default data that needs to be double-checked
514
-        add_action(
515
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
516
-            array($this, 'initialize_db_if_no_migrations_required')
517
-        );
518
-    }
519
-
520
-
521
-    /**
522
-     * set_db_update_option_name
523
-     * Until we do something better, we'll just check for migration scripts upon
524
-     * plugin activation only. In the future, we'll want to do it on plugin updates too
525
-     *
526
-     * @return bool
527
-     */
528
-    public function set_db_update_option_name()
529
-    {
530
-        EE_Error::doing_it_wrong(
531
-            __FUNCTION__,
532
-            esc_html__(
533
-                'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
534
-                'event_espresso'
535
-            ),
536
-            '4.3.0.alpha.016'
537
-        );
538
-        // let's just handle this on the next request, ok? right now we're just not really ready
539
-        return $this->set_activation_indicator_option();
540
-    }
541
-
542
-
543
-    /**
544
-     * Returns the name of the activation indicator option
545
-     * (an option which is set temporarily to indicate that this addon was just activated)
546
-     *
547
-     * @deprecated since version 4.3.0.alpha.016
548
-     * @return string
549
-     */
550
-    public function get_db_update_option_name()
551
-    {
552
-        EE_Error::doing_it_wrong(
553
-            __FUNCTION__,
554
-            esc_html__(
555
-                'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
556
-                'event_espresso'
557
-            ),
558
-            '4.3.0.alpha.016'
559
-        );
560
-        return $this->get_activation_indicator_option_name();
561
-    }
562
-
563
-
564
-    /**
565
-     * When the addon is activated, this should be called to set a wordpress option that
566
-     * indicates it was activated. This is especially useful for detecting reactivations.
567
-     *
568
-     * @return bool
569
-     */
570
-    public function set_activation_indicator_option()
571
-    {
572
-        // let's just handle this on the next request, ok? right now we're just not really ready
573
-        return update_option($this->get_activation_indicator_option_name(), true);
574
-    }
575
-
576
-
577
-    /**
578
-     * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
579
-     *
580
-     * @return string
581
-     */
582
-    public function get_activation_indicator_option_name()
583
-    {
584
-        return 'ee_activation_' . $this->name();
585
-    }
586
-
587
-
588
-    /**
589
-     * Used by EE_System to set the request type of this addon. Should not be used by addon developers
590
-     *
591
-     * @param int $req_type
592
-     */
593
-    public function set_req_type($req_type)
594
-    {
595
-        $this->_req_type = $req_type;
596
-    }
597
-
598
-
599
-    /**
600
-     * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
601
-     * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
602
-     * EE_System when it is checking for new install or upgrades of addons
603
-     */
604
-    public function detect_req_type($redetect = false)
605
-    {
606
-        if ($this->_req_type === null || $redetect) {
607
-            $this->detect_activation_or_upgrade();
608
-        }
609
-        return $this->_req_type;
610
-    }
611
-
612
-
613
-    /**
614
-     * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
615
-     * Should only be called once per request
616
-     *
617
-     * @return void
618
-     * @throws EE_Error
619
-     */
620
-    public function detect_activation_or_upgrade()
621
-    {
622
-        $activation_history_for_addon = $this->get_activation_history();
623
-        $request_type = EE_System::detect_req_type_given_activation_history(
624
-            $activation_history_for_addon,
625
-            $this->get_activation_indicator_option_name(),
626
-            $this->version()
627
-        );
628
-        $this->set_req_type($request_type);
629
-        $classname = get_class($this);
630
-        switch ($request_type) {
631
-            case EE_System::req_type_new_activation:
632
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
633
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
634
-                $this->new_install();
635
-                $this->update_list_of_installed_versions($activation_history_for_addon);
636
-                break;
637
-            case EE_System::req_type_reactivation:
638
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
639
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
640
-                $this->reactivation();
641
-                $this->update_list_of_installed_versions($activation_history_for_addon);
642
-                break;
643
-            case EE_System::req_type_upgrade:
644
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
645
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
646
-                $this->upgrade();
647
-                $this->update_list_of_installed_versions($activation_history_for_addon);
648
-                break;
649
-            case EE_System::req_type_downgrade:
650
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
651
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
652
-                $this->downgrade();
653
-                $this->update_list_of_installed_versions($activation_history_for_addon);
654
-                break;
655
-            case EE_System::req_type_normal:
656
-            default:
657
-                break;
658
-        }
659
-
660
-        do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
661
-    }
662
-
663
-    /**
664
-     * Updates the version history for this addon
665
-     *
666
-     * @param array  $version_history
667
-     * @param string $current_version_to_add
668
-     * @return bool success
669
-     */
670
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
671
-    {
672
-        if (! $version_history) {
673
-            $version_history = $this->get_activation_history();
674
-        }
675
-        if ($current_version_to_add === null) {
676
-            $current_version_to_add = $this->version();
677
-        }
678
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
679
-        // resave
680
-        return update_option($this->get_activation_history_option_name(), $version_history);
681
-    }
682
-
683
-    /**
684
-     * Gets the name of the wp option that stores the activation history
685
-     * of this addon
686
-     *
687
-     * @return string
688
-     */
689
-    public function get_activation_history_option_name()
690
-    {
691
-        return self::ee_addon_version_history_option_prefix . $this->name();
692
-    }
693
-
694
-
695
-    /**
696
-     * Gets the wp option which stores the activation history for this addon
697
-     *
698
-     * @return array
699
-     */
700
-    public function get_activation_history()
701
-    {
702
-        return get_option($this->get_activation_history_option_name(), null);
703
-    }
704
-
705
-
706
-    /**
707
-     * @param string $config_section
708
-     */
709
-    public function set_config_section($config_section = '')
710
-    {
711
-        $this->_config_section = ! empty($config_section) ? $config_section : 'addons';
712
-    }
713
-
714
-    /**
715
-     * Sets the filepath to the main plugin file
716
-     *
717
-     * @param string $filepath
718
-     */
719
-    public function set_main_plugin_file($filepath)
720
-    {
721
-        $this->_main_plugin_file = $filepath;
722
-    }
723
-
724
-    /**
725
-     * gets the filepath to teh main file
726
-     *
727
-     * @return string
728
-     */
729
-    public function get_main_plugin_file()
730
-    {
731
-        return $this->_main_plugin_file;
732
-    }
733
-
734
-    /**
735
-     * Gets the filename (no path) of the main file (the main file loaded
736
-     * by WP)
737
-     *
738
-     * @return string
739
-     */
740
-    public function get_main_plugin_file_basename()
741
-    {
742
-        return plugin_basename($this->get_main_plugin_file());
743
-    }
744
-
745
-    /**
746
-     * Gets the folder name which contains the main plugin file
747
-     *
748
-     * @return string
749
-     */
750
-    public function get_main_plugin_file_dirname()
751
-    {
752
-        return dirname($this->get_main_plugin_file());
753
-    }
754
-
755
-
756
-    /**
757
-     * sets hooks used in the admin
758
-     *
759
-     * @return void
760
-     */
761
-    public function admin_init()
762
-    {
763
-        // is admin and not in M-Mode ?
764
-        if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
765
-            add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
766
-            add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
767
-        }
768
-    }
769
-
770
-
771
-    /**
772
-     * plugin_actions
773
-     * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
774
-     *
775
-     * @param $links
776
-     * @param $file
777
-     * @return array
778
-     */
779
-    public function plugin_action_links($links, $file)
780
-    {
781
-        if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
782
-            // before other links
783
-            array_unshift(
784
-                $links,
785
-                '<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
786
-                . esc_html__('Settings', 'event_espresso')
787
-                . '</a>'
788
-            );
789
-        }
790
-        return $links;
791
-    }
792
-
793
-
794
-    /**
795
-     * after_plugin_row
796
-     * Add additional content to the plugins page plugin row
797
-     * Inserts another row
798
-     *
799
-     * @param $plugin_file
800
-     * @param $plugin_data
801
-     * @param $status
802
-     * @return void
803
-     */
804
-    public function after_plugin_row($plugin_file, $plugin_data, $status)
805
-    {
806
-        $after_plugin_row = '';
807
-        $plugins_page_row = $this->get_plugins_page_row();
808
-        if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
809
-            $class = $status ? 'active' : 'inactive';
810
-            $link_text = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
811
-            $link_url = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
812
-            $description = isset($plugins_page_row['description'])
813
-                ? $plugins_page_row['description']
814
-                : '';
815
-            if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
816
-                $after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
817
-                $after_plugin_row .= '<th class="check-column" scope="row"></th>';
818
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
819
-                $after_plugin_row .= '<p class="ee-addon-upsell-info-dv">
409
+			EEH_Activation::initialize_db_content();
410
+			/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
411
+			$rewrite_rules = LoaderFactory::getLoader()->getShared(
412
+				'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
413
+			);
414
+			$rewrite_rules->flushRewriteRules();
415
+			// in case there are lots of addons being activated at once, let's force garbage collection
416
+			// to help avoid memory limit errors
417
+			// EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
418
+			gc_collect_cycles();
419
+		} else {
420
+			// ask the data migration manager to init this addon's data
421
+			// when migrations are finished because we can't do it now
422
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
423
+		}
424
+	}
425
+
426
+
427
+	/**
428
+	 * Used to setup this addon's database tables, but not necessarily any default
429
+	 * data in them. The default is to actually use the most up-to-date data migration script
430
+	 * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
431
+	 * methods to setup the db.
432
+	 */
433
+	public function initialize_db()
434
+	{
435
+		// find the migration script that sets the database to be compatible with the code
436
+		$current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
437
+		if ($current_dms_name) {
438
+			$current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
439
+			$current_data_migration_script->set_migrating(false);
440
+			$current_data_migration_script->schema_changes_before_migration();
441
+			$current_data_migration_script->schema_changes_after_migration();
442
+			if ($current_data_migration_script->get_errors()) {
443
+				foreach ($current_data_migration_script->get_errors() as $error) {
444
+					EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
445
+				}
446
+			}
447
+		}
448
+		// if not DMS was found that should be ok. This addon just doesn't require any database changes
449
+		EE_Data_Migration_Manager::instance()->update_current_database_state_to(
450
+			array(
451
+				'slug'    => $this->name(),
452
+				'version' => $this->version(),
453
+			)
454
+		);
455
+	}
456
+
457
+
458
+	/**
459
+	 * If you want to setup default data for the addon, override this method, and call
460
+	 * parent::initialize_default_data() from within it. This is normally called
461
+	 * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
462
+	 * and should verify default data is present (but this is also called
463
+	 * on reactivations and just after migrations, so please verify you actually want
464
+	 * to ADD default data, because it may already be present).
465
+	 * However, please call this parent (currently it just fires a hook which other
466
+	 * addons may be depending on)
467
+	 */
468
+	public function initialize_default_data()
469
+	{
470
+		/**
471
+		 * Called when an addon is ensuring its default data is set (possibly called
472
+		 * on a reactivation, so first check for the absence of other data before setting
473
+		 * default data)
474
+		 *
475
+		 * @param EE_Addon $addon the addon that called this
476
+		 */
477
+		do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
478
+		// override to insert default data. It is safe to use the models here
479
+		// because the site should not be in maintenance mode
480
+	}
481
+
482
+
483
+	/**
484
+	 * EE Core detected that this addon has been upgraded. We should check if there
485
+	 * are any new migration scripts, and if so put the site into maintenance mode until
486
+	 * they're ran
487
+	 *
488
+	 * @return void
489
+	 * @throws EE_Error
490
+	 */
491
+	public function upgrade()
492
+	{
493
+		$classname = get_class($this);
494
+		do_action("AHEE__{$classname}__upgrade");
495
+		do_action('AHEE__EE_Addon__upgrade', $this);
496
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
497
+		// also it's possible there is new default data that needs to be added
498
+		add_action(
499
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
500
+			array($this, 'initialize_db_if_no_migrations_required')
501
+		);
502
+	}
503
+
504
+
505
+	/**
506
+	 * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
507
+	 */
508
+	public function downgrade()
509
+	{
510
+		$classname = get_class($this);
511
+		do_action("AHEE__{$classname}__downgrade");
512
+		do_action('AHEE__EE_Addon__downgrade', $this);
513
+		// it's possible there's old default data that needs to be double-checked
514
+		add_action(
515
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
516
+			array($this, 'initialize_db_if_no_migrations_required')
517
+		);
518
+	}
519
+
520
+
521
+	/**
522
+	 * set_db_update_option_name
523
+	 * Until we do something better, we'll just check for migration scripts upon
524
+	 * plugin activation only. In the future, we'll want to do it on plugin updates too
525
+	 *
526
+	 * @return bool
527
+	 */
528
+	public function set_db_update_option_name()
529
+	{
530
+		EE_Error::doing_it_wrong(
531
+			__FUNCTION__,
532
+			esc_html__(
533
+				'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
534
+				'event_espresso'
535
+			),
536
+			'4.3.0.alpha.016'
537
+		);
538
+		// let's just handle this on the next request, ok? right now we're just not really ready
539
+		return $this->set_activation_indicator_option();
540
+	}
541
+
542
+
543
+	/**
544
+	 * Returns the name of the activation indicator option
545
+	 * (an option which is set temporarily to indicate that this addon was just activated)
546
+	 *
547
+	 * @deprecated since version 4.3.0.alpha.016
548
+	 * @return string
549
+	 */
550
+	public function get_db_update_option_name()
551
+	{
552
+		EE_Error::doing_it_wrong(
553
+			__FUNCTION__,
554
+			esc_html__(
555
+				'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
556
+				'event_espresso'
557
+			),
558
+			'4.3.0.alpha.016'
559
+		);
560
+		return $this->get_activation_indicator_option_name();
561
+	}
562
+
563
+
564
+	/**
565
+	 * When the addon is activated, this should be called to set a wordpress option that
566
+	 * indicates it was activated. This is especially useful for detecting reactivations.
567
+	 *
568
+	 * @return bool
569
+	 */
570
+	public function set_activation_indicator_option()
571
+	{
572
+		// let's just handle this on the next request, ok? right now we're just not really ready
573
+		return update_option($this->get_activation_indicator_option_name(), true);
574
+	}
575
+
576
+
577
+	/**
578
+	 * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
579
+	 *
580
+	 * @return string
581
+	 */
582
+	public function get_activation_indicator_option_name()
583
+	{
584
+		return 'ee_activation_' . $this->name();
585
+	}
586
+
587
+
588
+	/**
589
+	 * Used by EE_System to set the request type of this addon. Should not be used by addon developers
590
+	 *
591
+	 * @param int $req_type
592
+	 */
593
+	public function set_req_type($req_type)
594
+	{
595
+		$this->_req_type = $req_type;
596
+	}
597
+
598
+
599
+	/**
600
+	 * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
601
+	 * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
602
+	 * EE_System when it is checking for new install or upgrades of addons
603
+	 */
604
+	public function detect_req_type($redetect = false)
605
+	{
606
+		if ($this->_req_type === null || $redetect) {
607
+			$this->detect_activation_or_upgrade();
608
+		}
609
+		return $this->_req_type;
610
+	}
611
+
612
+
613
+	/**
614
+	 * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
615
+	 * Should only be called once per request
616
+	 *
617
+	 * @return void
618
+	 * @throws EE_Error
619
+	 */
620
+	public function detect_activation_or_upgrade()
621
+	{
622
+		$activation_history_for_addon = $this->get_activation_history();
623
+		$request_type = EE_System::detect_req_type_given_activation_history(
624
+			$activation_history_for_addon,
625
+			$this->get_activation_indicator_option_name(),
626
+			$this->version()
627
+		);
628
+		$this->set_req_type($request_type);
629
+		$classname = get_class($this);
630
+		switch ($request_type) {
631
+			case EE_System::req_type_new_activation:
632
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
633
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
634
+				$this->new_install();
635
+				$this->update_list_of_installed_versions($activation_history_for_addon);
636
+				break;
637
+			case EE_System::req_type_reactivation:
638
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
639
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
640
+				$this->reactivation();
641
+				$this->update_list_of_installed_versions($activation_history_for_addon);
642
+				break;
643
+			case EE_System::req_type_upgrade:
644
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
645
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
646
+				$this->upgrade();
647
+				$this->update_list_of_installed_versions($activation_history_for_addon);
648
+				break;
649
+			case EE_System::req_type_downgrade:
650
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
651
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
652
+				$this->downgrade();
653
+				$this->update_list_of_installed_versions($activation_history_for_addon);
654
+				break;
655
+			case EE_System::req_type_normal:
656
+			default:
657
+				break;
658
+		}
659
+
660
+		do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
661
+	}
662
+
663
+	/**
664
+	 * Updates the version history for this addon
665
+	 *
666
+	 * @param array  $version_history
667
+	 * @param string $current_version_to_add
668
+	 * @return bool success
669
+	 */
670
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
671
+	{
672
+		if (! $version_history) {
673
+			$version_history = $this->get_activation_history();
674
+		}
675
+		if ($current_version_to_add === null) {
676
+			$current_version_to_add = $this->version();
677
+		}
678
+		$version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
679
+		// resave
680
+		return update_option($this->get_activation_history_option_name(), $version_history);
681
+	}
682
+
683
+	/**
684
+	 * Gets the name of the wp option that stores the activation history
685
+	 * of this addon
686
+	 *
687
+	 * @return string
688
+	 */
689
+	public function get_activation_history_option_name()
690
+	{
691
+		return self::ee_addon_version_history_option_prefix . $this->name();
692
+	}
693
+
694
+
695
+	/**
696
+	 * Gets the wp option which stores the activation history for this addon
697
+	 *
698
+	 * @return array
699
+	 */
700
+	public function get_activation_history()
701
+	{
702
+		return get_option($this->get_activation_history_option_name(), null);
703
+	}
704
+
705
+
706
+	/**
707
+	 * @param string $config_section
708
+	 */
709
+	public function set_config_section($config_section = '')
710
+	{
711
+		$this->_config_section = ! empty($config_section) ? $config_section : 'addons';
712
+	}
713
+
714
+	/**
715
+	 * Sets the filepath to the main plugin file
716
+	 *
717
+	 * @param string $filepath
718
+	 */
719
+	public function set_main_plugin_file($filepath)
720
+	{
721
+		$this->_main_plugin_file = $filepath;
722
+	}
723
+
724
+	/**
725
+	 * gets the filepath to teh main file
726
+	 *
727
+	 * @return string
728
+	 */
729
+	public function get_main_plugin_file()
730
+	{
731
+		return $this->_main_plugin_file;
732
+	}
733
+
734
+	/**
735
+	 * Gets the filename (no path) of the main file (the main file loaded
736
+	 * by WP)
737
+	 *
738
+	 * @return string
739
+	 */
740
+	public function get_main_plugin_file_basename()
741
+	{
742
+		return plugin_basename($this->get_main_plugin_file());
743
+	}
744
+
745
+	/**
746
+	 * Gets the folder name which contains the main plugin file
747
+	 *
748
+	 * @return string
749
+	 */
750
+	public function get_main_plugin_file_dirname()
751
+	{
752
+		return dirname($this->get_main_plugin_file());
753
+	}
754
+
755
+
756
+	/**
757
+	 * sets hooks used in the admin
758
+	 *
759
+	 * @return void
760
+	 */
761
+	public function admin_init()
762
+	{
763
+		// is admin and not in M-Mode ?
764
+		if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
765
+			add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
766
+			add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
767
+		}
768
+	}
769
+
770
+
771
+	/**
772
+	 * plugin_actions
773
+	 * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
774
+	 *
775
+	 * @param $links
776
+	 * @param $file
777
+	 * @return array
778
+	 */
779
+	public function plugin_action_links($links, $file)
780
+	{
781
+		if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
782
+			// before other links
783
+			array_unshift(
784
+				$links,
785
+				'<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
786
+				. esc_html__('Settings', 'event_espresso')
787
+				. '</a>'
788
+			);
789
+		}
790
+		return $links;
791
+	}
792
+
793
+
794
+	/**
795
+	 * after_plugin_row
796
+	 * Add additional content to the plugins page plugin row
797
+	 * Inserts another row
798
+	 *
799
+	 * @param $plugin_file
800
+	 * @param $plugin_data
801
+	 * @param $status
802
+	 * @return void
803
+	 */
804
+	public function after_plugin_row($plugin_file, $plugin_data, $status)
805
+	{
806
+		$after_plugin_row = '';
807
+		$plugins_page_row = $this->get_plugins_page_row();
808
+		if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
809
+			$class = $status ? 'active' : 'inactive';
810
+			$link_text = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
811
+			$link_url = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
812
+			$description = isset($plugins_page_row['description'])
813
+				? $plugins_page_row['description']
814
+				: '';
815
+			if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
816
+				$after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
817
+				$after_plugin_row .= '<th class="check-column" scope="row"></th>';
818
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
819
+				$after_plugin_row .= '<p class="ee-addon-upsell-info-dv">
820 820
 	                <a class="ee-button" href="' . esc_url_raw($link_url) . '">'
821
-                    . $link_text
822
-                    . ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
823
-                    . '</a>
821
+					. $link_text
822
+					. ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
823
+					. '</a>
824 824
                 </p>';
825
-                $after_plugin_row .= '</td>';
826
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
827
-                $after_plugin_row .= $description;
828
-                $after_plugin_row .= '</td>';
829
-                $after_plugin_row .= '</tr>';
830
-            } else {
831
-                $after_plugin_row .= $description;
832
-            }
833
-        }
834
-
835
-        echo wp_kses($after_plugin_row, AllowedTags::getAllowedTags());
836
-    }
837
-
838
-
839
-    /**
840
-     * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
841
-     * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
842
-     * for back compat reasons.
843
-     *
844
-     * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
845
-     *
846
-     * It is recommended, if client code is `de-registering` an add-on, then do it on the
847
-     * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
848
-     * callback does not get run/set in that request.
849
-     *
850
-     * Also, keep in mind that if a registered add-on happens to be deactivated via
851
-     * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
852
-     * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
853
-     * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
854
-     * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
855
-     * to call `parent::deactivation`.
856
-     *
857
-     * @since 4.9.26
858
-     */
859
-    public function after_registration()
860
-    {
861
-        // cricket chirp... cricket chirp...
862
-    }
863
-
864
-    /**
865
-     * @return string
866
-     */
867
-    public function getPueSlug()
868
-    {
869
-        return $this->pue_slug;
870
-    }
871
-    /**
872
-     * @param string $pue_slug
873
-     */
874
-    public function setPueSlug($pue_slug)
875
-    {
876
-        $this->pue_slug = $pue_slug;
877
-    }
825
+				$after_plugin_row .= '</td>';
826
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
827
+				$after_plugin_row .= $description;
828
+				$after_plugin_row .= '</td>';
829
+				$after_plugin_row .= '</tr>';
830
+			} else {
831
+				$after_plugin_row .= $description;
832
+			}
833
+		}
834
+
835
+		echo wp_kses($after_plugin_row, AllowedTags::getAllowedTags());
836
+	}
837
+
838
+
839
+	/**
840
+	 * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
841
+	 * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
842
+	 * for back compat reasons.
843
+	 *
844
+	 * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
845
+	 *
846
+	 * It is recommended, if client code is `de-registering` an add-on, then do it on the
847
+	 * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
848
+	 * callback does not get run/set in that request.
849
+	 *
850
+	 * Also, keep in mind that if a registered add-on happens to be deactivated via
851
+	 * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
852
+	 * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
853
+	 * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
854
+	 * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
855
+	 * to call `parent::deactivation`.
856
+	 *
857
+	 * @since 4.9.26
858
+	 */
859
+	public function after_registration()
860
+	{
861
+		// cricket chirp... cricket chirp...
862
+	}
863
+
864
+	/**
865
+	 * @return string
866
+	 */
867
+	public function getPueSlug()
868
+	{
869
+		return $this->pue_slug;
870
+	}
871
+	/**
872
+	 * @param string $pue_slug
873
+	 */
874
+	public function setPueSlug($pue_slug)
875
+	{
876
+		$this->pue_slug = $pue_slug;
877
+	}
878 878
 }
Please login to merge, or discard this patch.
core/EE_Error.core.php 2 patches
Indentation   +1126 added lines, -1126 removed lines patch added patch discarded remove patch
@@ -12,8 +12,8 @@  discard block
 block discarded – undo
12 12
 // if you're a dev and want to receive all errors via email
13 13
 // add this to your wp-config.php: define( 'EE_ERROR_EMAILS', TRUE );
14 14
 if (defined('WP_DEBUG') && WP_DEBUG === true && defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS === true) {
15
-    set_error_handler(array('EE_Error', 'error_handler'));
16
-    register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
15
+	set_error_handler(array('EE_Error', 'error_handler'));
16
+	register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
17 17
 }
18 18
 
19 19
 
@@ -27,266 +27,266 @@  discard block
 block discarded – undo
27 27
 class EE_Error extends Exception
28 28
 {
29 29
 
30
-    const OPTIONS_KEY_NOTICES = 'ee_notices';
31
-
32
-
33
-    /**
34
-     * name of the file to log exceptions to
35
-     *
36
-     * @var string
37
-     */
38
-    private static $_exception_log_file = 'espresso_error_log.txt';
39
-
40
-    /**
41
-     *    stores details for all exception
42
-     *
43
-     * @var array
44
-     */
45
-    private static $_all_exceptions = array();
46
-
47
-    /**
48
-     *    tracks number of errors
49
-     *
50
-     * @var int
51
-     */
52
-    private static $_error_count = 0;
53
-
54
-    /**
55
-     * @var array $_espresso_notices
56
-     */
57
-    private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
58
-
59
-
60
-    /**
61
-     * @override default exception handling
62
-     * @param string         $message
63
-     * @param int            $code
64
-     * @param Exception|null $previous
65
-     */
66
-    public function __construct($message, $code = 0, Exception $previous = null)
67
-    {
68
-        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
69
-            parent::__construct($message, $code);
70
-        } else {
71
-            parent::__construct($message, $code, $previous);
72
-        }
73
-    }
74
-
75
-
76
-    /**
77
-     *    error_handler
78
-     *
79
-     * @param $code
80
-     * @param $message
81
-     * @param $file
82
-     * @param $line
83
-     * @return void
84
-     */
85
-    public static function error_handler($code, $message, $file, $line)
86
-    {
87
-        $type = EE_Error::error_type($code);
88
-        $site = site_url();
89
-        switch ($site) {
90
-            case 'http://ee4.eventespresso.com/':
91
-            case 'http://ee4decaf.eventespresso.com/':
92
-            case 'http://ee4hf.eventespresso.com/':
93
-            case 'http://ee4a.eventespresso.com/':
94
-            case 'http://ee4ad.eventespresso.com/':
95
-            case 'http://ee4b.eventespresso.com/':
96
-            case 'http://ee4bd.eventespresso.com/':
97
-            case 'http://ee4d.eventespresso.com/':
98
-            case 'http://ee4dd.eventespresso.com/':
99
-                $to = '[email protected]';
100
-                break;
101
-            default:
102
-                $to = get_option('admin_email');
103
-        }
104
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
105
-        $msg = EE_Error::_format_error($type, $message, $file, $line);
106
-        if (function_exists('wp_mail')) {
107
-            add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
108
-            wp_mail($to, $subject, $msg);
109
-        }
110
-        echo '<div id="message" class="espresso-notices error"><p>';
111
-        echo wp_kses($type . ': ' . $message . '<br />' . $file . ' line ' . $line, AllowedTags::getWithFormTags());
112
-        echo '<br /></p></div>';
113
-    }
114
-
115
-
116
-    /**
117
-     * error_type
118
-     * http://www.php.net/manual/en/errorfunc.constants.php#109430
119
-     *
120
-     * @param $code
121
-     * @return string
122
-     */
123
-    public static function error_type($code)
124
-    {
125
-        switch ($code) {
126
-            case E_ERROR: // 1 //
127
-                return 'E_ERROR';
128
-            case E_WARNING: // 2 //
129
-                return 'E_WARNING';
130
-            case E_PARSE: // 4 //
131
-                return 'E_PARSE';
132
-            case E_NOTICE: // 8 //
133
-                return 'E_NOTICE';
134
-            case E_CORE_ERROR: // 16 //
135
-                return 'E_CORE_ERROR';
136
-            case E_CORE_WARNING: // 32 //
137
-                return 'E_CORE_WARNING';
138
-            case E_COMPILE_ERROR: // 64 //
139
-                return 'E_COMPILE_ERROR';
140
-            case E_COMPILE_WARNING: // 128 //
141
-                return 'E_COMPILE_WARNING';
142
-            case E_USER_ERROR: // 256 //
143
-                return 'E_USER_ERROR';
144
-            case E_USER_WARNING: // 512 //
145
-                return 'E_USER_WARNING';
146
-            case E_USER_NOTICE: // 1024 //
147
-                return 'E_USER_NOTICE';
148
-            case E_STRICT: // 2048 //
149
-                return 'E_STRICT';
150
-            case E_RECOVERABLE_ERROR: // 4096 //
151
-                return 'E_RECOVERABLE_ERROR';
152
-            case E_DEPRECATED: // 8192 //
153
-                return 'E_DEPRECATED';
154
-            case E_USER_DEPRECATED: // 16384 //
155
-                return 'E_USER_DEPRECATED';
156
-            case E_ALL: // 16384 //
157
-                return 'E_ALL';
158
-        }
159
-        return '';
160
-    }
161
-
162
-
163
-    /**
164
-     *    fatal_error_handler
165
-     *
166
-     * @return void
167
-     */
168
-    public static function fatal_error_handler()
169
-    {
170
-        $last_error = error_get_last();
171
-        if ($last_error['type'] === E_ERROR) {
172
-            EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
173
-        }
174
-    }
175
-
176
-
177
-    /**
178
-     * _format_error
179
-     *
180
-     * @param $code
181
-     * @param $message
182
-     * @param $file
183
-     * @param $line
184
-     * @return string
185
-     */
186
-    private static function _format_error($code, $message, $file, $line)
187
-    {
188
-        $html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
189
-        $html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
190
-        $html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
191
-        $html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
192
-        $html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
193
-        $html .= '</tbody></table>';
194
-        return $html;
195
-    }
196
-
197
-
198
-    /**
199
-     * set_content_type
200
-     *
201
-     * @param $content_type
202
-     * @return string
203
-     */
204
-    public static function set_content_type($content_type)
205
-    {
206
-        return 'text/html';
207
-    }
208
-
209
-
210
-    /**
211
-     * @return void
212
-     * @throws EE_Error
213
-     * @throws ReflectionException
214
-     */
215
-    public function get_error()
216
-    {
217
-        if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
218
-            throw $this;
219
-        }
220
-        // get separate user and developer messages if they exist
221
-        $msg = explode('||', $this->getMessage());
222
-        $user_msg = $msg[0];
223
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
224
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
225
-        // add details to _all_exceptions array
226
-        $x_time = time();
227
-        self::$_all_exceptions[ $x_time ]['name'] = get_class($this);
228
-        self::$_all_exceptions[ $x_time ]['file'] = $this->getFile();
229
-        self::$_all_exceptions[ $x_time ]['line'] = $this->getLine();
230
-        self::$_all_exceptions[ $x_time ]['msg'] = $msg;
231
-        self::$_all_exceptions[ $x_time ]['code'] = $this->getCode();
232
-        self::$_all_exceptions[ $x_time ]['trace'] = $this->getTrace();
233
-        self::$_all_exceptions[ $x_time ]['string'] = $this->getTraceAsString();
234
-        self::$_error_count++;
235
-        // add_action( 'shutdown', array( $this, 'display_errors' ));
236
-        $this->display_errors();
237
-    }
238
-
239
-
240
-    /**
241
-     * @param bool   $check_stored
242
-     * @param string $type_to_check
243
-     * @return bool
244
-     * @throws InvalidInterfaceException
245
-     * @throws InvalidArgumentException
246
-     * @throws InvalidDataTypeException
247
-     */
248
-    public static function has_error($check_stored = false, $type_to_check = 'errors')
249
-    {
250
-        $has_error = isset(self::$_espresso_notices[ $type_to_check ])
251
-                     && ! empty(self::$_espresso_notices[ $type_to_check ])
252
-            ? true
253
-            : false;
254
-        if ($check_stored && ! $has_error) {
255
-            $notices = EE_Error::getStoredNotices();
256
-            foreach ($notices as $type => $notice) {
257
-                if ($type === $type_to_check && $notice) {
258
-                    return true;
259
-                }
260
-            }
261
-        }
262
-        return $has_error;
263
-    }
264
-
265
-
266
-    /**
267
-     * @echo string
268
-     * @throws ReflectionException
269
-     */
270
-    public function display_errors()
271
-    {
272
-        $trace_details = '';
273
-        $output = '
30
+	const OPTIONS_KEY_NOTICES = 'ee_notices';
31
+
32
+
33
+	/**
34
+	 * name of the file to log exceptions to
35
+	 *
36
+	 * @var string
37
+	 */
38
+	private static $_exception_log_file = 'espresso_error_log.txt';
39
+
40
+	/**
41
+	 *    stores details for all exception
42
+	 *
43
+	 * @var array
44
+	 */
45
+	private static $_all_exceptions = array();
46
+
47
+	/**
48
+	 *    tracks number of errors
49
+	 *
50
+	 * @var int
51
+	 */
52
+	private static $_error_count = 0;
53
+
54
+	/**
55
+	 * @var array $_espresso_notices
56
+	 */
57
+	private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
58
+
59
+
60
+	/**
61
+	 * @override default exception handling
62
+	 * @param string         $message
63
+	 * @param int            $code
64
+	 * @param Exception|null $previous
65
+	 */
66
+	public function __construct($message, $code = 0, Exception $previous = null)
67
+	{
68
+		if (version_compare(PHP_VERSION, '5.3.0', '<')) {
69
+			parent::__construct($message, $code);
70
+		} else {
71
+			parent::__construct($message, $code, $previous);
72
+		}
73
+	}
74
+
75
+
76
+	/**
77
+	 *    error_handler
78
+	 *
79
+	 * @param $code
80
+	 * @param $message
81
+	 * @param $file
82
+	 * @param $line
83
+	 * @return void
84
+	 */
85
+	public static function error_handler($code, $message, $file, $line)
86
+	{
87
+		$type = EE_Error::error_type($code);
88
+		$site = site_url();
89
+		switch ($site) {
90
+			case 'http://ee4.eventespresso.com/':
91
+			case 'http://ee4decaf.eventespresso.com/':
92
+			case 'http://ee4hf.eventespresso.com/':
93
+			case 'http://ee4a.eventespresso.com/':
94
+			case 'http://ee4ad.eventespresso.com/':
95
+			case 'http://ee4b.eventespresso.com/':
96
+			case 'http://ee4bd.eventespresso.com/':
97
+			case 'http://ee4d.eventespresso.com/':
98
+			case 'http://ee4dd.eventespresso.com/':
99
+				$to = '[email protected]';
100
+				break;
101
+			default:
102
+				$to = get_option('admin_email');
103
+		}
104
+		$subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
105
+		$msg = EE_Error::_format_error($type, $message, $file, $line);
106
+		if (function_exists('wp_mail')) {
107
+			add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
108
+			wp_mail($to, $subject, $msg);
109
+		}
110
+		echo '<div id="message" class="espresso-notices error"><p>';
111
+		echo wp_kses($type . ': ' . $message . '<br />' . $file . ' line ' . $line, AllowedTags::getWithFormTags());
112
+		echo '<br /></p></div>';
113
+	}
114
+
115
+
116
+	/**
117
+	 * error_type
118
+	 * http://www.php.net/manual/en/errorfunc.constants.php#109430
119
+	 *
120
+	 * @param $code
121
+	 * @return string
122
+	 */
123
+	public static function error_type($code)
124
+	{
125
+		switch ($code) {
126
+			case E_ERROR: // 1 //
127
+				return 'E_ERROR';
128
+			case E_WARNING: // 2 //
129
+				return 'E_WARNING';
130
+			case E_PARSE: // 4 //
131
+				return 'E_PARSE';
132
+			case E_NOTICE: // 8 //
133
+				return 'E_NOTICE';
134
+			case E_CORE_ERROR: // 16 //
135
+				return 'E_CORE_ERROR';
136
+			case E_CORE_WARNING: // 32 //
137
+				return 'E_CORE_WARNING';
138
+			case E_COMPILE_ERROR: // 64 //
139
+				return 'E_COMPILE_ERROR';
140
+			case E_COMPILE_WARNING: // 128 //
141
+				return 'E_COMPILE_WARNING';
142
+			case E_USER_ERROR: // 256 //
143
+				return 'E_USER_ERROR';
144
+			case E_USER_WARNING: // 512 //
145
+				return 'E_USER_WARNING';
146
+			case E_USER_NOTICE: // 1024 //
147
+				return 'E_USER_NOTICE';
148
+			case E_STRICT: // 2048 //
149
+				return 'E_STRICT';
150
+			case E_RECOVERABLE_ERROR: // 4096 //
151
+				return 'E_RECOVERABLE_ERROR';
152
+			case E_DEPRECATED: // 8192 //
153
+				return 'E_DEPRECATED';
154
+			case E_USER_DEPRECATED: // 16384 //
155
+				return 'E_USER_DEPRECATED';
156
+			case E_ALL: // 16384 //
157
+				return 'E_ALL';
158
+		}
159
+		return '';
160
+	}
161
+
162
+
163
+	/**
164
+	 *    fatal_error_handler
165
+	 *
166
+	 * @return void
167
+	 */
168
+	public static function fatal_error_handler()
169
+	{
170
+		$last_error = error_get_last();
171
+		if ($last_error['type'] === E_ERROR) {
172
+			EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
173
+		}
174
+	}
175
+
176
+
177
+	/**
178
+	 * _format_error
179
+	 *
180
+	 * @param $code
181
+	 * @param $message
182
+	 * @param $file
183
+	 * @param $line
184
+	 * @return string
185
+	 */
186
+	private static function _format_error($code, $message, $file, $line)
187
+	{
188
+		$html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
189
+		$html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
190
+		$html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
191
+		$html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
192
+		$html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
193
+		$html .= '</tbody></table>';
194
+		return $html;
195
+	}
196
+
197
+
198
+	/**
199
+	 * set_content_type
200
+	 *
201
+	 * @param $content_type
202
+	 * @return string
203
+	 */
204
+	public static function set_content_type($content_type)
205
+	{
206
+		return 'text/html';
207
+	}
208
+
209
+
210
+	/**
211
+	 * @return void
212
+	 * @throws EE_Error
213
+	 * @throws ReflectionException
214
+	 */
215
+	public function get_error()
216
+	{
217
+		if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
218
+			throw $this;
219
+		}
220
+		// get separate user and developer messages if they exist
221
+		$msg = explode('||', $this->getMessage());
222
+		$user_msg = $msg[0];
223
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
224
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
225
+		// add details to _all_exceptions array
226
+		$x_time = time();
227
+		self::$_all_exceptions[ $x_time ]['name'] = get_class($this);
228
+		self::$_all_exceptions[ $x_time ]['file'] = $this->getFile();
229
+		self::$_all_exceptions[ $x_time ]['line'] = $this->getLine();
230
+		self::$_all_exceptions[ $x_time ]['msg'] = $msg;
231
+		self::$_all_exceptions[ $x_time ]['code'] = $this->getCode();
232
+		self::$_all_exceptions[ $x_time ]['trace'] = $this->getTrace();
233
+		self::$_all_exceptions[ $x_time ]['string'] = $this->getTraceAsString();
234
+		self::$_error_count++;
235
+		// add_action( 'shutdown', array( $this, 'display_errors' ));
236
+		$this->display_errors();
237
+	}
238
+
239
+
240
+	/**
241
+	 * @param bool   $check_stored
242
+	 * @param string $type_to_check
243
+	 * @return bool
244
+	 * @throws InvalidInterfaceException
245
+	 * @throws InvalidArgumentException
246
+	 * @throws InvalidDataTypeException
247
+	 */
248
+	public static function has_error($check_stored = false, $type_to_check = 'errors')
249
+	{
250
+		$has_error = isset(self::$_espresso_notices[ $type_to_check ])
251
+					 && ! empty(self::$_espresso_notices[ $type_to_check ])
252
+			? true
253
+			: false;
254
+		if ($check_stored && ! $has_error) {
255
+			$notices = EE_Error::getStoredNotices();
256
+			foreach ($notices as $type => $notice) {
257
+				if ($type === $type_to_check && $notice) {
258
+					return true;
259
+				}
260
+			}
261
+		}
262
+		return $has_error;
263
+	}
264
+
265
+
266
+	/**
267
+	 * @echo string
268
+	 * @throws ReflectionException
269
+	 */
270
+	public function display_errors()
271
+	{
272
+		$trace_details = '';
273
+		$output = '
274 274
         <div id="ee-error-message" class="error">';
275
-        if (! WP_DEBUG) {
276
-            $output .= '
275
+		if (! WP_DEBUG) {
276
+			$output .= '
277 277
 	        <p>';
278
-        }
279
-        // cycle thru errors
280
-        foreach (self::$_all_exceptions as $time => $ex) {
281
-            $error_code = '';
282
-            // process trace info
283
-            if (empty($ex['trace'])) {
284
-                $trace_details .= esc_html__(
285
-                    'Sorry, but no trace information was available for this exception.',
286
-                    'event_espresso'
287
-                );
288
-            } else {
289
-                $trace_details .= '
278
+		}
279
+		// cycle thru errors
280
+		foreach (self::$_all_exceptions as $time => $ex) {
281
+			$error_code = '';
282
+			// process trace info
283
+			if (empty($ex['trace'])) {
284
+				$trace_details .= esc_html__(
285
+					'Sorry, but no trace information was available for this exception.',
286
+					'event_espresso'
287
+				);
288
+			} else {
289
+				$trace_details .= '
290 290
 			<div id="ee-trace-details">
291 291
 			<table width="100%" border="0" cellpadding="5" cellspacing="0">
292 292
 				<tr>
@@ -296,43 +296,43 @@  discard block
 block discarded – undo
296 296
 					<th scope="col" align="left">Class</th>
297 297
 					<th scope="col" align="left">Method( arguments )</th>
298 298
 				</tr>';
299
-                $last_on_stack = count($ex['trace']) - 1;
300
-                // reverse array so that stack is in proper chronological order
301
-                $sorted_trace = array_reverse($ex['trace']);
302
-                foreach ($sorted_trace as $nmbr => $trace) {
303
-                    $file = isset($trace['file']) ? $trace['file'] : '';
304
-                    $class = isset($trace['class']) ? $trace['class'] : '';
305
-                    $type = isset($trace['type']) ? $trace['type'] : '';
306
-                    $function = isset($trace['function']) ? $trace['function'] : '';
307
-                    $args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
308
-                    $line = isset($trace['line']) ? $trace['line'] : '';
309
-                    $zebra = ($nmbr % 2) ? ' odd' : '';
310
-                    if (empty($file) && ! empty($class)) {
311
-                        $a = new ReflectionClass($class);
312
-                        $file = $a->getFileName();
313
-                        if (empty($line) && ! empty($function)) {
314
-                            try {
315
-                                // if $function is a closure, this throws an exception
316
-                                $b = new ReflectionMethod($class, $function);
317
-                                $line = $b->getStartLine();
318
-                            } catch (Exception $closure_exception) {
319
-                                $line = 'unknown';
320
-                            }
321
-                        }
322
-                    }
323
-                    if ($nmbr === $last_on_stack) {
324
-                        $file = $ex['file'] !== '' ? $ex['file'] : $file;
325
-                        $line = $ex['line'] !== '' ? $ex['line'] : $line;
326
-                        $error_code = self::generate_error_code($file, $trace['function'], $line);
327
-                    }
328
-                    $nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
329
-                    $line_dsply = ! empty($line) ? $line : '&nbsp;';
330
-                    $file_dsply = ! empty($file) ? $file : '&nbsp;';
331
-                    $class_dsply = ! empty($class) ? $class : '&nbsp;';
332
-                    $type_dsply = ! empty($type) ? $type : '&nbsp;';
333
-                    $function_dsply = ! empty($function) ? $function : '&nbsp;';
334
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
335
-                    $trace_details .= '
299
+				$last_on_stack = count($ex['trace']) - 1;
300
+				// reverse array so that stack is in proper chronological order
301
+				$sorted_trace = array_reverse($ex['trace']);
302
+				foreach ($sorted_trace as $nmbr => $trace) {
303
+					$file = isset($trace['file']) ? $trace['file'] : '';
304
+					$class = isset($trace['class']) ? $trace['class'] : '';
305
+					$type = isset($trace['type']) ? $trace['type'] : '';
306
+					$function = isset($trace['function']) ? $trace['function'] : '';
307
+					$args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
308
+					$line = isset($trace['line']) ? $trace['line'] : '';
309
+					$zebra = ($nmbr % 2) ? ' odd' : '';
310
+					if (empty($file) && ! empty($class)) {
311
+						$a = new ReflectionClass($class);
312
+						$file = $a->getFileName();
313
+						if (empty($line) && ! empty($function)) {
314
+							try {
315
+								// if $function is a closure, this throws an exception
316
+								$b = new ReflectionMethod($class, $function);
317
+								$line = $b->getStartLine();
318
+							} catch (Exception $closure_exception) {
319
+								$line = 'unknown';
320
+							}
321
+						}
322
+					}
323
+					if ($nmbr === $last_on_stack) {
324
+						$file = $ex['file'] !== '' ? $ex['file'] : $file;
325
+						$line = $ex['line'] !== '' ? $ex['line'] : $line;
326
+						$error_code = self::generate_error_code($file, $trace['function'], $line);
327
+					}
328
+					$nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
329
+					$line_dsply = ! empty($line) ? $line : '&nbsp;';
330
+					$file_dsply = ! empty($file) ? $file : '&nbsp;';
331
+					$class_dsply = ! empty($class) ? $class : '&nbsp;';
332
+					$type_dsply = ! empty($type) ? $type : '&nbsp;';
333
+					$function_dsply = ! empty($function) ? $function : '&nbsp;';
334
+					$args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
335
+					$trace_details .= '
336 336
 					<tr>
337 337
 						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
338 338
 						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
@@ -340,628 +340,628 @@  discard block
 block discarded – undo
340 340
 						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
341 341
 						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
342 342
 					</tr>';
343
-                }
344
-                $trace_details .= '
343
+				}
344
+				$trace_details .= '
345 345
 			 </table>
346 346
 			</div>';
347
-            }
348
-            $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
349
-            // add generic non-identifying messages for non-privileged users
350
-            if (! WP_DEBUG) {
351
-                $output .= '<span class="ee-error-user-msg-spn">'
352
-                           . trim($ex['msg'])
353
-                           . '</span> &nbsp; <sup>'
354
-                           . $ex['code']
355
-                           . '</sup><br />';
356
-            } else {
357
-                // or helpful developer messages if debugging is on
358
-                $output .= '
347
+			}
348
+			$ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
349
+			// add generic non-identifying messages for non-privileged users
350
+			if (! WP_DEBUG) {
351
+				$output .= '<span class="ee-error-user-msg-spn">'
352
+						   . trim($ex['msg'])
353
+						   . '</span> &nbsp; <sup>'
354
+						   . $ex['code']
355
+						   . '</sup><br />';
356
+			} else {
357
+				// or helpful developer messages if debugging is on
358
+				$output .= '
359 359
 		<div class="ee-error-dev-msg-dv">
360 360
 			<p class="ee-error-dev-msg-pg">
361 361
 				<strong class="ee-error-dev-msg-str">An '
362
-                           . $ex['name']
363
-                           . ' exception was thrown!</strong>  &nbsp; <span>code: '
364
-                           . $ex['code']
365
-                           . '</span><br />
362
+						   . $ex['name']
363
+						   . ' exception was thrown!</strong>  &nbsp; <span>code: '
364
+						   . $ex['code']
365
+						   . '</span><br />
366 366
 				<span class="big-text">"'
367
-                           . trim($ex['msg'])
368
-                           . '"</span><br/>
367
+						   . trim($ex['msg'])
368
+						   . '"</span><br/>
369 369
 				<a id="display-ee-error-trace-'
370
-                           . self::$_error_count
371
-                           . $time
372
-                           . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
373
-                           . self::$_error_count
374
-                           . $time
375
-                           . '">
370
+						   . self::$_error_count
371
+						   . $time
372
+						   . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
373
+						   . self::$_error_count
374
+						   . $time
375
+						   . '">
376 376
 					'
377
-                           . esc_html__('click to view backtrace and class/method details', 'event_espresso')
378
-                           . '
377
+						   . esc_html__('click to view backtrace and class/method details', 'event_espresso')
378
+						   . '
379 379
 				</a><br />
380 380
 				<span class="small-text lt-grey-text">'
381
-                           . $ex['file']
382
-                           . ' &nbsp; ( line no: '
383
-                           . $ex['line']
384
-                           . ' )</span>
381
+						   . $ex['file']
382
+						   . ' &nbsp; ( line no: '
383
+						   . $ex['line']
384
+						   . ' )</span>
385 385
 			</p>
386 386
 			<div id="ee-error-trace-'
387
-                           . self::$_error_count
388
-                           . $time
389
-                           . '-dv" class="ee-error-trace-dv" style="display: none;">
387
+						   . self::$_error_count
388
+						   . $time
389
+						   . '-dv" class="ee-error-trace-dv" style="display: none;">
390 390
 				'
391
-                           . $trace_details;
392
-                if (! empty($class)) {
393
-                    $output .= '
391
+						   . $trace_details;
392
+				if (! empty($class)) {
393
+					$output .= '
394 394
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
395 395
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
396 396
 						<h3>Class Details</h3>';
397
-                    $a = new ReflectionClass($class);
398
-                    $output .= '
397
+					$a = new ReflectionClass($class);
398
+					$output .= '
399 399
 						<pre>' . $a . '</pre>
400 400
 					</div>
401 401
 				</div>';
402
-                }
403
-                $output .= '
402
+				}
403
+				$output .= '
404 404
 			</div>
405 405
 		</div>
406 406
 		<br />';
407
-            }
408
-            $this->write_to_error_log($time, $ex);
409
-        }
410
-        // remove last linebreak
411
-        $output = substr($output, 0, -6);
412
-        if (! WP_DEBUG) {
413
-            $output .= '
407
+			}
408
+			$this->write_to_error_log($time, $ex);
409
+		}
410
+		// remove last linebreak
411
+		$output = substr($output, 0, -6);
412
+		if (! WP_DEBUG) {
413
+			$output .= '
414 414
 	        </p>';
415
-        }
416
-        $output .= '
415
+		}
416
+		$output .= '
417 417
         </div>';
418
-        $output .= self::_print_scripts(true);
419
-        if (defined('DOING_AJAX')) {
420
-            echo wp_json_encode(array('error' => $output));
421
-            exit();
422
-        }
423
-        echo wp_kses($output, AllowedTags::getWithFormTags());
424
-        die();
425
-    }
426
-
427
-
428
-    /**
429
-     *    generate string from exception trace args
430
-     *
431
-     * @param array $arguments
432
-     * @param bool  $array
433
-     * @return string
434
-     */
435
-    private function _convert_args_to_string($arguments = array(), $array = false)
436
-    {
437
-        $arg_string = '';
438
-        if (! empty($arguments)) {
439
-            $args = array();
440
-            foreach ($arguments as $arg) {
441
-                if (! empty($arg)) {
442
-                    if (is_string($arg)) {
443
-                        $args[] = " '" . $arg . "'";
444
-                    } elseif (is_array($arg)) {
445
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
446
-                    } elseif ($arg === null) {
447
-                        $args[] = ' NULL';
448
-                    } elseif (is_bool($arg)) {
449
-                        $args[] = ($arg) ? ' TRUE' : ' FALSE';
450
-                    } elseif (is_object($arg)) {
451
-                        $args[] = ' OBJECT ' . get_class($arg);
452
-                    } elseif (is_resource($arg)) {
453
-                        $args[] = get_resource_type($arg);
454
-                    } else {
455
-                        $args[] = $arg;
456
-                    }
457
-                }
458
-            }
459
-            $arg_string = implode(', ', $args);
460
-        }
461
-        if ($array) {
462
-            $arg_string .= ' )';
463
-        }
464
-        return $arg_string;
465
-    }
466
-
467
-
468
-    /**
469
-     *    add error message
470
-     *
471
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
472
-     *                            separate messages for user || dev
473
-     * @param        string $file the file that the error occurred in - just use __FILE__
474
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
475
-     * @param        string $line the line number where the error occurred - just use __LINE__
476
-     * @return        void
477
-     */
478
-    public static function add_error($msg = null, $file = null, $func = null, $line = null)
479
-    {
480
-        self::_add_notice('errors', $msg, $file, $func, $line);
481
-        self::$_error_count++;
482
-    }
483
-
484
-
485
-    /**
486
-     * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
487
-     * adds an error
488
-     *
489
-     * @param string $msg
490
-     * @param string $file
491
-     * @param string $func
492
-     * @param string $line
493
-     * @throws EE_Error
494
-     */
495
-    public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
496
-    {
497
-        if (WP_DEBUG) {
498
-            throw new EE_Error($msg);
499
-        }
500
-        EE_Error::add_error($msg, $file, $func, $line);
501
-    }
502
-
503
-
504
-    /**
505
-     *    add success message
506
-     *
507
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
508
-     *                            separate messages for user || dev
509
-     * @param        string $file the file that the error occurred in - just use __FILE__
510
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
511
-     * @param        string $line the line number where the error occurred - just use __LINE__
512
-     * @return        void
513
-     */
514
-    public static function add_success($msg = null, $file = null, $func = null, $line = null)
515
-    {
516
-        self::_add_notice('success', $msg, $file, $func, $line);
517
-    }
518
-
519
-
520
-    /**
521
-     *    add attention message
522
-     *
523
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
524
-     *                            separate messages for user || dev
525
-     * @param        string $file the file that the error occurred in - just use __FILE__
526
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
527
-     * @param        string $line the line number where the error occurred - just use __LINE__
528
-     * @return        void
529
-     */
530
-    public static function add_attention($msg = null, $file = null, $func = null, $line = null)
531
-    {
532
-        self::_add_notice('attention', $msg, $file, $func, $line);
533
-    }
534
-
535
-
536
-    /**
537
-     * @param string $type whether the message is for a success or error notification
538
-     * @param string $msg  the message to display to users or developers
539
-     *                     - adding a double pipe || (OR) creates separate messages for user || dev
540
-     * @param string $file the file that the error occurred in - just use __FILE__
541
-     * @param string $func the function/method that the error occurred in - just use __FUNCTION__
542
-     * @param string $line the line number where the error occurred - just use __LINE__
543
-     * @return void
544
-     */
545
-    private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
546
-    {
547
-        if (empty($msg)) {
548
-            EE_Error::doing_it_wrong(
549
-                'EE_Error::add_' . $type . '()',
550
-                sprintf(
551
-                    esc_html__(
552
-                        'Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
553
-                        'event_espresso'
554
-                    ),
555
-                    $type,
556
-                    $file,
557
-                    $line
558
-                ),
559
-                EVENT_ESPRESSO_VERSION
560
-            );
561
-        }
562
-        if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
563
-            EE_Error::doing_it_wrong(
564
-                'EE_Error::add_error()',
565
-                esc_html__(
566
-                    'You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
567
-                    'event_espresso'
568
-                ),
569
-                EVENT_ESPRESSO_VERSION
570
-            );
571
-        }
572
-        // get separate user and developer messages if they exist
573
-        $msg = explode('||', $msg);
574
-        $user_msg = $msg[0];
575
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
576
-        /**
577
-         * Do an action so other code can be triggered when a notice is created
578
-         *
579
-         * @param string $type     can be 'errors', 'attention', or 'success'
580
-         * @param string $user_msg message displayed to user when WP_DEBUG is off
581
-         * @param string $user_msg message displayed to user when WP_DEBUG is on
582
-         * @param string $file     file where error was generated
583
-         * @param string $func     function where error was generated
584
-         * @param string $line     line where error was generated
585
-         */
586
-        do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
587
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
588
-        // add notice if message exists
589
-        if (! empty($msg)) {
590
-            // get error code
591
-            $notice_code = EE_Error::generate_error_code($file, $func, $line);
592
-            if (WP_DEBUG && $type === 'errors') {
593
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
594
-            }
595
-            // add notice. Index by code if it's not blank
596
-            if ($notice_code) {
597
-                self::$_espresso_notices[ $type ][ $notice_code ] = $msg;
598
-            } else {
599
-                self::$_espresso_notices[ $type ][] = $msg;
600
-            }
601
-            add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
602
-        }
603
-    }
604
-
605
-
606
-    /**
607
-     * in some case it may be necessary to overwrite the existing success messages
608
-     *
609
-     * @return        void
610
-     */
611
-    public static function overwrite_success()
612
-    {
613
-        self::$_espresso_notices['success'] = false;
614
-    }
615
-
616
-
617
-    /**
618
-     * in some case it may be necessary to overwrite the existing attention messages
619
-     *
620
-     * @return void
621
-     */
622
-    public static function overwrite_attention()
623
-    {
624
-        self::$_espresso_notices['attention'] = false;
625
-    }
626
-
627
-
628
-    /**
629
-     * in some case it may be necessary to overwrite the existing error messages
630
-     *
631
-     * @return void
632
-     */
633
-    public static function overwrite_errors()
634
-    {
635
-        self::$_espresso_notices['errors'] = false;
636
-    }
637
-
638
-
639
-    /**
640
-     * @return void
641
-     */
642
-    public static function reset_notices()
643
-    {
644
-        self::$_espresso_notices['success'] = false;
645
-        self::$_espresso_notices['attention'] = false;
646
-        self::$_espresso_notices['errors'] = false;
647
-    }
648
-
649
-
650
-    /**
651
-     * @return int
652
-     */
653
-    public static function has_notices()
654
-    {
655
-        $has_notices = 0;
656
-        // check for success messages
657
-        $has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
658
-            ? 3
659
-            : $has_notices;
660
-        // check for attention messages
661
-        $has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
662
-            ? 2
663
-            : $has_notices;
664
-        // check for error messages
665
-        $has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
666
-            ? 1
667
-            : $has_notices;
668
-        return $has_notices;
669
-    }
670
-
671
-
672
-    /**
673
-     * This simply returns non formatted error notices as they were sent into the EE_Error object.
674
-     *
675
-     * @since 4.9.0
676
-     * @return array
677
-     */
678
-    public static function get_vanilla_notices()
679
-    {
680
-        return array(
681
-            'success'   => isset(self::$_espresso_notices['success'])
682
-                ? self::$_espresso_notices['success']
683
-                : array(),
684
-            'attention' => isset(self::$_espresso_notices['attention'])
685
-                ? self::$_espresso_notices['attention']
686
-                : array(),
687
-            'errors'    => isset(self::$_espresso_notices['errors'])
688
-                ? self::$_espresso_notices['errors']
689
-                : array(),
690
-        );
691
-    }
692
-
693
-
694
-    /**
695
-     * @return array
696
-     * @throws InvalidArgumentException
697
-     * @throws InvalidDataTypeException
698
-     * @throws InvalidInterfaceException
699
-     */
700
-    public static function getStoredNotices()
701
-    {
702
-        if ($user_id = get_current_user_id()) {
703
-            // get notices for logged in user
704
-            $notices = get_user_option(EE_Error::OPTIONS_KEY_NOTICES, $user_id);
705
-            return is_array($notices) ? $notices : array();
706
-        }
707
-        if (EE_Session::isLoadedAndActive()) {
708
-            // get notices for user currently engaged in a session
709
-            $session_data = EE_Session::instance()->get_session_data(EE_Error::OPTIONS_KEY_NOTICES);
710
-            return is_array($session_data) ? $session_data : array();
711
-        }
712
-        // get global notices and hope they apply to the current site visitor
713
-        $notices = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
714
-        return is_array($notices) ? $notices : array();
715
-    }
716
-
717
-
718
-    /**
719
-     * @param array $notices
720
-     * @return bool
721
-     * @throws InvalidArgumentException
722
-     * @throws InvalidDataTypeException
723
-     * @throws InvalidInterfaceException
724
-     */
725
-    public static function storeNotices(array $notices)
726
-    {
727
-        if ($user_id = get_current_user_id()) {
728
-            // store notices for logged in user
729
-            return (bool) update_user_option(
730
-                $user_id,
731
-                EE_Error::OPTIONS_KEY_NOTICES,
732
-                $notices
733
-            );
734
-        }
735
-        if (EE_Session::isLoadedAndActive()) {
736
-            // store notices for user currently engaged in a session
737
-            return EE_Session::instance()->set_session_data(
738
-                array(EE_Error::OPTIONS_KEY_NOTICES => $notices)
739
-            );
740
-        }
741
-        // store global notices and hope they apply to the same site visitor on the next request
742
-        return update_option(EE_Error::OPTIONS_KEY_NOTICES, $notices);
743
-    }
744
-
745
-
746
-    /**
747
-     * @return bool|TRUE
748
-     * @throws InvalidArgumentException
749
-     * @throws InvalidDataTypeException
750
-     * @throws InvalidInterfaceException
751
-     */
752
-    public static function clearNotices()
753
-    {
754
-        if ($user_id = get_current_user_id()) {
755
-            // clear notices for logged in user
756
-            return (bool) update_user_option(
757
-                $user_id,
758
-                EE_Error::OPTIONS_KEY_NOTICES,
759
-                array()
760
-            );
761
-        }
762
-        if (EE_Session::isLoadedAndActive()) {
763
-            // clear notices for user currently engaged in a session
764
-            return EE_Session::instance()->reset_data(EE_Error::OPTIONS_KEY_NOTICES);
765
-        }
766
-        // clear global notices and hope none belonged to some for some other site visitor
767
-        return update_option(EE_Error::OPTIONS_KEY_NOTICES, array());
768
-    }
769
-
770
-
771
-    /**
772
-     * saves notices to the db for retrieval on next request
773
-     *
774
-     * @return void
775
-     * @throws InvalidArgumentException
776
-     * @throws InvalidDataTypeException
777
-     * @throws InvalidInterfaceException
778
-     */
779
-    public static function stashNoticesBeforeRedirect()
780
-    {
781
-        EE_Error::get_notices(false, true);
782
-    }
783
-
784
-
785
-    /**
786
-     * compile all error or success messages into one string
787
-     *
788
-     * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
789
-     * @param bool $format_output            whether or not to format the messages for display in the WP admin
790
-     * @param bool $save_to_transient        whether or not to save notices to the db for retrieval on next request
791
-     *                                          - ONLY do this just before redirecting
792
-     * @param bool $remove_empty             whether or not to unset empty messages
793
-     * @return array|string
794
-     * @throws InvalidArgumentException
795
-     * @throws InvalidDataTypeException
796
-     * @throws InvalidInterfaceException
797
-     */
798
-    public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
799
-    {
800
-        $success_messages = '';
801
-        $attention_messages = '';
802
-        $error_messages = '';
803
-        /** @var RequestInterface $request */
804
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
805
-        // either save notices to the db
806
-        if ($save_to_transient || $request->requestParamIsSet('activate-selected')) {
807
-            self::$_espresso_notices = array_merge(
808
-                EE_Error::getStoredNotices(),
809
-                self::$_espresso_notices
810
-            );
811
-            EE_Error::storeNotices(self::$_espresso_notices);
812
-            return array();
813
-        }
814
-        $print_scripts = EE_Error::combineExistingAndNewNotices();
815
-        // check for success messages
816
-        if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
817
-            // combine messages
818
-            $success_messages .= implode('<br />', self::$_espresso_notices['success']);
819
-            $print_scripts = true;
820
-        }
821
-        // check for attention messages
822
-        if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
823
-            // combine messages
824
-            $attention_messages .= implode('<br />', self::$_espresso_notices['attention']);
825
-            $print_scripts = true;
826
-        }
827
-        // check for error messages
828
-        if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
829
-            $error_messages .= count(self::$_espresso_notices['errors']) > 1
830
-                ? esc_html__('The following errors have occurred:', 'event_espresso')
831
-                : esc_html__('An error has occurred:', 'event_espresso');
832
-            // combine messages
833
-            $error_messages .= '<br />' . implode('<br />', self::$_espresso_notices['errors']);
834
-            $print_scripts = true;
835
-        }
836
-        if ($format_output) {
837
-            $notices = EE_Error::formatNoticesOutput(
838
-                $success_messages,
839
-                $attention_messages,
840
-                $error_messages
841
-            );
842
-        } else {
843
-            $notices = array(
844
-                'success'   => $success_messages,
845
-                'attention' => $attention_messages,
846
-                'errors'    => $error_messages,
847
-            );
848
-            if ($remove_empty) {
849
-                // remove empty notices
850
-                foreach ($notices as $type => $notice) {
851
-                    if (empty($notice)) {
852
-                        unset($notices[ $type ]);
853
-                    }
854
-                }
855
-            }
856
-        }
857
-        if ($print_scripts) {
858
-            self::_print_scripts();
859
-        }
860
-        return $notices;
861
-    }
862
-
863
-
864
-    /**
865
-     * @return bool
866
-     * @throws InvalidArgumentException
867
-     * @throws InvalidDataTypeException
868
-     * @throws InvalidInterfaceException
869
-     */
870
-    private static function combineExistingAndNewNotices()
871
-    {
872
-        $print_scripts = false;
873
-        // grab any notices that have been previously saved
874
-        $notices = EE_Error::getStoredNotices();
875
-        if (! empty($notices)) {
876
-            foreach ($notices as $type => $notice) {
877
-                if (is_array($notice) && ! empty($notice)) {
878
-                    // make sure that existing notice type is an array
879
-                    self::$_espresso_notices[ $type ] = is_array(self::$_espresso_notices[ $type ])
880
-                                                        && ! empty(self::$_espresso_notices[ $type ])
881
-                        ? self::$_espresso_notices[ $type ]
882
-                        : array();
883
-                    // add newly created notices to existing ones
884
-                    self::$_espresso_notices[ $type ] += $notice;
885
-                    $print_scripts = true;
886
-                }
887
-            }
888
-            // now clear any stored notices
889
-            EE_Error::clearNotices();
890
-        }
891
-        return $print_scripts;
892
-    }
893
-
894
-
895
-    /**
896
-     * @param string $success_messages
897
-     * @param string $attention_messages
898
-     * @param string $error_messages
899
-     * @return string
900
-     */
901
-    private static function formatNoticesOutput($success_messages, $attention_messages, $error_messages)
902
-    {
903
-        $notices = '<div id="espresso-notices">';
904
-        $close = is_admin()
905
-            ? ''
906
-            : '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"/></a>';
907
-        if ($success_messages !== '') {
908
-            $css_id = is_admin() ? 'ee-success-message' : 'espresso-notices-success';
909
-            $css_class = is_admin() ? 'updated fade' : 'success fade-away';
910
-            // showMessage( $success_messages );
911
-            $notices .= '<div id="' . $css_id . '" '
912
-                        . 'class="espresso-notices ' . $css_class . '" '
913
-                        . 'style="display:none;">'
914
-                        . '<p>' . $success_messages . '</p>'
915
-                        . $close
916
-                        . '</div>';
917
-        }
918
-        if ($attention_messages !== '') {
919
-            $css_id = is_admin() ? 'ee-attention-message' : 'espresso-notices-attention';
920
-            $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
921
-            // showMessage( $error_messages, TRUE );
922
-            $notices .= '<div id="' . $css_id . '" '
923
-                        . 'class="espresso-notices ' . $css_class . '" '
924
-                        . 'style="display:none;">'
925
-                        . '<p>' . $attention_messages . '</p>'
926
-                        . $close
927
-                        . '</div>';
928
-        }
929
-        if ($error_messages !== '') {
930
-            $css_id = is_admin() ? 'ee-error-message' : 'espresso-notices-error';
931
-            $css_class = is_admin() ? 'error' : 'error fade-away';
932
-            // showMessage( $error_messages, TRUE );
933
-            $notices .= '<div id="' . $css_id . '" '
934
-                        . 'class="espresso-notices ' . $css_class . '" '
935
-                        . 'style="display:none;">'
936
-                        . '<p>' . $error_messages . '</p>'
937
-                        . $close
938
-                        . '</div>';
939
-        }
940
-        $notices .= '</div>';
941
-        return $notices;
942
-    }
943
-
944
-
945
-    /**
946
-     * _print_scripts
947
-     *
948
-     * @param    bool $force_print
949
-     * @return    string
950
-     */
951
-    private static function _print_scripts($force_print = false)
952
-    {
953
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
954
-            if (wp_script_is('ee_error_js', 'registered')) {
955
-                wp_enqueue_style('espresso_default');
956
-                wp_enqueue_style('espresso_custom_css');
957
-                wp_enqueue_script('ee_error_js');
958
-            }
959
-            if (wp_script_is('ee_error_js', 'enqueued')) {
960
-                wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
961
-                return '';
962
-            }
963
-        } else {
964
-            return '
418
+		$output .= self::_print_scripts(true);
419
+		if (defined('DOING_AJAX')) {
420
+			echo wp_json_encode(array('error' => $output));
421
+			exit();
422
+		}
423
+		echo wp_kses($output, AllowedTags::getWithFormTags());
424
+		die();
425
+	}
426
+
427
+
428
+	/**
429
+	 *    generate string from exception trace args
430
+	 *
431
+	 * @param array $arguments
432
+	 * @param bool  $array
433
+	 * @return string
434
+	 */
435
+	private function _convert_args_to_string($arguments = array(), $array = false)
436
+	{
437
+		$arg_string = '';
438
+		if (! empty($arguments)) {
439
+			$args = array();
440
+			foreach ($arguments as $arg) {
441
+				if (! empty($arg)) {
442
+					if (is_string($arg)) {
443
+						$args[] = " '" . $arg . "'";
444
+					} elseif (is_array($arg)) {
445
+						$args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
446
+					} elseif ($arg === null) {
447
+						$args[] = ' NULL';
448
+					} elseif (is_bool($arg)) {
449
+						$args[] = ($arg) ? ' TRUE' : ' FALSE';
450
+					} elseif (is_object($arg)) {
451
+						$args[] = ' OBJECT ' . get_class($arg);
452
+					} elseif (is_resource($arg)) {
453
+						$args[] = get_resource_type($arg);
454
+					} else {
455
+						$args[] = $arg;
456
+					}
457
+				}
458
+			}
459
+			$arg_string = implode(', ', $args);
460
+		}
461
+		if ($array) {
462
+			$arg_string .= ' )';
463
+		}
464
+		return $arg_string;
465
+	}
466
+
467
+
468
+	/**
469
+	 *    add error message
470
+	 *
471
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
472
+	 *                            separate messages for user || dev
473
+	 * @param        string $file the file that the error occurred in - just use __FILE__
474
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
475
+	 * @param        string $line the line number where the error occurred - just use __LINE__
476
+	 * @return        void
477
+	 */
478
+	public static function add_error($msg = null, $file = null, $func = null, $line = null)
479
+	{
480
+		self::_add_notice('errors', $msg, $file, $func, $line);
481
+		self::$_error_count++;
482
+	}
483
+
484
+
485
+	/**
486
+	 * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
487
+	 * adds an error
488
+	 *
489
+	 * @param string $msg
490
+	 * @param string $file
491
+	 * @param string $func
492
+	 * @param string $line
493
+	 * @throws EE_Error
494
+	 */
495
+	public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
496
+	{
497
+		if (WP_DEBUG) {
498
+			throw new EE_Error($msg);
499
+		}
500
+		EE_Error::add_error($msg, $file, $func, $line);
501
+	}
502
+
503
+
504
+	/**
505
+	 *    add success message
506
+	 *
507
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
508
+	 *                            separate messages for user || dev
509
+	 * @param        string $file the file that the error occurred in - just use __FILE__
510
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
511
+	 * @param        string $line the line number where the error occurred - just use __LINE__
512
+	 * @return        void
513
+	 */
514
+	public static function add_success($msg = null, $file = null, $func = null, $line = null)
515
+	{
516
+		self::_add_notice('success', $msg, $file, $func, $line);
517
+	}
518
+
519
+
520
+	/**
521
+	 *    add attention message
522
+	 *
523
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
524
+	 *                            separate messages for user || dev
525
+	 * @param        string $file the file that the error occurred in - just use __FILE__
526
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
527
+	 * @param        string $line the line number where the error occurred - just use __LINE__
528
+	 * @return        void
529
+	 */
530
+	public static function add_attention($msg = null, $file = null, $func = null, $line = null)
531
+	{
532
+		self::_add_notice('attention', $msg, $file, $func, $line);
533
+	}
534
+
535
+
536
+	/**
537
+	 * @param string $type whether the message is for a success or error notification
538
+	 * @param string $msg  the message to display to users or developers
539
+	 *                     - adding a double pipe || (OR) creates separate messages for user || dev
540
+	 * @param string $file the file that the error occurred in - just use __FILE__
541
+	 * @param string $func the function/method that the error occurred in - just use __FUNCTION__
542
+	 * @param string $line the line number where the error occurred - just use __LINE__
543
+	 * @return void
544
+	 */
545
+	private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
546
+	{
547
+		if (empty($msg)) {
548
+			EE_Error::doing_it_wrong(
549
+				'EE_Error::add_' . $type . '()',
550
+				sprintf(
551
+					esc_html__(
552
+						'Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
553
+						'event_espresso'
554
+					),
555
+					$type,
556
+					$file,
557
+					$line
558
+				),
559
+				EVENT_ESPRESSO_VERSION
560
+			);
561
+		}
562
+		if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
563
+			EE_Error::doing_it_wrong(
564
+				'EE_Error::add_error()',
565
+				esc_html__(
566
+					'You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
567
+					'event_espresso'
568
+				),
569
+				EVENT_ESPRESSO_VERSION
570
+			);
571
+		}
572
+		// get separate user and developer messages if they exist
573
+		$msg = explode('||', $msg);
574
+		$user_msg = $msg[0];
575
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
576
+		/**
577
+		 * Do an action so other code can be triggered when a notice is created
578
+		 *
579
+		 * @param string $type     can be 'errors', 'attention', or 'success'
580
+		 * @param string $user_msg message displayed to user when WP_DEBUG is off
581
+		 * @param string $user_msg message displayed to user when WP_DEBUG is on
582
+		 * @param string $file     file where error was generated
583
+		 * @param string $func     function where error was generated
584
+		 * @param string $line     line where error was generated
585
+		 */
586
+		do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
587
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
588
+		// add notice if message exists
589
+		if (! empty($msg)) {
590
+			// get error code
591
+			$notice_code = EE_Error::generate_error_code($file, $func, $line);
592
+			if (WP_DEBUG && $type === 'errors') {
593
+				$msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
594
+			}
595
+			// add notice. Index by code if it's not blank
596
+			if ($notice_code) {
597
+				self::$_espresso_notices[ $type ][ $notice_code ] = $msg;
598
+			} else {
599
+				self::$_espresso_notices[ $type ][] = $msg;
600
+			}
601
+			add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
602
+		}
603
+	}
604
+
605
+
606
+	/**
607
+	 * in some case it may be necessary to overwrite the existing success messages
608
+	 *
609
+	 * @return        void
610
+	 */
611
+	public static function overwrite_success()
612
+	{
613
+		self::$_espresso_notices['success'] = false;
614
+	}
615
+
616
+
617
+	/**
618
+	 * in some case it may be necessary to overwrite the existing attention messages
619
+	 *
620
+	 * @return void
621
+	 */
622
+	public static function overwrite_attention()
623
+	{
624
+		self::$_espresso_notices['attention'] = false;
625
+	}
626
+
627
+
628
+	/**
629
+	 * in some case it may be necessary to overwrite the existing error messages
630
+	 *
631
+	 * @return void
632
+	 */
633
+	public static function overwrite_errors()
634
+	{
635
+		self::$_espresso_notices['errors'] = false;
636
+	}
637
+
638
+
639
+	/**
640
+	 * @return void
641
+	 */
642
+	public static function reset_notices()
643
+	{
644
+		self::$_espresso_notices['success'] = false;
645
+		self::$_espresso_notices['attention'] = false;
646
+		self::$_espresso_notices['errors'] = false;
647
+	}
648
+
649
+
650
+	/**
651
+	 * @return int
652
+	 */
653
+	public static function has_notices()
654
+	{
655
+		$has_notices = 0;
656
+		// check for success messages
657
+		$has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
658
+			? 3
659
+			: $has_notices;
660
+		// check for attention messages
661
+		$has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
662
+			? 2
663
+			: $has_notices;
664
+		// check for error messages
665
+		$has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
666
+			? 1
667
+			: $has_notices;
668
+		return $has_notices;
669
+	}
670
+
671
+
672
+	/**
673
+	 * This simply returns non formatted error notices as they were sent into the EE_Error object.
674
+	 *
675
+	 * @since 4.9.0
676
+	 * @return array
677
+	 */
678
+	public static function get_vanilla_notices()
679
+	{
680
+		return array(
681
+			'success'   => isset(self::$_espresso_notices['success'])
682
+				? self::$_espresso_notices['success']
683
+				: array(),
684
+			'attention' => isset(self::$_espresso_notices['attention'])
685
+				? self::$_espresso_notices['attention']
686
+				: array(),
687
+			'errors'    => isset(self::$_espresso_notices['errors'])
688
+				? self::$_espresso_notices['errors']
689
+				: array(),
690
+		);
691
+	}
692
+
693
+
694
+	/**
695
+	 * @return array
696
+	 * @throws InvalidArgumentException
697
+	 * @throws InvalidDataTypeException
698
+	 * @throws InvalidInterfaceException
699
+	 */
700
+	public static function getStoredNotices()
701
+	{
702
+		if ($user_id = get_current_user_id()) {
703
+			// get notices for logged in user
704
+			$notices = get_user_option(EE_Error::OPTIONS_KEY_NOTICES, $user_id);
705
+			return is_array($notices) ? $notices : array();
706
+		}
707
+		if (EE_Session::isLoadedAndActive()) {
708
+			// get notices for user currently engaged in a session
709
+			$session_data = EE_Session::instance()->get_session_data(EE_Error::OPTIONS_KEY_NOTICES);
710
+			return is_array($session_data) ? $session_data : array();
711
+		}
712
+		// get global notices and hope they apply to the current site visitor
713
+		$notices = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
714
+		return is_array($notices) ? $notices : array();
715
+	}
716
+
717
+
718
+	/**
719
+	 * @param array $notices
720
+	 * @return bool
721
+	 * @throws InvalidArgumentException
722
+	 * @throws InvalidDataTypeException
723
+	 * @throws InvalidInterfaceException
724
+	 */
725
+	public static function storeNotices(array $notices)
726
+	{
727
+		if ($user_id = get_current_user_id()) {
728
+			// store notices for logged in user
729
+			return (bool) update_user_option(
730
+				$user_id,
731
+				EE_Error::OPTIONS_KEY_NOTICES,
732
+				$notices
733
+			);
734
+		}
735
+		if (EE_Session::isLoadedAndActive()) {
736
+			// store notices for user currently engaged in a session
737
+			return EE_Session::instance()->set_session_data(
738
+				array(EE_Error::OPTIONS_KEY_NOTICES => $notices)
739
+			);
740
+		}
741
+		// store global notices and hope they apply to the same site visitor on the next request
742
+		return update_option(EE_Error::OPTIONS_KEY_NOTICES, $notices);
743
+	}
744
+
745
+
746
+	/**
747
+	 * @return bool|TRUE
748
+	 * @throws InvalidArgumentException
749
+	 * @throws InvalidDataTypeException
750
+	 * @throws InvalidInterfaceException
751
+	 */
752
+	public static function clearNotices()
753
+	{
754
+		if ($user_id = get_current_user_id()) {
755
+			// clear notices for logged in user
756
+			return (bool) update_user_option(
757
+				$user_id,
758
+				EE_Error::OPTIONS_KEY_NOTICES,
759
+				array()
760
+			);
761
+		}
762
+		if (EE_Session::isLoadedAndActive()) {
763
+			// clear notices for user currently engaged in a session
764
+			return EE_Session::instance()->reset_data(EE_Error::OPTIONS_KEY_NOTICES);
765
+		}
766
+		// clear global notices and hope none belonged to some for some other site visitor
767
+		return update_option(EE_Error::OPTIONS_KEY_NOTICES, array());
768
+	}
769
+
770
+
771
+	/**
772
+	 * saves notices to the db for retrieval on next request
773
+	 *
774
+	 * @return void
775
+	 * @throws InvalidArgumentException
776
+	 * @throws InvalidDataTypeException
777
+	 * @throws InvalidInterfaceException
778
+	 */
779
+	public static function stashNoticesBeforeRedirect()
780
+	{
781
+		EE_Error::get_notices(false, true);
782
+	}
783
+
784
+
785
+	/**
786
+	 * compile all error or success messages into one string
787
+	 *
788
+	 * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
789
+	 * @param bool $format_output            whether or not to format the messages for display in the WP admin
790
+	 * @param bool $save_to_transient        whether or not to save notices to the db for retrieval on next request
791
+	 *                                          - ONLY do this just before redirecting
792
+	 * @param bool $remove_empty             whether or not to unset empty messages
793
+	 * @return array|string
794
+	 * @throws InvalidArgumentException
795
+	 * @throws InvalidDataTypeException
796
+	 * @throws InvalidInterfaceException
797
+	 */
798
+	public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
799
+	{
800
+		$success_messages = '';
801
+		$attention_messages = '';
802
+		$error_messages = '';
803
+		/** @var RequestInterface $request */
804
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
805
+		// either save notices to the db
806
+		if ($save_to_transient || $request->requestParamIsSet('activate-selected')) {
807
+			self::$_espresso_notices = array_merge(
808
+				EE_Error::getStoredNotices(),
809
+				self::$_espresso_notices
810
+			);
811
+			EE_Error::storeNotices(self::$_espresso_notices);
812
+			return array();
813
+		}
814
+		$print_scripts = EE_Error::combineExistingAndNewNotices();
815
+		// check for success messages
816
+		if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
817
+			// combine messages
818
+			$success_messages .= implode('<br />', self::$_espresso_notices['success']);
819
+			$print_scripts = true;
820
+		}
821
+		// check for attention messages
822
+		if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
823
+			// combine messages
824
+			$attention_messages .= implode('<br />', self::$_espresso_notices['attention']);
825
+			$print_scripts = true;
826
+		}
827
+		// check for error messages
828
+		if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
829
+			$error_messages .= count(self::$_espresso_notices['errors']) > 1
830
+				? esc_html__('The following errors have occurred:', 'event_espresso')
831
+				: esc_html__('An error has occurred:', 'event_espresso');
832
+			// combine messages
833
+			$error_messages .= '<br />' . implode('<br />', self::$_espresso_notices['errors']);
834
+			$print_scripts = true;
835
+		}
836
+		if ($format_output) {
837
+			$notices = EE_Error::formatNoticesOutput(
838
+				$success_messages,
839
+				$attention_messages,
840
+				$error_messages
841
+			);
842
+		} else {
843
+			$notices = array(
844
+				'success'   => $success_messages,
845
+				'attention' => $attention_messages,
846
+				'errors'    => $error_messages,
847
+			);
848
+			if ($remove_empty) {
849
+				// remove empty notices
850
+				foreach ($notices as $type => $notice) {
851
+					if (empty($notice)) {
852
+						unset($notices[ $type ]);
853
+					}
854
+				}
855
+			}
856
+		}
857
+		if ($print_scripts) {
858
+			self::_print_scripts();
859
+		}
860
+		return $notices;
861
+	}
862
+
863
+
864
+	/**
865
+	 * @return bool
866
+	 * @throws InvalidArgumentException
867
+	 * @throws InvalidDataTypeException
868
+	 * @throws InvalidInterfaceException
869
+	 */
870
+	private static function combineExistingAndNewNotices()
871
+	{
872
+		$print_scripts = false;
873
+		// grab any notices that have been previously saved
874
+		$notices = EE_Error::getStoredNotices();
875
+		if (! empty($notices)) {
876
+			foreach ($notices as $type => $notice) {
877
+				if (is_array($notice) && ! empty($notice)) {
878
+					// make sure that existing notice type is an array
879
+					self::$_espresso_notices[ $type ] = is_array(self::$_espresso_notices[ $type ])
880
+														&& ! empty(self::$_espresso_notices[ $type ])
881
+						? self::$_espresso_notices[ $type ]
882
+						: array();
883
+					// add newly created notices to existing ones
884
+					self::$_espresso_notices[ $type ] += $notice;
885
+					$print_scripts = true;
886
+				}
887
+			}
888
+			// now clear any stored notices
889
+			EE_Error::clearNotices();
890
+		}
891
+		return $print_scripts;
892
+	}
893
+
894
+
895
+	/**
896
+	 * @param string $success_messages
897
+	 * @param string $attention_messages
898
+	 * @param string $error_messages
899
+	 * @return string
900
+	 */
901
+	private static function formatNoticesOutput($success_messages, $attention_messages, $error_messages)
902
+	{
903
+		$notices = '<div id="espresso-notices">';
904
+		$close = is_admin()
905
+			? ''
906
+			: '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"/></a>';
907
+		if ($success_messages !== '') {
908
+			$css_id = is_admin() ? 'ee-success-message' : 'espresso-notices-success';
909
+			$css_class = is_admin() ? 'updated fade' : 'success fade-away';
910
+			// showMessage( $success_messages );
911
+			$notices .= '<div id="' . $css_id . '" '
912
+						. 'class="espresso-notices ' . $css_class . '" '
913
+						. 'style="display:none;">'
914
+						. '<p>' . $success_messages . '</p>'
915
+						. $close
916
+						. '</div>';
917
+		}
918
+		if ($attention_messages !== '') {
919
+			$css_id = is_admin() ? 'ee-attention-message' : 'espresso-notices-attention';
920
+			$css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
921
+			// showMessage( $error_messages, TRUE );
922
+			$notices .= '<div id="' . $css_id . '" '
923
+						. 'class="espresso-notices ' . $css_class . '" '
924
+						. 'style="display:none;">'
925
+						. '<p>' . $attention_messages . '</p>'
926
+						. $close
927
+						. '</div>';
928
+		}
929
+		if ($error_messages !== '') {
930
+			$css_id = is_admin() ? 'ee-error-message' : 'espresso-notices-error';
931
+			$css_class = is_admin() ? 'error' : 'error fade-away';
932
+			// showMessage( $error_messages, TRUE );
933
+			$notices .= '<div id="' . $css_id . '" '
934
+						. 'class="espresso-notices ' . $css_class . '" '
935
+						. 'style="display:none;">'
936
+						. '<p>' . $error_messages . '</p>'
937
+						. $close
938
+						. '</div>';
939
+		}
940
+		$notices .= '</div>';
941
+		return $notices;
942
+	}
943
+
944
+
945
+	/**
946
+	 * _print_scripts
947
+	 *
948
+	 * @param    bool $force_print
949
+	 * @return    string
950
+	 */
951
+	private static function _print_scripts($force_print = false)
952
+	{
953
+		if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
954
+			if (wp_script_is('ee_error_js', 'registered')) {
955
+				wp_enqueue_style('espresso_default');
956
+				wp_enqueue_style('espresso_custom_css');
957
+				wp_enqueue_script('ee_error_js');
958
+			}
959
+			if (wp_script_is('ee_error_js', 'enqueued')) {
960
+				wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
961
+				return '';
962
+			}
963
+		} else {
964
+			return '
965 965
                 <script>
966 966
                 /* <![CDATA[ */
967 967
                 var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
@@ -971,221 +971,221 @@  discard block
 block discarded – undo
971 971
                 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
972 972
                 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
973 973
             ';
974
-        }
975
-        return '';
976
-    }
977
-
978
-
979
-    /**
980
-     * @return void
981
-     */
982
-    public static function enqueue_error_scripts()
983
-    {
984
-        self::_print_scripts();
985
-    }
986
-
987
-
988
-    /**
989
-     * create error code from filepath, function name,
990
-     * and line number where exception or error was thrown
991
-     *
992
-     * @param string $file
993
-     * @param string $func
994
-     * @param string $line
995
-     * @return string
996
-     */
997
-    public static function generate_error_code($file = '', $func = '', $line = '')
998
-    {
999
-        $file = explode('.', basename($file));
1000
-        $error_code = ! empty($file[0]) ? $file[0] : '';
1001
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
1002
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
1003
-        return $error_code;
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * write exception details to log file
1009
-     * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
1010
-     *
1011
-     * @param int   $time
1012
-     * @param array $ex
1013
-     * @param bool  $clear
1014
-     * @return void
1015
-     */
1016
-    public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1017
-    {
1018
-        if (empty($ex)) {
1019
-            return;
1020
-        }
1021
-        if (! $time) {
1022
-            $time = time();
1023
-        }
1024
-        $exception_log = '----------------------------------------------------------------------------------------'
1025
-                         . PHP_EOL;
1026
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1027
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1028
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1029
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1030
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1031
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
1032
-        $exception_log .= $ex['string'] . PHP_EOL;
1033
-        $exception_log .= '----------------------------------------------------------------------------------------'
1034
-                          . PHP_EOL;
1035
-        try {
1036
-            error_log($exception_log);
1037
-        } catch (EE_Error $e) {
1038
-            EE_Error::add_error(
1039
-                sprintf(
1040
-                    esc_html__(
1041
-                        'Event Espresso error logging could not be setup because: %s',
1042
-                        'event_espresso'
1043
-                    ),
1044
-                    $e->getMessage()
1045
-                )
1046
-            );
1047
-        }
1048
-    }
1049
-
1050
-
1051
-    /**
1052
-     * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1053
-     * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1054
-     * but the code execution is done in a manner that could lead to unexpected results
1055
-     * (i.e. running to early, or too late in WP or EE loading process).
1056
-     * A good test for knowing whether to use this method is:
1057
-     * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1058
-     * Yes -> use EE_Error::add_error() or throw new EE_Error()
1059
-     * 2. If this is loaded before something else, it won't break anything,
1060
-     * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1061
-     *
1062
-     * @uses   constant WP_DEBUG test if wp_debug is on or not
1063
-     * @param string $function      The function that was called
1064
-     * @param string $message       A message explaining what has been done incorrectly
1065
-     * @param string $version       The version of Event Espresso where the error was added
1066
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1067
-     *                              for a deprecated function. This allows deprecation to occur during one version,
1068
-     *                              but not have any notices appear until a later version. This allows developers
1069
-     *                              extra time to update their code before notices appear.
1070
-     * @param int    $error_type
1071
-     */
1072
-    public static function doing_it_wrong(
1073
-        $function,
1074
-        $message,
1075
-        $version,
1076
-        $applies_when = '',
1077
-        $error_type = null
1078
-    ) {
1079
-        if (defined('WP_DEBUG') && WP_DEBUG) {
1080
-            EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1081
-        }
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * Like get_notices, but returns an array of all the notices of the given type.
1087
-     *
1088
-     * @return array {
1089
-     * @type array $success   all the success messages
1090
-     * @type array $errors    all the error messages
1091
-     * @type array $attention all the attention messages
1092
-     * }
1093
-     */
1094
-    public static function get_raw_notices()
1095
-    {
1096
-        return self::$_espresso_notices;
1097
-    }
1098
-
1099
-
1100
-    /**
1101
-     * @deprecated 4.9.27
1102
-     * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1103
-     * @param string $pan_message  the message to be stored persistently until dismissed
1104
-     * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1105
-     * @return void
1106
-     * @throws InvalidDataTypeException
1107
-     */
1108
-    public static function add_persistent_admin_notice($pan_name, $pan_message, $force_update = false)
1109
-    {
1110
-        new PersistentAdminNotice(
1111
-            $pan_name,
1112
-            $pan_message,
1113
-            $force_update
1114
-        );
1115
-        EE_Error::doing_it_wrong(
1116
-            __METHOD__,
1117
-            sprintf(
1118
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1119
-                '\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1120
-            ),
1121
-            '4.9.27'
1122
-        );
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * @deprecated 4.9.27
1128
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1129
-     * @param bool   $purge
1130
-     * @param bool   $return
1131
-     * @throws DomainException
1132
-     * @throws InvalidInterfaceException
1133
-     * @throws InvalidDataTypeException
1134
-     * @throws ServiceNotFoundException
1135
-     * @throws InvalidArgumentException
1136
-     */
1137
-    public static function dismiss_persistent_admin_notice($pan_name, $purge = false, $return = false)
1138
-    {
1139
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1140
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1141
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1142
-        );
1143
-        $persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1144
-        EE_Error::doing_it_wrong(
1145
-            __METHOD__,
1146
-            sprintf(
1147
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1148
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1149
-            ),
1150
-            '4.9.27'
1151
-        );
1152
-    }
1153
-
1154
-
1155
-    /**
1156
-     * @deprecated 4.9.27
1157
-     * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1158
-     * @param  string $pan_message the message to be stored persistently until dismissed
1159
-     * @param  string $return_url  URL to go back to after nag notice is dismissed
1160
-     */
1161
-    public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1162
-    {
1163
-        EE_Error::doing_it_wrong(
1164
-            __METHOD__,
1165
-            sprintf(
1166
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1167
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1168
-            ),
1169
-            '4.9.27'
1170
-        );
1171
-    }
1172
-
1173
-
1174
-    /**
1175
-     * @deprecated 4.9.27
1176
-     * @param string $return_url
1177
-     */
1178
-    public static function get_persistent_admin_notices($return_url = '')
1179
-    {
1180
-        EE_Error::doing_it_wrong(
1181
-            __METHOD__,
1182
-            sprintf(
1183
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1184
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1185
-            ),
1186
-            '4.9.27'
1187
-        );
1188
-    }
974
+		}
975
+		return '';
976
+	}
977
+
978
+
979
+	/**
980
+	 * @return void
981
+	 */
982
+	public static function enqueue_error_scripts()
983
+	{
984
+		self::_print_scripts();
985
+	}
986
+
987
+
988
+	/**
989
+	 * create error code from filepath, function name,
990
+	 * and line number where exception or error was thrown
991
+	 *
992
+	 * @param string $file
993
+	 * @param string $func
994
+	 * @param string $line
995
+	 * @return string
996
+	 */
997
+	public static function generate_error_code($file = '', $func = '', $line = '')
998
+	{
999
+		$file = explode('.', basename($file));
1000
+		$error_code = ! empty($file[0]) ? $file[0] : '';
1001
+		$error_code .= ! empty($func) ? ' - ' . $func : '';
1002
+		$error_code .= ! empty($line) ? ' - ' . $line : '';
1003
+		return $error_code;
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * write exception details to log file
1009
+	 * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
1010
+	 *
1011
+	 * @param int   $time
1012
+	 * @param array $ex
1013
+	 * @param bool  $clear
1014
+	 * @return void
1015
+	 */
1016
+	public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1017
+	{
1018
+		if (empty($ex)) {
1019
+			return;
1020
+		}
1021
+		if (! $time) {
1022
+			$time = time();
1023
+		}
1024
+		$exception_log = '----------------------------------------------------------------------------------------'
1025
+						 . PHP_EOL;
1026
+		$exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1027
+		$exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1028
+		$exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1029
+		$exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1030
+		$exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1031
+		$exception_log .= 'Stack trace: ' . PHP_EOL;
1032
+		$exception_log .= $ex['string'] . PHP_EOL;
1033
+		$exception_log .= '----------------------------------------------------------------------------------------'
1034
+						  . PHP_EOL;
1035
+		try {
1036
+			error_log($exception_log);
1037
+		} catch (EE_Error $e) {
1038
+			EE_Error::add_error(
1039
+				sprintf(
1040
+					esc_html__(
1041
+						'Event Espresso error logging could not be setup because: %s',
1042
+						'event_espresso'
1043
+					),
1044
+					$e->getMessage()
1045
+				)
1046
+			);
1047
+		}
1048
+	}
1049
+
1050
+
1051
+	/**
1052
+	 * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1053
+	 * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1054
+	 * but the code execution is done in a manner that could lead to unexpected results
1055
+	 * (i.e. running to early, or too late in WP or EE loading process).
1056
+	 * A good test for knowing whether to use this method is:
1057
+	 * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1058
+	 * Yes -> use EE_Error::add_error() or throw new EE_Error()
1059
+	 * 2. If this is loaded before something else, it won't break anything,
1060
+	 * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1061
+	 *
1062
+	 * @uses   constant WP_DEBUG test if wp_debug is on or not
1063
+	 * @param string $function      The function that was called
1064
+	 * @param string $message       A message explaining what has been done incorrectly
1065
+	 * @param string $version       The version of Event Espresso where the error was added
1066
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1067
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
1068
+	 *                              but not have any notices appear until a later version. This allows developers
1069
+	 *                              extra time to update their code before notices appear.
1070
+	 * @param int    $error_type
1071
+	 */
1072
+	public static function doing_it_wrong(
1073
+		$function,
1074
+		$message,
1075
+		$version,
1076
+		$applies_when = '',
1077
+		$error_type = null
1078
+	) {
1079
+		if (defined('WP_DEBUG') && WP_DEBUG) {
1080
+			EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1081
+		}
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * Like get_notices, but returns an array of all the notices of the given type.
1087
+	 *
1088
+	 * @return array {
1089
+	 * @type array $success   all the success messages
1090
+	 * @type array $errors    all the error messages
1091
+	 * @type array $attention all the attention messages
1092
+	 * }
1093
+	 */
1094
+	public static function get_raw_notices()
1095
+	{
1096
+		return self::$_espresso_notices;
1097
+	}
1098
+
1099
+
1100
+	/**
1101
+	 * @deprecated 4.9.27
1102
+	 * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1103
+	 * @param string $pan_message  the message to be stored persistently until dismissed
1104
+	 * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1105
+	 * @return void
1106
+	 * @throws InvalidDataTypeException
1107
+	 */
1108
+	public static function add_persistent_admin_notice($pan_name, $pan_message, $force_update = false)
1109
+	{
1110
+		new PersistentAdminNotice(
1111
+			$pan_name,
1112
+			$pan_message,
1113
+			$force_update
1114
+		);
1115
+		EE_Error::doing_it_wrong(
1116
+			__METHOD__,
1117
+			sprintf(
1118
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1119
+				'\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1120
+			),
1121
+			'4.9.27'
1122
+		);
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * @deprecated 4.9.27
1128
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1129
+	 * @param bool   $purge
1130
+	 * @param bool   $return
1131
+	 * @throws DomainException
1132
+	 * @throws InvalidInterfaceException
1133
+	 * @throws InvalidDataTypeException
1134
+	 * @throws ServiceNotFoundException
1135
+	 * @throws InvalidArgumentException
1136
+	 */
1137
+	public static function dismiss_persistent_admin_notice($pan_name, $purge = false, $return = false)
1138
+	{
1139
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1140
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1141
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1142
+		);
1143
+		$persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1144
+		EE_Error::doing_it_wrong(
1145
+			__METHOD__,
1146
+			sprintf(
1147
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1148
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1149
+			),
1150
+			'4.9.27'
1151
+		);
1152
+	}
1153
+
1154
+
1155
+	/**
1156
+	 * @deprecated 4.9.27
1157
+	 * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1158
+	 * @param  string $pan_message the message to be stored persistently until dismissed
1159
+	 * @param  string $return_url  URL to go back to after nag notice is dismissed
1160
+	 */
1161
+	public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1162
+	{
1163
+		EE_Error::doing_it_wrong(
1164
+			__METHOD__,
1165
+			sprintf(
1166
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1167
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1168
+			),
1169
+			'4.9.27'
1170
+		);
1171
+	}
1172
+
1173
+
1174
+	/**
1175
+	 * @deprecated 4.9.27
1176
+	 * @param string $return_url
1177
+	 */
1178
+	public static function get_persistent_admin_notices($return_url = '')
1179
+	{
1180
+		EE_Error::doing_it_wrong(
1181
+			__METHOD__,
1182
+			sprintf(
1183
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1184
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1185
+			),
1186
+			'4.9.27'
1187
+		);
1188
+	}
1189 1189
 }
1190 1190
 
1191 1191
 // end of Class EE_Exceptions
@@ -1198,26 +1198,26 @@  discard block
 block discarded – undo
1198 1198
  */
1199 1199
 function espresso_error_enqueue_scripts()
1200 1200
 {
1201
-    // js for error handling
1202
-    wp_register_script(
1203
-        'espresso_core',
1204
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1205
-        array('jquery'),
1206
-        EVENT_ESPRESSO_VERSION
1207
-    );
1208
-    wp_register_script(
1209
-        'ee_error_js',
1210
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1211
-        array('espresso_core'),
1212
-        EVENT_ESPRESSO_VERSION
1213
-    );
1214
-    wp_localize_script('ee_error_js', 'ee_settings', ['wp_debug' => WP_DEBUG]);
1201
+	// js for error handling
1202
+	wp_register_script(
1203
+		'espresso_core',
1204
+		EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1205
+		array('jquery'),
1206
+		EVENT_ESPRESSO_VERSION
1207
+	);
1208
+	wp_register_script(
1209
+		'ee_error_js',
1210
+		EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1211
+		array('espresso_core'),
1212
+		EVENT_ESPRESSO_VERSION
1213
+	);
1214
+	wp_localize_script('ee_error_js', 'ee_settings', ['wp_debug' => WP_DEBUG]);
1215 1215
 }
1216 1216
 
1217 1217
 if (is_admin()) {
1218
-    add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 5);
1218
+	add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 5);
1219 1219
 } else {
1220
-    add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 5);
1220
+	add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 5);
1221 1221
 }
1222 1222
 
1223 1223
 
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -101,14 +101,14 @@  discard block
 block discarded – undo
101 101
             default:
102 102
                 $to = get_option('admin_email');
103 103
         }
104
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
104
+        $subject = $type.' '.$message.' in '.EVENT_ESPRESSO_VERSION.' on '.site_url();
105 105
         $msg = EE_Error::_format_error($type, $message, $file, $line);
106 106
         if (function_exists('wp_mail')) {
107 107
             add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
108 108
             wp_mail($to, $subject, $msg);
109 109
         }
110 110
         echo '<div id="message" class="espresso-notices error"><p>';
111
-        echo wp_kses($type . ': ' . $message . '<br />' . $file . ' line ' . $line, AllowedTags::getWithFormTags());
111
+        echo wp_kses($type.': '.$message.'<br />'.$file.' line '.$line, AllowedTags::getWithFormTags());
112 112
         echo '<br /></p></div>';
113 113
     }
114 114
 
@@ -224,13 +224,13 @@  discard block
 block discarded – undo
224 224
         $msg = WP_DEBUG ? $dev_msg : $user_msg;
225 225
         // add details to _all_exceptions array
226 226
         $x_time = time();
227
-        self::$_all_exceptions[ $x_time ]['name'] = get_class($this);
228
-        self::$_all_exceptions[ $x_time ]['file'] = $this->getFile();
229
-        self::$_all_exceptions[ $x_time ]['line'] = $this->getLine();
230
-        self::$_all_exceptions[ $x_time ]['msg'] = $msg;
231
-        self::$_all_exceptions[ $x_time ]['code'] = $this->getCode();
232
-        self::$_all_exceptions[ $x_time ]['trace'] = $this->getTrace();
233
-        self::$_all_exceptions[ $x_time ]['string'] = $this->getTraceAsString();
227
+        self::$_all_exceptions[$x_time]['name'] = get_class($this);
228
+        self::$_all_exceptions[$x_time]['file'] = $this->getFile();
229
+        self::$_all_exceptions[$x_time]['line'] = $this->getLine();
230
+        self::$_all_exceptions[$x_time]['msg'] = $msg;
231
+        self::$_all_exceptions[$x_time]['code'] = $this->getCode();
232
+        self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
233
+        self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
234 234
         self::$_error_count++;
235 235
         // add_action( 'shutdown', array( $this, 'display_errors' ));
236 236
         $this->display_errors();
@@ -247,8 +247,8 @@  discard block
 block discarded – undo
247 247
      */
248 248
     public static function has_error($check_stored = false, $type_to_check = 'errors')
249 249
     {
250
-        $has_error = isset(self::$_espresso_notices[ $type_to_check ])
251
-                     && ! empty(self::$_espresso_notices[ $type_to_check ])
250
+        $has_error = isset(self::$_espresso_notices[$type_to_check])
251
+                     && ! empty(self::$_espresso_notices[$type_to_check])
252 252
             ? true
253 253
             : false;
254 254
         if ($check_stored && ! $has_error) {
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
         $trace_details = '';
273 273
         $output = '
274 274
         <div id="ee-error-message" class="error">';
275
-        if (! WP_DEBUG) {
275
+        if ( ! WP_DEBUG) {
276 276
             $output .= '
277 277
 	        <p>';
278 278
         }
@@ -331,14 +331,14 @@  discard block
 block discarded – undo
331 331
                     $class_dsply = ! empty($class) ? $class : '&nbsp;';
332 332
                     $type_dsply = ! empty($type) ? $type : '&nbsp;';
333 333
                     $function_dsply = ! empty($function) ? $function : '&nbsp;';
334
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
334
+                    $args_dsply = ! empty($args) ? '( '.$args.' )' : '';
335 335
                     $trace_details .= '
336 336
 					<tr>
337
-						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
338
-						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
339
-						<td align="left" class="' . $zebra . '">' . $file_dsply . '</td>
340
-						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
341
-						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
337
+						<td align="right" class="' . $zebra.'">'.$nmbr_dsply.'</td>
338
+						<td align="right" class="' . $zebra.'">'.$line_dsply.'</td>
339
+						<td align="left" class="' . $zebra.'">'.$file_dsply.'</td>
340
+						<td align="left" class="' . $zebra.'">'.$class_dsply.'</td>
341
+						<td align="left" class="' . $zebra.'">'.$type_dsply.$function_dsply.$args_dsply.'</td>
342 342
 					</tr>';
343 343
                 }
344 344
                 $trace_details .= '
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
             }
348 348
             $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
349 349
             // add generic non-identifying messages for non-privileged users
350
-            if (! WP_DEBUG) {
350
+            if ( ! WP_DEBUG) {
351 351
                 $output .= '<span class="ee-error-user-msg-spn">'
352 352
                            . trim($ex['msg'])
353 353
                            . '</span> &nbsp; <sup>'
@@ -389,14 +389,14 @@  discard block
 block discarded – undo
389 389
                            . '-dv" class="ee-error-trace-dv" style="display: none;">
390 390
 				'
391 391
                            . $trace_details;
392
-                if (! empty($class)) {
392
+                if ( ! empty($class)) {
393 393
                     $output .= '
394 394
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
395 395
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
396 396
 						<h3>Class Details</h3>';
397 397
                     $a = new ReflectionClass($class);
398 398
                     $output .= '
399
-						<pre>' . $a . '</pre>
399
+						<pre>' . $a.'</pre>
400 400
 					</div>
401 401
 				</div>';
402 402
                 }
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
         }
410 410
         // remove last linebreak
411 411
         $output = substr($output, 0, -6);
412
-        if (! WP_DEBUG) {
412
+        if ( ! WP_DEBUG) {
413 413
             $output .= '
414 414
 	        </p>';
415 415
         }
@@ -435,20 +435,20 @@  discard block
 block discarded – undo
435 435
     private function _convert_args_to_string($arguments = array(), $array = false)
436 436
     {
437 437
         $arg_string = '';
438
-        if (! empty($arguments)) {
438
+        if ( ! empty($arguments)) {
439 439
             $args = array();
440 440
             foreach ($arguments as $arg) {
441
-                if (! empty($arg)) {
441
+                if ( ! empty($arg)) {
442 442
                     if (is_string($arg)) {
443
-                        $args[] = " '" . $arg . "'";
443
+                        $args[] = " '".$arg."'";
444 444
                     } elseif (is_array($arg)) {
445
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
445
+                        $args[] = 'ARRAY('.$this->_convert_args_to_string($arg, true);
446 446
                     } elseif ($arg === null) {
447 447
                         $args[] = ' NULL';
448 448
                     } elseif (is_bool($arg)) {
449 449
                         $args[] = ($arg) ? ' TRUE' : ' FALSE';
450 450
                     } elseif (is_object($arg)) {
451
-                        $args[] = ' OBJECT ' . get_class($arg);
451
+                        $args[] = ' OBJECT '.get_class($arg);
452 452
                     } elseif (is_resource($arg)) {
453 453
                         $args[] = get_resource_type($arg);
454 454
                     } else {
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
     {
547 547
         if (empty($msg)) {
548 548
             EE_Error::doing_it_wrong(
549
-                'EE_Error::add_' . $type . '()',
549
+                'EE_Error::add_'.$type.'()',
550 550
                 sprintf(
551 551
                     esc_html__(
552 552
                         'Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
@@ -586,17 +586,17 @@  discard block
 block discarded – undo
586 586
         do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
587 587
         $msg = WP_DEBUG ? $dev_msg : $user_msg;
588 588
         // add notice if message exists
589
-        if (! empty($msg)) {
589
+        if ( ! empty($msg)) {
590 590
             // get error code
591 591
             $notice_code = EE_Error::generate_error_code($file, $func, $line);
592 592
             if (WP_DEBUG && $type === 'errors') {
593
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
593
+                $msg .= '<br/><span class="tiny-text">'.$notice_code.'</span>';
594 594
             }
595 595
             // add notice. Index by code if it's not blank
596 596
             if ($notice_code) {
597
-                self::$_espresso_notices[ $type ][ $notice_code ] = $msg;
597
+                self::$_espresso_notices[$type][$notice_code] = $msg;
598 598
             } else {
599
-                self::$_espresso_notices[ $type ][] = $msg;
599
+                self::$_espresso_notices[$type][] = $msg;
600 600
             }
601 601
             add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
602 602
         }
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
                 ? esc_html__('The following errors have occurred:', 'event_espresso')
831 831
                 : esc_html__('An error has occurred:', 'event_espresso');
832 832
             // combine messages
833
-            $error_messages .= '<br />' . implode('<br />', self::$_espresso_notices['errors']);
833
+            $error_messages .= '<br />'.implode('<br />', self::$_espresso_notices['errors']);
834 834
             $print_scripts = true;
835 835
         }
836 836
         if ($format_output) {
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
                 // remove empty notices
850 850
                 foreach ($notices as $type => $notice) {
851 851
                     if (empty($notice)) {
852
-                        unset($notices[ $type ]);
852
+                        unset($notices[$type]);
853 853
                     }
854 854
                 }
855 855
             }
@@ -872,16 +872,16 @@  discard block
 block discarded – undo
872 872
         $print_scripts = false;
873 873
         // grab any notices that have been previously saved
874 874
         $notices = EE_Error::getStoredNotices();
875
-        if (! empty($notices)) {
875
+        if ( ! empty($notices)) {
876 876
             foreach ($notices as $type => $notice) {
877 877
                 if (is_array($notice) && ! empty($notice)) {
878 878
                     // make sure that existing notice type is an array
879
-                    self::$_espresso_notices[ $type ] = is_array(self::$_espresso_notices[ $type ])
880
-                                                        && ! empty(self::$_espresso_notices[ $type ])
881
-                        ? self::$_espresso_notices[ $type ]
879
+                    self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
880
+                                                        && ! empty(self::$_espresso_notices[$type])
881
+                        ? self::$_espresso_notices[$type]
882 882
                         : array();
883 883
                     // add newly created notices to existing ones
884
-                    self::$_espresso_notices[ $type ] += $notice;
884
+                    self::$_espresso_notices[$type] += $notice;
885 885
                     $print_scripts = true;
886 886
                 }
887 887
             }
@@ -908,10 +908,10 @@  discard block
 block discarded – undo
908 908
             $css_id = is_admin() ? 'ee-success-message' : 'espresso-notices-success';
909 909
             $css_class = is_admin() ? 'updated fade' : 'success fade-away';
910 910
             // showMessage( $success_messages );
911
-            $notices .= '<div id="' . $css_id . '" '
912
-                        . 'class="espresso-notices ' . $css_class . '" '
911
+            $notices .= '<div id="'.$css_id.'" '
912
+                        . 'class="espresso-notices '.$css_class.'" '
913 913
                         . 'style="display:none;">'
914
-                        . '<p>' . $success_messages . '</p>'
914
+                        . '<p>'.$success_messages.'</p>'
915 915
                         . $close
916 916
                         . '</div>';
917 917
         }
@@ -919,10 +919,10 @@  discard block
 block discarded – undo
919 919
             $css_id = is_admin() ? 'ee-attention-message' : 'espresso-notices-attention';
920 920
             $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
921 921
             // showMessage( $error_messages, TRUE );
922
-            $notices .= '<div id="' . $css_id . '" '
923
-                        . 'class="espresso-notices ' . $css_class . '" '
922
+            $notices .= '<div id="'.$css_id.'" '
923
+                        . 'class="espresso-notices '.$css_class.'" '
924 924
                         . 'style="display:none;">'
925
-                        . '<p>' . $attention_messages . '</p>'
925
+                        . '<p>'.$attention_messages.'</p>'
926 926
                         . $close
927 927
                         . '</div>';
928 928
         }
@@ -930,10 +930,10 @@  discard block
 block discarded – undo
930 930
             $css_id = is_admin() ? 'ee-error-message' : 'espresso-notices-error';
931 931
             $css_class = is_admin() ? 'error' : 'error fade-away';
932 932
             // showMessage( $error_messages, TRUE );
933
-            $notices .= '<div id="' . $css_id . '" '
934
-                        . 'class="espresso-notices ' . $css_class . '" '
933
+            $notices .= '<div id="'.$css_id.'" '
934
+                        . 'class="espresso-notices '.$css_class.'" '
935 935
                         . 'style="display:none;">'
936
-                        . '<p>' . $error_messages . '</p>'
936
+                        . '<p>'.$error_messages.'</p>'
937 937
                         . $close
938 938
                         . '</div>';
939 939
         }
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
      */
951 951
     private static function _print_scripts($force_print = false)
952 952
     {
953
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
953
+        if ( ! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
954 954
             if (wp_script_is('ee_error_js', 'registered')) {
955 955
                 wp_enqueue_style('espresso_default');
956 956
                 wp_enqueue_style('espresso_custom_css');
@@ -964,12 +964,12 @@  discard block
 block discarded – undo
964 964
             return '
965 965
                 <script>
966 966
                 /* <![CDATA[ */
967
-                var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
967
+                var ee_settings = {"wp_debug":"' . WP_DEBUG.'"};
968 968
                 /* ]]> */
969 969
                 </script>
970
-                <script src="' . includes_url() . 'js/jquery/jquery.js" type="text/javascript"></script>
971
-                <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
972
-                <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
970
+                <script src="' . includes_url().'js/jquery/jquery.js" type="text/javascript"></script>
971
+                <script src="' . EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
972
+                <script src="' . EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
973 973
             ';
974 974
         }
975 975
         return '';
@@ -998,8 +998,8 @@  discard block
 block discarded – undo
998 998
     {
999 999
         $file = explode('.', basename($file));
1000 1000
         $error_code = ! empty($file[0]) ? $file[0] : '';
1001
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
1002
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
1001
+        $error_code .= ! empty($func) ? ' - '.$func : '';
1002
+        $error_code .= ! empty($line) ? ' - '.$line : '';
1003 1003
         return $error_code;
1004 1004
     }
1005 1005
 
@@ -1018,18 +1018,18 @@  discard block
 block discarded – undo
1018 1018
         if (empty($ex)) {
1019 1019
             return;
1020 1020
         }
1021
-        if (! $time) {
1021
+        if ( ! $time) {
1022 1022
             $time = time();
1023 1023
         }
1024 1024
         $exception_log = '----------------------------------------------------------------------------------------'
1025 1025
                          . PHP_EOL;
1026
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1027
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1028
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1029
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1030
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1031
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
1032
-        $exception_log .= $ex['string'] . PHP_EOL;
1026
+        $exception_log .= '['.date('Y-m-d H:i:s', $time).']  Exception Details'.PHP_EOL;
1027
+        $exception_log .= 'Message: '.$ex['msg'].PHP_EOL;
1028
+        $exception_log .= 'Code: '.$ex['code'].PHP_EOL;
1029
+        $exception_log .= 'File: '.$ex['file'].PHP_EOL;
1030
+        $exception_log .= 'Line No: '.$ex['line'].PHP_EOL;
1031
+        $exception_log .= 'Stack trace: '.PHP_EOL;
1032
+        $exception_log .= $ex['string'].PHP_EOL;
1033 1033
         $exception_log .= '----------------------------------------------------------------------------------------'
1034 1034
                           . PHP_EOL;
1035 1035
         try {
@@ -1201,13 +1201,13 @@  discard block
 block discarded – undo
1201 1201
     // js for error handling
1202 1202
     wp_register_script(
1203 1203
         'espresso_core',
1204
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1204
+        EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
1205 1205
         array('jquery'),
1206 1206
         EVENT_ESPRESSO_VERSION
1207 1207
     );
1208 1208
     wp_register_script(
1209 1209
         'ee_error_js',
1210
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1210
+        EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
1211 1211
         array('espresso_core'),
1212 1212
         EVENT_ESPRESSO_VERSION
1213 1213
     );
Please login to merge, or discard this patch.
modules/single_page_checkout/inc/EE_SPCO_JSON_Response.php 1 patch
Indentation   +397 added lines, -397 removed lines patch added patch discarded remove patch
@@ -15,401 +15,401 @@
 block discarded – undo
15 15
 class EE_SPCO_JSON_Response
16 16
 {
17 17
 
18
-    /**
19
-     * @var string
20
-     */
21
-    protected $_errors = '';
22
-
23
-    /**
24
-     * @var string
25
-     */
26
-    protected $_unexpected_errors = '';
27
-
28
-    /**
29
-     * @var string
30
-     */
31
-    protected $_attention = '';
32
-
33
-    /**
34
-     * @var string
35
-     */
36
-    protected $_success = '';
37
-
38
-    /**
39
-     * @var string
40
-     */
41
-    protected $_plz_select_method_of_payment = '';
42
-
43
-    /**
44
-     * @var string
45
-     */
46
-    protected $_redirect_url = '';
47
-
48
-    /**
49
-     * @var string
50
-     */
51
-    protected $_registration_time_limit = '';
52
-
53
-    /**
54
-     * @var string
55
-     */
56
-    protected $_redirect_form = '';
57
-
58
-    /**
59
-     * @var string
60
-     */
61
-    protected $_reg_step_html = '';
62
-
63
-    /**
64
-     * @var string
65
-     */
66
-    protected $_method_of_payment = '';
67
-
68
-    /**
69
-     * @var float
70
-     */
71
-    protected $_payment_amount;
72
-
73
-    /**
74
-     * @var array
75
-     */
76
-    protected $_return_data = array();
77
-
78
-
79
-    /**
80
-     * @var array
81
-     */
82
-    protected $_validation_rules = array();
83
-
84
-
85
-    /**
86
-     *    class constructor
87
-     */
88
-    public function __construct()
89
-    {
90
-    }
91
-
92
-
93
-    /**
94
-     *    __toString
95
-     *
96
-     *        allows you to simply echo or print an EE_SPCO_JSON_Response object to produce a  JSON encoded string
97
-     *
98
-     * @access    public
99
-     * @return    string
100
-     */
101
-    public function __toString()
102
-    {
103
-        $JSON_response = array();
104
-        // grab notices
105
-        $notices = EE_Error::get_notices(false);
106
-        $this->set_attention(isset($notices['attention']) ? $notices['attention'] : '');
107
-        $this->set_errors(isset($notices['errors']) ? $notices['errors'] : '');
108
-        $this->set_success(isset($notices['success']) ? $notices['success'] : '');
109
-        // add notices to JSON response, but only if they exist
110
-        if ($this->attention()) {
111
-            $JSON_response['attention'] = $this->attention();
112
-        }
113
-        if ($this->errors()) {
114
-            $JSON_response['errors'] = $this->errors();
115
-        }
116
-        if ($this->unexpected_errors()) {
117
-            $JSON_response['unexpected_errors'] = $this->unexpected_errors();
118
-        }
119
-        if ($this->success()) {
120
-            $JSON_response['success'] = $this->success();
121
-        }
122
-        // but if NO notices are set... at least set the "success" as a key so that the JS knows everything worked
123
-        if (! isset($JSON_response['attention']) && ! isset($JSON_response['errors']) && ! isset($JSON_response['success'])) {
124
-            $JSON_response['success'] = null;
125
-        }
126
-        // set redirect_url, IF it exists
127
-        if ($this->redirect_url()) {
128
-            $JSON_response['redirect_url'] = $this->redirect_url();
129
-        }
130
-        // set registration_time_limit, IF it exists
131
-        if ($this->registration_time_limit()) {
132
-            $JSON_response['registration_time_limit'] = $this->registration_time_limit();
133
-        }
134
-        // set payment_amount, IF it exists
135
-        if ($this->payment_amount() !== null) {
136
-            $JSON_response['payment_amount'] = $this->payment_amount();
137
-        }
138
-        // grab generic return data
139
-        $return_data = $this->return_data();
140
-        // add billing form validation rules
141
-        if ($this->validation_rules()) {
142
-            $return_data['validation_rules'] = $this->validation_rules();
143
-        }
144
-        // set reg_step_html, IF it exists
145
-        if ($this->reg_step_html()) {
146
-            $return_data['reg_step_html'] = $this->reg_step_html();
147
-        }
148
-        // set method of payment, IF it exists
149
-        if ($this->method_of_payment()) {
150
-            $return_data['method_of_payment'] = $this->method_of_payment();
151
-        }
152
-        // set "plz_select_method_of_payment" message, IF it exists
153
-        if ($this->plz_select_method_of_payment()) {
154
-            $return_data['plz_select_method_of_payment'] = $this->plz_select_method_of_payment();
155
-        }
156
-        // set redirect_form, IF it exists
157
-        if ($this->redirect_form()) {
158
-            $return_data['redirect_form'] = $this->redirect_form();
159
-        }
160
-        // and finally, add return_data array to main JSON response array, IF it contains anything
161
-        // why did we add some of the above properties to the return data array?
162
-        // because it is easier and cleaner in the Javascript to deal with this way
163
-        if (! empty($return_data)) {
164
-            $JSON_response['return_data'] = $return_data;
165
-        }
166
-        // filter final array
167
-        $JSON_response = apply_filters('FHEE__EE_SPCO_JSON_Response___toString__JSON_response', $JSON_response);
168
-        // return encoded array
169
-        return (string) wp_json_encode($JSON_response);
170
-    }
171
-
172
-
173
-    /**
174
-     * @param string $attention
175
-     */
176
-    public function set_attention($attention)
177
-    {
178
-        $this->_attention = $attention;
179
-    }
180
-
181
-
182
-    /**
183
-     * @return string
184
-     */
185
-    public function attention()
186
-    {
187
-        return $this->_attention;
188
-    }
189
-
190
-
191
-    /**
192
-     * @param string $errors
193
-     */
194
-    public function set_errors($errors)
195
-    {
196
-        $this->_errors = $errors;
197
-    }
198
-
199
-
200
-    /**
201
-     * @return string
202
-     */
203
-    public function errors()
204
-    {
205
-        return $this->_errors;
206
-    }
207
-
208
-
209
-    /**
210
-     * @return string
211
-     */
212
-    public function unexpected_errors()
213
-    {
214
-        return $this->_unexpected_errors;
215
-    }
216
-
217
-
218
-    /**
219
-     * @param string $unexpected_errors
220
-     */
221
-    public function set_unexpected_errors($unexpected_errors)
222
-    {
223
-        $this->_unexpected_errors = $unexpected_errors;
224
-    }
225
-
226
-
227
-    /**
228
-     * @param string $success
229
-     */
230
-    public function set_success($success)
231
-    {
232
-        $this->_success = $success;
233
-    }
234
-
235
-
236
-    /**
237
-     * @return string
238
-     */
239
-    public function success()
240
-    {
241
-        return $this->_success;
242
-    }
243
-
244
-
245
-    /**
246
-     * @param string $method_of_payment
247
-     */
248
-    public function set_method_of_payment($method_of_payment)
249
-    {
250
-        $this->_method_of_payment = $method_of_payment;
251
-    }
252
-
253
-
254
-    /**
255
-     * @return string
256
-     */
257
-    public function method_of_payment()
258
-    {
259
-        return $this->_method_of_payment;
260
-    }
261
-
262
-
263
-    /**
264
-     * @return float
265
-     */
266
-    public function payment_amount()
267
-    {
268
-        return $this->_payment_amount;
269
-    }
270
-
271
-
272
-    /**
273
-     * @param float $payment_amount
274
-     * @throws EE_Error
275
-     */
276
-    public function set_payment_amount($payment_amount)
277
-    {
278
-        $this->_payment_amount = (float) $payment_amount;
279
-    }
280
-
281
-
282
-    /**
283
-     * @param string $next_step_html
284
-     */
285
-    public function set_reg_step_html($next_step_html)
286
-    {
287
-        $this->_reg_step_html = $next_step_html;
288
-    }
289
-
290
-
291
-    /**
292
-     * @return string
293
-     */
294
-    public function reg_step_html()
295
-    {
296
-        return $this->_reg_step_html;
297
-    }
298
-
299
-
300
-    /**
301
-     * @param string $redirect_form
302
-     */
303
-    public function set_redirect_form($redirect_form)
304
-    {
305
-        $this->_redirect_form = $redirect_form;
306
-    }
307
-
308
-
309
-    /**
310
-     * @return string
311
-     */
312
-    public function redirect_form()
313
-    {
314
-        return ! empty($this->_redirect_form) ? $this->_redirect_form : false;
315
-    }
316
-
317
-
318
-    /**
319
-     * @param string $plz_select_method_of_payment
320
-     */
321
-    public function set_plz_select_method_of_payment($plz_select_method_of_payment)
322
-    {
323
-        $this->_plz_select_method_of_payment = $plz_select_method_of_payment;
324
-    }
325
-
326
-
327
-    /**
328
-     * @return string
329
-     */
330
-    public function plz_select_method_of_payment()
331
-    {
332
-        return $this->_plz_select_method_of_payment;
333
-    }
334
-
335
-
336
-    /**
337
-     * @param string $redirect_url
338
-     */
339
-    public function set_redirect_url($redirect_url)
340
-    {
341
-        $this->_redirect_url = $redirect_url;
342
-    }
343
-
344
-
345
-    /**
346
-     * @return string
347
-     */
348
-    public function redirect_url()
349
-    {
350
-        return $this->_redirect_url;
351
-    }
352
-
353
-
354
-    /**
355
-     * @return string
356
-     */
357
-    public function registration_time_limit()
358
-    {
359
-        return $this->_registration_time_limit;
360
-    }
361
-
362
-
363
-    /**
364
-     * @param string $registration_time_limit
365
-     */
366
-    public function set_registration_time_limit($registration_time_limit)
367
-    {
368
-        $this->_registration_time_limit = $registration_time_limit;
369
-    }
370
-
371
-
372
-    /**
373
-     * @param array $return_data
374
-     */
375
-    public function set_return_data($return_data)
376
-    {
377
-        $this->_return_data = array_merge($this->_return_data, $return_data);
378
-    }
379
-
380
-
381
-    /**
382
-     * @return array
383
-     */
384
-    public function return_data()
385
-    {
386
-        return $this->_return_data;
387
-    }
388
-
389
-
390
-    /**
391
-     * @param array $validation_rules
392
-     */
393
-    public function add_validation_rules(array $validation_rules = array())
394
-    {
395
-        if (is_array($validation_rules) && ! empty($validation_rules)) {
396
-            $this->_validation_rules = array_merge($this->_validation_rules, $validation_rules);
397
-        }
398
-    }
399
-
400
-
401
-    /**
402
-     * @return array | bool
403
-     */
404
-    public function validation_rules()
405
-    {
406
-        return ! empty($this->_validation_rules) ? $this->_validation_rules : false;
407
-    }
408
-
409
-
410
-    public function echoAndExit()
411
-    {
412
-        echo $this;
413
-        exit();
414
-    }
18
+	/**
19
+	 * @var string
20
+	 */
21
+	protected $_errors = '';
22
+
23
+	/**
24
+	 * @var string
25
+	 */
26
+	protected $_unexpected_errors = '';
27
+
28
+	/**
29
+	 * @var string
30
+	 */
31
+	protected $_attention = '';
32
+
33
+	/**
34
+	 * @var string
35
+	 */
36
+	protected $_success = '';
37
+
38
+	/**
39
+	 * @var string
40
+	 */
41
+	protected $_plz_select_method_of_payment = '';
42
+
43
+	/**
44
+	 * @var string
45
+	 */
46
+	protected $_redirect_url = '';
47
+
48
+	/**
49
+	 * @var string
50
+	 */
51
+	protected $_registration_time_limit = '';
52
+
53
+	/**
54
+	 * @var string
55
+	 */
56
+	protected $_redirect_form = '';
57
+
58
+	/**
59
+	 * @var string
60
+	 */
61
+	protected $_reg_step_html = '';
62
+
63
+	/**
64
+	 * @var string
65
+	 */
66
+	protected $_method_of_payment = '';
67
+
68
+	/**
69
+	 * @var float
70
+	 */
71
+	protected $_payment_amount;
72
+
73
+	/**
74
+	 * @var array
75
+	 */
76
+	protected $_return_data = array();
77
+
78
+
79
+	/**
80
+	 * @var array
81
+	 */
82
+	protected $_validation_rules = array();
83
+
84
+
85
+	/**
86
+	 *    class constructor
87
+	 */
88
+	public function __construct()
89
+	{
90
+	}
91
+
92
+
93
+	/**
94
+	 *    __toString
95
+	 *
96
+	 *        allows you to simply echo or print an EE_SPCO_JSON_Response object to produce a  JSON encoded string
97
+	 *
98
+	 * @access    public
99
+	 * @return    string
100
+	 */
101
+	public function __toString()
102
+	{
103
+		$JSON_response = array();
104
+		// grab notices
105
+		$notices = EE_Error::get_notices(false);
106
+		$this->set_attention(isset($notices['attention']) ? $notices['attention'] : '');
107
+		$this->set_errors(isset($notices['errors']) ? $notices['errors'] : '');
108
+		$this->set_success(isset($notices['success']) ? $notices['success'] : '');
109
+		// add notices to JSON response, but only if they exist
110
+		if ($this->attention()) {
111
+			$JSON_response['attention'] = $this->attention();
112
+		}
113
+		if ($this->errors()) {
114
+			$JSON_response['errors'] = $this->errors();
115
+		}
116
+		if ($this->unexpected_errors()) {
117
+			$JSON_response['unexpected_errors'] = $this->unexpected_errors();
118
+		}
119
+		if ($this->success()) {
120
+			$JSON_response['success'] = $this->success();
121
+		}
122
+		// but if NO notices are set... at least set the "success" as a key so that the JS knows everything worked
123
+		if (! isset($JSON_response['attention']) && ! isset($JSON_response['errors']) && ! isset($JSON_response['success'])) {
124
+			$JSON_response['success'] = null;
125
+		}
126
+		// set redirect_url, IF it exists
127
+		if ($this->redirect_url()) {
128
+			$JSON_response['redirect_url'] = $this->redirect_url();
129
+		}
130
+		// set registration_time_limit, IF it exists
131
+		if ($this->registration_time_limit()) {
132
+			$JSON_response['registration_time_limit'] = $this->registration_time_limit();
133
+		}
134
+		// set payment_amount, IF it exists
135
+		if ($this->payment_amount() !== null) {
136
+			$JSON_response['payment_amount'] = $this->payment_amount();
137
+		}
138
+		// grab generic return data
139
+		$return_data = $this->return_data();
140
+		// add billing form validation rules
141
+		if ($this->validation_rules()) {
142
+			$return_data['validation_rules'] = $this->validation_rules();
143
+		}
144
+		// set reg_step_html, IF it exists
145
+		if ($this->reg_step_html()) {
146
+			$return_data['reg_step_html'] = $this->reg_step_html();
147
+		}
148
+		// set method of payment, IF it exists
149
+		if ($this->method_of_payment()) {
150
+			$return_data['method_of_payment'] = $this->method_of_payment();
151
+		}
152
+		// set "plz_select_method_of_payment" message, IF it exists
153
+		if ($this->plz_select_method_of_payment()) {
154
+			$return_data['plz_select_method_of_payment'] = $this->plz_select_method_of_payment();
155
+		}
156
+		// set redirect_form, IF it exists
157
+		if ($this->redirect_form()) {
158
+			$return_data['redirect_form'] = $this->redirect_form();
159
+		}
160
+		// and finally, add return_data array to main JSON response array, IF it contains anything
161
+		// why did we add some of the above properties to the return data array?
162
+		// because it is easier and cleaner in the Javascript to deal with this way
163
+		if (! empty($return_data)) {
164
+			$JSON_response['return_data'] = $return_data;
165
+		}
166
+		// filter final array
167
+		$JSON_response = apply_filters('FHEE__EE_SPCO_JSON_Response___toString__JSON_response', $JSON_response);
168
+		// return encoded array
169
+		return (string) wp_json_encode($JSON_response);
170
+	}
171
+
172
+
173
+	/**
174
+	 * @param string $attention
175
+	 */
176
+	public function set_attention($attention)
177
+	{
178
+		$this->_attention = $attention;
179
+	}
180
+
181
+
182
+	/**
183
+	 * @return string
184
+	 */
185
+	public function attention()
186
+	{
187
+		return $this->_attention;
188
+	}
189
+
190
+
191
+	/**
192
+	 * @param string $errors
193
+	 */
194
+	public function set_errors($errors)
195
+	{
196
+		$this->_errors = $errors;
197
+	}
198
+
199
+
200
+	/**
201
+	 * @return string
202
+	 */
203
+	public function errors()
204
+	{
205
+		return $this->_errors;
206
+	}
207
+
208
+
209
+	/**
210
+	 * @return string
211
+	 */
212
+	public function unexpected_errors()
213
+	{
214
+		return $this->_unexpected_errors;
215
+	}
216
+
217
+
218
+	/**
219
+	 * @param string $unexpected_errors
220
+	 */
221
+	public function set_unexpected_errors($unexpected_errors)
222
+	{
223
+		$this->_unexpected_errors = $unexpected_errors;
224
+	}
225
+
226
+
227
+	/**
228
+	 * @param string $success
229
+	 */
230
+	public function set_success($success)
231
+	{
232
+		$this->_success = $success;
233
+	}
234
+
235
+
236
+	/**
237
+	 * @return string
238
+	 */
239
+	public function success()
240
+	{
241
+		return $this->_success;
242
+	}
243
+
244
+
245
+	/**
246
+	 * @param string $method_of_payment
247
+	 */
248
+	public function set_method_of_payment($method_of_payment)
249
+	{
250
+		$this->_method_of_payment = $method_of_payment;
251
+	}
252
+
253
+
254
+	/**
255
+	 * @return string
256
+	 */
257
+	public function method_of_payment()
258
+	{
259
+		return $this->_method_of_payment;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @return float
265
+	 */
266
+	public function payment_amount()
267
+	{
268
+		return $this->_payment_amount;
269
+	}
270
+
271
+
272
+	/**
273
+	 * @param float $payment_amount
274
+	 * @throws EE_Error
275
+	 */
276
+	public function set_payment_amount($payment_amount)
277
+	{
278
+		$this->_payment_amount = (float) $payment_amount;
279
+	}
280
+
281
+
282
+	/**
283
+	 * @param string $next_step_html
284
+	 */
285
+	public function set_reg_step_html($next_step_html)
286
+	{
287
+		$this->_reg_step_html = $next_step_html;
288
+	}
289
+
290
+
291
+	/**
292
+	 * @return string
293
+	 */
294
+	public function reg_step_html()
295
+	{
296
+		return $this->_reg_step_html;
297
+	}
298
+
299
+
300
+	/**
301
+	 * @param string $redirect_form
302
+	 */
303
+	public function set_redirect_form($redirect_form)
304
+	{
305
+		$this->_redirect_form = $redirect_form;
306
+	}
307
+
308
+
309
+	/**
310
+	 * @return string
311
+	 */
312
+	public function redirect_form()
313
+	{
314
+		return ! empty($this->_redirect_form) ? $this->_redirect_form : false;
315
+	}
316
+
317
+
318
+	/**
319
+	 * @param string $plz_select_method_of_payment
320
+	 */
321
+	public function set_plz_select_method_of_payment($plz_select_method_of_payment)
322
+	{
323
+		$this->_plz_select_method_of_payment = $plz_select_method_of_payment;
324
+	}
325
+
326
+
327
+	/**
328
+	 * @return string
329
+	 */
330
+	public function plz_select_method_of_payment()
331
+	{
332
+		return $this->_plz_select_method_of_payment;
333
+	}
334
+
335
+
336
+	/**
337
+	 * @param string $redirect_url
338
+	 */
339
+	public function set_redirect_url($redirect_url)
340
+	{
341
+		$this->_redirect_url = $redirect_url;
342
+	}
343
+
344
+
345
+	/**
346
+	 * @return string
347
+	 */
348
+	public function redirect_url()
349
+	{
350
+		return $this->_redirect_url;
351
+	}
352
+
353
+
354
+	/**
355
+	 * @return string
356
+	 */
357
+	public function registration_time_limit()
358
+	{
359
+		return $this->_registration_time_limit;
360
+	}
361
+
362
+
363
+	/**
364
+	 * @param string $registration_time_limit
365
+	 */
366
+	public function set_registration_time_limit($registration_time_limit)
367
+	{
368
+		$this->_registration_time_limit = $registration_time_limit;
369
+	}
370
+
371
+
372
+	/**
373
+	 * @param array $return_data
374
+	 */
375
+	public function set_return_data($return_data)
376
+	{
377
+		$this->_return_data = array_merge($this->_return_data, $return_data);
378
+	}
379
+
380
+
381
+	/**
382
+	 * @return array
383
+	 */
384
+	public function return_data()
385
+	{
386
+		return $this->_return_data;
387
+	}
388
+
389
+
390
+	/**
391
+	 * @param array $validation_rules
392
+	 */
393
+	public function add_validation_rules(array $validation_rules = array())
394
+	{
395
+		if (is_array($validation_rules) && ! empty($validation_rules)) {
396
+			$this->_validation_rules = array_merge($this->_validation_rules, $validation_rules);
397
+		}
398
+	}
399
+
400
+
401
+	/**
402
+	 * @return array | bool
403
+	 */
404
+	public function validation_rules()
405
+	{
406
+		return ! empty($this->_validation_rules) ? $this->_validation_rules : false;
407
+	}
408
+
409
+
410
+	public function echoAndExit()
411
+	{
412
+		echo $this;
413
+		exit();
414
+	}
415 415
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +6478 added lines, -6478 removed lines patch added patch discarded remove patch
@@ -36,6484 +36,6484 @@
 block discarded – undo
36 36
 abstract class EEM_Base extends EE_Base implements ResettableInterface
37 37
 {
38 38
 
39
-    /**
40
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
-     * They almost always WILL NOT, but it's not necessarily a requirement.
43
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
-     *
45
-     * @var boolean
46
-     */
47
-    private $_values_already_prepared_by_model_object = 0;
48
-
49
-    /**
50
-     * when $_values_already_prepared_by_model_object equals this, we assume
51
-     * the data is just like form input that needs to have the model fields'
52
-     * prepare_for_set and prepare_for_use_in_db called on it
53
-     */
54
-    const not_prepared_by_model_object = 0;
55
-
56
-    /**
57
-     * when $_values_already_prepared_by_model_object equals this, we
58
-     * assume this value is coming from a model object and doesn't need to have
59
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
60
-     */
61
-    const prepared_by_model_object = 1;
62
-
63
-    /**
64
-     * when $_values_already_prepared_by_model_object equals this, we assume
65
-     * the values are already to be used in the database (ie no processing is done
66
-     * on them by the model's fields)
67
-     */
68
-    const prepared_for_use_in_db = 2;
69
-
70
-
71
-    protected $singular_item = 'Item';
72
-
73
-    protected $plural_item   = 'Items';
74
-
75
-    /**
76
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
-     */
78
-    protected $_tables;
79
-
80
-    /**
81
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
-     *
85
-     * @var \EE_Model_Field_Base[][] $_fields
86
-     */
87
-    protected $_fields;
88
-
89
-    /**
90
-     * array of different kinds of relations
91
-     *
92
-     * @var \EE_Model_Relation_Base[] $_model_relations
93
-     */
94
-    protected $_model_relations;
95
-
96
-    /**
97
-     * @var \EE_Index[] $_indexes
98
-     */
99
-    protected $_indexes = array();
100
-
101
-    /**
102
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
103
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
-     * by setting the same columns as used in these queries in the query yourself.
105
-     *
106
-     * @var EE_Default_Where_Conditions
107
-     */
108
-    protected $_default_where_conditions_strategy;
109
-
110
-    /**
111
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
-     * This is particularly useful when you want something between 'none' and 'default'
113
-     *
114
-     * @var EE_Default_Where_Conditions
115
-     */
116
-    protected $_minimum_where_conditions_strategy;
117
-
118
-    /**
119
-     * String describing how to find the "owner" of this model's objects.
120
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
-     * But when there isn't, this indicates which related model, or transiently-related model,
122
-     * has the foreign key to the wp_users table.
123
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
-     * related to events, and events have a foreign key to wp_users.
125
-     * On EEM_Transaction, this would be 'Transaction.Event'
126
-     *
127
-     * @var string
128
-     */
129
-    protected $_model_chain_to_wp_user = '';
130
-
131
-    /**
132
-     * String describing how to find the model with a password controlling access to this model. This property has the
133
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
-     * This value is the path of models to follow to arrive at the model with the password field.
135
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
-     * model with a password that should affect reading this on the front-end.
137
-     * Eg this is an empty string for the Event model because it has a password.
138
-     * This is null for the Registration model, because its event's password has no bearing on whether
139
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
-     * should hide tickets for datetimes for events that have a password set.
142
-     * @var string |null
143
-     */
144
-    protected $model_chain_to_password = null;
145
-
146
-    /**
147
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
-     * don't need it (particularly CPT models)
149
-     *
150
-     * @var bool
151
-     */
152
-    protected $_ignore_where_strategy = false;
153
-
154
-    /**
155
-     * String used in caps relating to this model. Eg, if the caps relating to this
156
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
-     *
158
-     * @var string. If null it hasn't been initialized yet. If false then we
159
-     * have indicated capabilities don't apply to this
160
-     */
161
-    protected $_caps_slug = null;
162
-
163
-    /**
164
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
-     * and next-level keys are capability names, and each's value is a
166
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
-     * they specify which context to use (ie, frontend, backend, edit or delete)
168
-     * and then each capability in the corresponding sub-array that they're missing
169
-     * adds the where conditions onto the query.
170
-     *
171
-     * @var array
172
-     */
173
-    protected $_cap_restrictions = array(
174
-        self::caps_read       => array(),
175
-        self::caps_read_admin => array(),
176
-        self::caps_edit       => array(),
177
-        self::caps_delete     => array(),
178
-    );
179
-
180
-    /**
181
-     * Array defining which cap restriction generators to use to create default
182
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
183
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
-     * automatically set this to false (not just null).
186
-     *
187
-     * @var EE_Restriction_Generator_Base[]
188
-     */
189
-    protected $_cap_restriction_generators = array();
190
-
191
-    /**
192
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
-     */
194
-    const caps_read       = 'read';
195
-
196
-    const caps_read_admin = 'read_admin';
197
-
198
-    const caps_edit       = 'edit';
199
-
200
-    const caps_delete     = 'delete';
201
-
202
-    /**
203
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
-     * maps to 'read' because when looking for relevant permissions we're going to use
206
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
207
-     *
208
-     * @var array
209
-     */
210
-    protected $_cap_contexts_to_cap_action_map = array(
211
-        self::caps_read       => 'read',
212
-        self::caps_read_admin => 'read',
213
-        self::caps_edit       => 'edit',
214
-        self::caps_delete     => 'delete',
215
-    );
216
-
217
-    /**
218
-     * Timezone
219
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
-     * EE_Datetime_Field data type will have access to it.
223
-     *
224
-     * @var string
225
-     */
226
-    protected $_timezone;
227
-
228
-
229
-    /**
230
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
-     * multisite.
232
-     *
233
-     * @var int
234
-     */
235
-    protected static $_model_query_blog_id;
236
-
237
-    /**
238
-     * A copy of _fields, except the array keys are the model names pointed to by
239
-     * the field
240
-     *
241
-     * @var EE_Model_Field_Base[]
242
-     */
243
-    private $_cache_foreign_key_to_fields = array();
244
-
245
-    /**
246
-     * Cached list of all the fields on the model, indexed by their name
247
-     *
248
-     * @var EE_Model_Field_Base[]
249
-     */
250
-    private $_cached_fields = null;
251
-
252
-    /**
253
-     * Cached list of all the fields on the model, except those that are
254
-     * marked as only pertinent to the database
255
-     *
256
-     * @var EE_Model_Field_Base[]
257
-     */
258
-    private $_cached_fields_non_db_only = null;
259
-
260
-    /**
261
-     * A cached reference to the primary key for quick lookup
262
-     *
263
-     * @var EE_Model_Field_Base
264
-     */
265
-    private $_primary_key_field = null;
266
-
267
-    /**
268
-     * Flag indicating whether this model has a primary key or not
269
-     *
270
-     * @var boolean
271
-     */
272
-    protected $_has_primary_key_field = null;
273
-
274
-    /**
275
-     * array in the format:  [ FK alias => full PK ]
276
-     * where keys are local column name aliases for foreign keys
277
-     * and values are the fully qualified column name for the primary key they represent
278
-     *  ex:
279
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
-     *
281
-     * @var array $foreign_key_aliases
282
-     */
283
-    protected $foreign_key_aliases = [];
284
-
285
-    /**
286
-     * Whether or not this model is based off a table in WP core only (CPTs should set
287
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
-     * This should be true for models that deal with data that should exist independent of EE.
289
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
291
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
293
-     * @var boolean
294
-     */
295
-    protected $_wp_core_model = false;
296
-
297
-    /**
298
-     * @var bool stores whether this model has a password field or not.
299
-     * null until initialized by hasPasswordField()
300
-     */
301
-    protected $has_password_field;
302
-
303
-    /**
304
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
-     */
306
-    protected $password_field;
307
-
308
-    /**
309
-     *    List of valid operators that can be used for querying.
310
-     * The keys are all operators we'll accept, the values are the real SQL
311
-     * operators used
312
-     *
313
-     * @var array
314
-     */
315
-    protected $_valid_operators = array(
316
-        '='           => '=',
317
-        '<='          => '<=',
318
-        '<'           => '<',
319
-        '>='          => '>=',
320
-        '>'           => '>',
321
-        '!='          => '!=',
322
-        'LIKE'        => 'LIKE',
323
-        'like'        => 'LIKE',
324
-        'NOT_LIKE'    => 'NOT LIKE',
325
-        'not_like'    => 'NOT LIKE',
326
-        'NOT LIKE'    => 'NOT LIKE',
327
-        'not like'    => 'NOT LIKE',
328
-        'IN'          => 'IN',
329
-        'in'          => 'IN',
330
-        'NOT_IN'      => 'NOT IN',
331
-        'not_in'      => 'NOT IN',
332
-        'NOT IN'      => 'NOT IN',
333
-        'not in'      => 'NOT IN',
334
-        'between'     => 'BETWEEN',
335
-        'BETWEEN'     => 'BETWEEN',
336
-        'IS_NOT_NULL' => 'IS NOT NULL',
337
-        'is_not_null' => 'IS NOT NULL',
338
-        'IS NOT NULL' => 'IS NOT NULL',
339
-        'is not null' => 'IS NOT NULL',
340
-        'IS_NULL'     => 'IS NULL',
341
-        'is_null'     => 'IS NULL',
342
-        'IS NULL'     => 'IS NULL',
343
-        'is null'     => 'IS NULL',
344
-        'REGEXP'      => 'REGEXP',
345
-        'regexp'      => 'REGEXP',
346
-        'NOT_REGEXP'  => 'NOT REGEXP',
347
-        'not_regexp'  => 'NOT REGEXP',
348
-        'NOT REGEXP'  => 'NOT REGEXP',
349
-        'not regexp'  => 'NOT REGEXP',
350
-    );
351
-
352
-    /**
353
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
-     *
355
-     * @var array
356
-     */
357
-    protected $_in_style_operators = array('IN', 'NOT IN');
358
-
359
-    /**
360
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
-     * '12-31-2012'"
362
-     *
363
-     * @var array
364
-     */
365
-    protected $_between_style_operators = array('BETWEEN');
366
-
367
-    /**
368
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
-     * @var array
370
-     */
371
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
-    /**
373
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
-     * on a join table.
375
-     *
376
-     * @var array
377
-     */
378
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
-
380
-    /**
381
-     * Allowed values for $query_params['order'] for ordering in queries
382
-     *
383
-     * @var array
384
-     */
385
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
-
387
-    /**
388
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
390
-     *
391
-     * @var array
392
-     */
393
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
-
395
-    /**
396
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
398
-     *
399
-     * @var array
400
-     */
401
-    private $_allowed_query_params = array(
402
-        0,
403
-        'limit',
404
-        'order_by',
405
-        'group_by',
406
-        'having',
407
-        'force_join',
408
-        'order',
409
-        'on_join_limit',
410
-        'default_where_conditions',
411
-        'caps',
412
-        'extra_selects',
413
-        'exclude_protected',
414
-    );
415
-
416
-    /**
417
-     * All the data types that can be used in $wpdb->prepare statements.
418
-     *
419
-     * @var array
420
-     */
421
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
-
423
-    /**
424
-     * @var EE_Registry $EE
425
-     */
426
-    protected $EE = null;
427
-
428
-
429
-    /**
430
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
-     *
432
-     * @var int
433
-     */
434
-    protected $_show_next_x_db_queries = 0;
435
-
436
-    /**
437
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
-     * WHERE, GROUP_BY, etc.
440
-     *
441
-     * @var CustomSelects
442
-     */
443
-    protected $_custom_selections = array();
444
-
445
-    /**
446
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
-     * caches every model object we've fetched from the DB on this request
448
-     *
449
-     * @var array
450
-     */
451
-    protected $_entity_map;
452
-
453
-    /**
454
-     * @var LoaderInterface $loader
455
-     */
456
-    protected static $loader;
457
-
458
-
459
-    /**
460
-     * constant used to show EEM_Base has not yet verified the db on this http request
461
-     */
462
-    const db_verified_none = 0;
463
-
464
-    /**
465
-     * constant used to show EEM_Base has verified the EE core db on this http request,
466
-     * but not the addons' dbs
467
-     */
468
-    const db_verified_core = 1;
469
-
470
-    /**
471
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
-     * the EE core db too)
473
-     */
474
-    const db_verified_addons = 2;
475
-
476
-    /**
477
-     * indicates whether an EEM_Base child has already re-verified the DB
478
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
479
-     * looking like EEM_Base::db_verified_*
480
-     *
481
-     * @var int - 0 = none, 1 = core, 2 = addons
482
-     */
483
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
484
-
485
-    /**
486
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
-     *        registrations for non-trashed tickets for non-trashed datetimes)
489
-     */
490
-    const default_where_conditions_all = 'all';
491
-
492
-    /**
493
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
-     *        models which share tables with other models, this can return data for the wrong model.
498
-     */
499
-    const default_where_conditions_this_only = 'this_model_only';
500
-
501
-    /**
502
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
-     */
506
-    const default_where_conditions_others_only = 'other_models_only';
507
-
508
-    /**
509
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
512
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
-     *        (regardless of whether those events and venues are trashed)
514
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
-     *        events.
516
-     */
517
-    const default_where_conditions_minimum_all = 'minimum';
518
-
519
-    /**
520
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
-     *        not)
524
-     */
525
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
-
527
-    /**
528
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
-     *        it's possible it will return table entries for other models. You should use
531
-     *        EEM_Base::default_where_conditions_minimum_all instead.
532
-     */
533
-    const default_where_conditions_none = 'none';
534
-
535
-
536
-
537
-    /**
538
-     * About all child constructors:
539
-     * they should define the _tables, _fields and _model_relations arrays.
540
-     * Should ALWAYS be called after child constructor.
541
-     * In order to make the child constructors to be as simple as possible, this parent constructor
542
-     * finalizes constructing all the object's attributes.
543
-     * Generally, rather than requiring a child to code
544
-     * $this->_tables = array(
545
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
-     *        ...);
547
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
-     * each EE_Table has a function to set the table's alias after the constructor, using
549
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
-     * do something similar.
551
-     *
552
-     * @param null $timezone
553
-     * @throws EE_Error
554
-     */
555
-    protected function __construct($timezone = null)
556
-    {
557
-        // check that the model has not been loaded too soon
558
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
-            throw new EE_Error(
560
-                sprintf(
561
-                    esc_html__(
562
-                        '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.',
563
-                        'event_espresso'
564
-                    ),
565
-                    get_class($this)
566
-                )
567
-            );
568
-        }
569
-        /**
570
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
-         */
572
-        if (empty(EEM_Base::$_model_query_blog_id)) {
573
-            EEM_Base::set_model_query_blog_id();
574
-        }
575
-        /**
576
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
-         * just use EE_Register_Model_Extension
578
-         *
579
-         * @var EE_Table_Base[] $_tables
580
-         */
581
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
-        foreach ($this->_tables as $table_alias => $table_obj) {
583
-            /** @var $table_obj EE_Table_Base */
584
-            $table_obj->_construct_finalize_with_alias($table_alias);
585
-            if ($table_obj instanceof EE_Secondary_Table) {
586
-                /** @var $table_obj EE_Secondary_Table */
587
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
-            }
589
-        }
590
-        /**
591
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
-         * EE_Register_Model_Extension
593
-         *
594
-         * @param EE_Model_Field_Base[] $_fields
595
-         */
596
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
-        $this->_invalidate_field_caches();
598
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
599
-            if (! array_key_exists($table_alias, $this->_tables)) {
600
-                throw new EE_Error(sprintf(esc_html__(
601
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
-                    'event_espresso'
603
-                ), $table_alias, implode(",", $this->_fields)));
604
-            }
605
-            foreach ($fields_for_table as $field_name => $field_obj) {
606
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
-                // primary key field base has a slightly different _construct_finalize
608
-                /** @var $field_obj EE_Model_Field_Base */
609
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
-            }
611
-        }
612
-        // everything is related to Extra_Meta
613
-        if (get_class($this) !== 'EEM_Extra_Meta') {
614
-            // make extra meta related to everything, but don't block deleting things just
615
-            // because they have related extra meta info. For now just orphan those extra meta
616
-            // in the future we should automatically delete them
617
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
-        }
619
-        // and change logs
620
-        if (get_class($this) !== 'EEM_Change_Log') {
621
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
-        }
623
-        /**
624
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
-         * EE_Register_Model_Extension
626
-         *
627
-         * @param EE_Model_Relation_Base[] $_model_relations
628
-         */
629
-        $this->_model_relations = (array) apply_filters(
630
-            'FHEE__' . get_class($this) . '__construct__model_relations',
631
-            $this->_model_relations
632
-        );
633
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
634
-            /** @var $relation_obj EE_Model_Relation_Base */
635
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
-        }
637
-        foreach ($this->_indexes as $index_name => $index_obj) {
638
-            /** @var $index_obj EE_Index */
639
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
-        }
641
-        $this->set_timezone($timezone);
642
-        // finalize default where condition strategy, or set default
643
-        if (! $this->_default_where_conditions_strategy) {
644
-            // nothing was set during child constructor, so set default
645
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
-        }
647
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
648
-        if (! $this->_minimum_where_conditions_strategy) {
649
-            // nothing was set during child constructor, so set default
650
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
-        }
652
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
654
-        // to indicate to NOT set it, set it to the logical default
655
-        if ($this->_caps_slug === null) {
656
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
-        }
658
-        // initialize the standard cap restriction generators if none were specified by the child constructor
659
-        if ($this->_cap_restriction_generators !== false) {
660
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
-                        new EE_Restriction_Generator_Protected(),
665
-                        $cap_context,
666
-                        $this
667
-                    );
668
-                }
669
-            }
670
-        }
671
-        // if there are cap restriction generators, use them to make the default cap restrictions
672
-        if ($this->_cap_restriction_generators !== false) {
673
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
-                if (! $generator_object) {
675
-                    continue;
676
-                }
677
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
-                    throw new EE_Error(
679
-                        sprintf(
680
-                            esc_html__(
681
-                                '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.',
682
-                                'event_espresso'
683
-                            ),
684
-                            $context,
685
-                            $this->get_this_model_name()
686
-                        )
687
-                    );
688
-                }
689
-                $action = $this->cap_action_for_context($context);
690
-                if (! $generator_object->construction_finalized()) {
691
-                    $generator_object->_construct_finalize($this, $action);
692
-                }
693
-            }
694
-        }
695
-        do_action('AHEE__' . get_class($this) . '__construct__end');
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * Used to set the $_model_query_blog_id static property.
702
-     *
703
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
-     *                      value for get_current_blog_id() will be used.
705
-     */
706
-    public static function set_model_query_blog_id($blog_id = 0)
707
-    {
708
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
-    }
710
-
711
-
712
-
713
-    /**
714
-     * Returns whatever is set as the internal $model_query_blog_id.
715
-     *
716
-     * @return int
717
-     */
718
-    public static function get_model_query_blog_id()
719
-    {
720
-        return EEM_Base::$_model_query_blog_id;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * This function is a singleton method used to instantiate the Espresso_model object
727
-     *
728
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
-     *                                (and any incoming timezone data that gets saved).
730
-     *                                Note this just sends the timezone info to the date time model field objects.
731
-     *                                Default is NULL
732
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
-     * @return static (as in the concrete child class)
734
-     * @throws EE_Error
735
-     * @throws InvalidArgumentException
736
-     * @throws InvalidDataTypeException
737
-     * @throws InvalidInterfaceException
738
-     */
739
-    public static function instance($timezone = null)
740
-    {
741
-        // check if instance of Espresso_model already exists
742
-        if (! static::$_instance instanceof static) {
743
-            // instantiate Espresso_model
744
-            static::$_instance = new static(
745
-                $timezone,
746
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
-            );
748
-        }
749
-        // we might have a timezone set, let set_timezone decide what to do with it
750
-        static::$_instance->set_timezone($timezone);
751
-        // Espresso_model object
752
-        return static::$_instance;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * resets the model and returns it
759
-     *
760
-     * @param null | string $timezone
761
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
-     * all its properties reset; if it wasn't instantiated, returns null)
763
-     * @throws EE_Error
764
-     * @throws ReflectionException
765
-     * @throws InvalidArgumentException
766
-     * @throws InvalidDataTypeException
767
-     * @throws InvalidInterfaceException
768
-     */
769
-    public static function reset($timezone = null)
770
-    {
771
-        if (static::$_instance instanceof EEM_Base) {
772
-            // let's try to NOT swap out the current instance for a new one
773
-            // because if someone has a reference to it, we can't remove their reference
774
-            // so it's best to keep using the same reference, but change the original object
775
-            // reset all its properties to their original values as defined in the class
776
-            $r = new ReflectionClass(get_class(static::$_instance));
777
-            $static_properties = $r->getStaticProperties();
778
-            foreach ($r->getDefaultProperties() as $property => $value) {
779
-                // don't set instance to null like it was originally,
780
-                // but it's static anyways, and we're ignoring static properties (for now at least)
781
-                if (! isset($static_properties[ $property ])) {
782
-                    static::$_instance->{$property} = $value;
783
-                }
784
-            }
785
-            // and then directly call its constructor again, like we would if we were creating a new one
786
-            static::$_instance->__construct(
787
-                $timezone,
788
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
-            );
790
-            return self::instance();
791
-        }
792
-        return null;
793
-    }
794
-
795
-
796
-
797
-    /**
798
-     * @return LoaderInterface
799
-     * @throws InvalidArgumentException
800
-     * @throws InvalidDataTypeException
801
-     * @throws InvalidInterfaceException
802
-     */
803
-    private static function getLoader()
804
-    {
805
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
806
-            EEM_Base::$loader = LoaderFactory::getLoader();
807
-        }
808
-        return EEM_Base::$loader;
809
-    }
810
-
811
-
812
-
813
-    /**
814
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
-     *
816
-     * @param  boolean $translated return localized strings or JUST the array.
817
-     * @return array
818
-     * @throws EE_Error
819
-     * @throws InvalidArgumentException
820
-     * @throws InvalidDataTypeException
821
-     * @throws InvalidInterfaceException
822
-     */
823
-    public function status_array($translated = false)
824
-    {
825
-        if (! array_key_exists('Status', $this->_model_relations)) {
826
-            return array();
827
-        }
828
-        $model_name = $this->get_this_model_name();
829
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
-        $status_array = array();
832
-        foreach ($stati as $status) {
833
-            $status_array[ $status->ID() ] = $status->get('STS_code');
834
-        }
835
-        return $translated
836
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
-            : $status_array;
838
-    }
839
-
840
-
841
-
842
-    /**
843
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
-     *
845
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
-     *                             or if you have the development copy of EE you can view this at the path:
847
-     *                             /docs/G--Model-System/model-query-params.md
848
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
-     *                                        array( array(
853
-     *                                        'OR'=>array(
854
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
-     *                                        )
857
-     *                                        ),
858
-     *                                        'limit'=>10,
859
-     *                                        'group_by'=>'TXN_ID'
860
-     *                                        ));
861
-     *                                        get all the answers to the question titled "shirt size" for event with id
862
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
-     *                                        'Question.QST_display_text'=>'shirt size',
864
-     *                                        'Registration.Event.EVT_ID'=>12
865
-     *                                        ),
866
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
867
-     *                                        ));
868
-     * @throws EE_Error
869
-     */
870
-    public function get_all($query_params = array())
871
-    {
872
-        if (
873
-            isset($query_params['limit'])
874
-            && ! isset($query_params['group_by'])
875
-        ) {
876
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
-        }
878
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * Modifies the query parameters so we only get back model objects
885
-     * that "belong" to the current user
886
-     *
887
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
-     */
890
-    public function alter_query_params_to_only_include_mine($query_params = array())
891
-    {
892
-        $wp_user_field_name = $this->wp_user_field_name();
893
-        if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
-        }
896
-        return $query_params;
897
-    }
898
-
899
-
900
-
901
-    /**
902
-     * Returns the name of the field's name that points to the WP_User table
903
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
-     * foreign key to the WP_User table)
905
-     *
906
-     * @return string|boolean string on success, boolean false when there is no
907
-     * foreign key to the WP_User table
908
-     */
909
-    public function wp_user_field_name()
910
-    {
911
-        try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
913
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
-                $last_model_name = end($models_to_follow_to_wp_users);
915
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
-            } else {
918
-                $model_with_fk_to_wp_users = $this;
919
-                $model_chain_to_wp_user = '';
920
-            }
921
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
923
-        } catch (EE_Error $e) {
924
-            return false;
925
-        }
926
-    }
927
-
928
-
929
-
930
-    /**
931
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
932
-     * (or transiently-related model) has a foreign key to the wp_users table;
933
-     * useful for finding if model objects of this type are 'owned' by the current user.
934
-     * This is an empty string when the foreign key is on this model and when it isn't,
935
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
936
-     * (or transiently-related model)
937
-     *
938
-     * @return string
939
-     */
940
-    public function model_chain_to_wp_user()
941
-    {
942
-        return $this->_model_chain_to_wp_user;
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
-     * like how registrations don't have a foreign key to wp_users, but the
950
-     * events they are for are), or is unrelated to wp users.
951
-     * generally available
952
-     *
953
-     * @return boolean
954
-     */
955
-    public function is_owned()
956
-    {
957
-        if ($this->model_chain_to_wp_user()) {
958
-            return true;
959
-        }
960
-        try {
961
-            $this->get_foreign_key_to('WP_User');
962
-            return true;
963
-        } catch (EE_Error $e) {
964
-            return false;
965
-        }
966
-    }
967
-
968
-
969
-    /**
970
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
-     * the model)
973
-     *
974
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
-     *                                  fields on the model, and the models we joined to in the query. However, you can
978
-     *                                  override this and set the select to "*", or a specific column name, like
979
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
-     *                                  the aliases used to refer to this selection, and values are to be
982
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
-     * @throws EE_Error
986
-     * @throws InvalidArgumentException
987
-     */
988
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
-    {
990
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
-        ;
992
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
993
-        $select_expressions = $columns_to_select === null
994
-            ? $this->_construct_default_select_sql($model_query_info)
995
-            : '';
996
-        if ($this->_custom_selections instanceof CustomSelects) {
997
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
-            $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
1000
-                : $custom_expressions;
1001
-        }
1002
-
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
-     * method of including extra select information.
1012
-     *
1013
-     * @param array             $query_params
1014
-     * @param null|array|string $columns_to_select
1015
-     * @return null|CustomSelects
1016
-     * @throws InvalidArgumentException
1017
-     */
1018
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
-    {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
-            return null;
1022
-        }
1023
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
-        return new CustomSelects($selects);
1026
-    }
1027
-
1028
-
1029
-
1030
-    /**
1031
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1032
-     * but you can use the model query params to more easily
1033
-     * take care of joins, field preparation etc.
1034
-     *
1035
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1039
-     *                                  override this and set the select to "*", or a specific column name, like
1040
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
-     *                                  the aliases used to refer to this selection, and values are to be
1043
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
-     * @throws EE_Error
1047
-     */
1048
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
-    {
1050
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
-    }
1052
-
1053
-
1054
-
1055
-    /**
1056
-     * For creating a custom select statement
1057
-     *
1058
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
-     *                                 SQL, and 1=>is the datatype
1061
-     * @throws EE_Error
1062
-     * @return string
1063
-     */
1064
-    private function _construct_select_from_input($columns_to_select)
1065
-    {
1066
-        if (is_array($columns_to_select)) {
1067
-            $select_sql_array = array();
1068
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
-                    throw new EE_Error(
1071
-                        sprintf(
1072
-                            esc_html__(
1073
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
-                                'event_espresso'
1075
-                            ),
1076
-                            $selection_and_datatype,
1077
-                            $alias
1078
-                        )
1079
-                    );
1080
-                }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype[1],
1089
-                            $selection_and_datatype[0],
1090
-                            $alias,
1091
-                            implode(', ', $this->_valid_wpdb_data_types)
1092
-                        )
1093
-                    );
1094
-                }
1095
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
-            }
1097
-            $columns_to_select_string = implode(', ', $select_sql_array);
1098
-        } else {
1099
-            $columns_to_select_string = $columns_to_select;
1100
-        }
1101
-        return $columns_to_select_string;
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
-     *
1109
-     * @return string
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function primary_key_name()
1113
-    {
1114
-        return $this->get_primary_key_field()->get_name();
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
-     * If there is no primary key on this model, $id is treated as primary key string
1121
-     *
1122
-     * @param mixed $id int or string, depending on the type of the model's primary key
1123
-     * @return EE_Base_Class
1124
-     * @throws EE_Error
1125
-     */
1126
-    public function get_one_by_ID($id)
1127
-    {
1128
-        if ($this->get_from_entity_map($id)) {
1129
-            return $this->get_from_entity_map($id);
1130
-        }
1131
-        $model_object = $this->get_one(
1132
-            $this->alter_query_params_to_restrict_by_ID(
1133
-                $id,
1134
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
-            )
1136
-        );
1137
-        $className = $this->_get_class_name();
1138
-        if ($model_object instanceof $className) {
1139
-            // make sure valid objects get added to the entity map
1140
-            // so that the next call to this method doesn't trigger another trip to the db
1141
-            $this->add_to_entity_map($model_object);
1142
-        }
1143
-        return $model_object;
1144
-    }
1145
-
1146
-
1147
-
1148
-    /**
1149
-     * Alters query parameters to only get items with this ID are returned.
1150
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
-     * or could just be a simple primary key ID
1152
-     *
1153
-     * @param int   $id
1154
-     * @param array $query_params
1155
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
-     * @throws EE_Error
1157
-     */
1158
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
-    {
1160
-        if (! isset($query_params[0])) {
1161
-            $query_params[0] = array();
1162
-        }
1163
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1164
-        if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1166
-        } else {
1167
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1168
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
-        }
1170
-        return $query_params;
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
-     * array. If no item is found, null is returned.
1178
-     *
1179
-     * @param array $query_params like EEM_Base's $query_params variable.
1180
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
-     * @throws EE_Error
1182
-     */
1183
-    public function get_one($query_params = array())
1184
-    {
1185
-        if (! is_array($query_params)) {
1186
-            EE_Error::doing_it_wrong(
1187
-                'EEM_Base::get_one',
1188
-                sprintf(
1189
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
-                    gettype($query_params)
1191
-                ),
1192
-                '4.6.0'
1193
-            );
1194
-            $query_params = array();
1195
-        }
1196
-        $query_params['limit'] = 1;
1197
-        $items = $this->get_all($query_params);
1198
-        if (empty($items)) {
1199
-            return null;
1200
-        }
1201
-        return array_shift($items);
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Returns the next x number of items in sequence from the given value as
1208
-     * found in the database matching the given query conditions.
1209
-     *
1210
-     * @param mixed $current_field_value    Value used for the reference point.
1211
-     * @param null  $field_to_order_by      What field is used for the
1212
-     *                                      reference point.
1213
-     * @param int   $limit                  How many to return.
1214
-     * @param array $query_params           Extra conditions on the query.
1215
-     * @param null  $columns_to_select      If left null, then an array of
1216
-     *                                      EE_Base_Class objects is returned,
1217
-     *                                      otherwise you can indicate just the
1218
-     *                                      columns you want returned.
1219
-     * @return EE_Base_Class[]|array
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function next_x(
1223
-        $current_field_value,
1224
-        $field_to_order_by = null,
1225
-        $limit = 1,
1226
-        $query_params = array(),
1227
-        $columns_to_select = null
1228
-    ) {
1229
-        return $this->_get_consecutive(
1230
-            $current_field_value,
1231
-            '>',
1232
-            $field_to_order_by,
1233
-            $limit,
1234
-            $query_params,
1235
-            $columns_to_select
1236
-        );
1237
-    }
1238
-
1239
-
1240
-
1241
-    /**
1242
-     * Returns the previous x number of items in sequence from the given value
1243
-     * as found in the database matching the given query conditions.
1244
-     *
1245
-     * @param mixed $current_field_value    Value used for the reference point.
1246
-     * @param null  $field_to_order_by      What field is used for the
1247
-     *                                      reference point.
1248
-     * @param int   $limit                  How many to return.
1249
-     * @param array $query_params           Extra conditions on the query.
1250
-     * @param null  $columns_to_select      If left null, then an array of
1251
-     *                                      EE_Base_Class objects is returned,
1252
-     *                                      otherwise you can indicate just the
1253
-     *                                      columns you want returned.
1254
-     * @return EE_Base_Class[]|array
1255
-     * @throws EE_Error
1256
-     */
1257
-    public function previous_x(
1258
-        $current_field_value,
1259
-        $field_to_order_by = null,
1260
-        $limit = 1,
1261
-        $query_params = array(),
1262
-        $columns_to_select = null
1263
-    ) {
1264
-        return $this->_get_consecutive(
1265
-            $current_field_value,
1266
-            '<',
1267
-            $field_to_order_by,
1268
-            $limit,
1269
-            $query_params,
1270
-            $columns_to_select
1271
-        );
1272
-    }
1273
-
1274
-
1275
-
1276
-    /**
1277
-     * Returns the next item in sequence from the given value as found in the
1278
-     * database matching the given query conditions.
1279
-     *
1280
-     * @param mixed $current_field_value    Value used for the reference point.
1281
-     * @param null  $field_to_order_by      What field is used for the
1282
-     *                                      reference point.
1283
-     * @param array $query_params           Extra conditions on the query.
1284
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
-     *                                      object is returned, otherwise you
1286
-     *                                      can indicate just the columns you
1287
-     *                                      want and a single array indexed by
1288
-     *                                      the columns will be returned.
1289
-     * @return EE_Base_Class|null|array()
1290
-     * @throws EE_Error
1291
-     */
1292
-    public function next(
1293
-        $current_field_value,
1294
-        $field_to_order_by = null,
1295
-        $query_params = array(),
1296
-        $columns_to_select = null
1297
-    ) {
1298
-        $results = $this->_get_consecutive(
1299
-            $current_field_value,
1300
-            '>',
1301
-            $field_to_order_by,
1302
-            1,
1303
-            $query_params,
1304
-            $columns_to_select
1305
-        );
1306
-        return empty($results) ? null : reset($results);
1307
-    }
1308
-
1309
-
1310
-
1311
-    /**
1312
-     * Returns the previous item in sequence from the given value as found in
1313
-     * the database matching the given query conditions.
1314
-     *
1315
-     * @param mixed $current_field_value    Value used for the reference point.
1316
-     * @param null  $field_to_order_by      What field is used for the
1317
-     *                                      reference point.
1318
-     * @param array $query_params           Extra conditions on the query.
1319
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
-     *                                      object is returned, otherwise you
1321
-     *                                      can indicate just the columns you
1322
-     *                                      want and a single array indexed by
1323
-     *                                      the columns will be returned.
1324
-     * @return EE_Base_Class|null|array()
1325
-     * @throws EE_Error
1326
-     */
1327
-    public function previous(
1328
-        $current_field_value,
1329
-        $field_to_order_by = null,
1330
-        $query_params = array(),
1331
-        $columns_to_select = null
1332
-    ) {
1333
-        $results = $this->_get_consecutive(
1334
-            $current_field_value,
1335
-            '<',
1336
-            $field_to_order_by,
1337
-            1,
1338
-            $query_params,
1339
-            $columns_to_select
1340
-        );
1341
-        return empty($results) ? null : reset($results);
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * Returns the a consecutive number of items in sequence from the given
1348
-     * value as found in the database matching the given query conditions.
1349
-     *
1350
-     * @param mixed  $current_field_value   Value used for the reference point.
1351
-     * @param string $operand               What operand is used for the sequence.
1352
-     * @param string $field_to_order_by     What field is used for the reference point.
1353
-     * @param int    $limit                 How many to return.
1354
-     * @param array  $query_params          Extra conditions on the query.
1355
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
-     *                                      otherwise you can indicate just the columns you want returned.
1357
-     * @return EE_Base_Class[]|array
1358
-     * @throws EE_Error
1359
-     */
1360
-    protected function _get_consecutive(
1361
-        $current_field_value,
1362
-        $operand = '>',
1363
-        $field_to_order_by = null,
1364
-        $limit = 1,
1365
-        $query_params = array(),
1366
-        $columns_to_select = null
1367
-    ) {
1368
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
-        if (empty($field_to_order_by)) {
1370
-            if ($this->has_primary_key_field()) {
1371
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1372
-            } else {
1373
-                if (WP_DEBUG) {
1374
-                    throw new EE_Error(esc_html__(
1375
-                        '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).',
1376
-                        'event_espresso'
1377
-                    ));
1378
-                }
1379
-                EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
-                return array();
1381
-            }
1382
-        }
1383
-        if (! is_array($query_params)) {
1384
-            EE_Error::doing_it_wrong(
1385
-                'EEM_Base::_get_consecutive',
1386
-                sprintf(
1387
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
-                    gettype($query_params)
1389
-                ),
1390
-                '4.6.0'
1391
-            );
1392
-            $query_params = array();
1393
-        }
1394
-        // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
-        $query_params['limit'] = $limit;
1397
-        // set direction
1398
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
-        $query_params['order_by'] = $operand === '>'
1400
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
-        if (empty($columns_to_select)) {
1404
-            return $this->get_all($query_params);
1405
-        }
1406
-        // getting just the fields
1407
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
-    }
1409
-
1410
-
1411
-
1412
-    /**
1413
-     * This sets the _timezone property after model object has been instantiated.
1414
-     *
1415
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
-     */
1417
-    public function set_timezone($timezone)
1418
-    {
1419
-        if ($timezone !== null) {
1420
-            $this->_timezone = $timezone;
1421
-        }
1422
-        // note we need to loop through relations and set the timezone on those objects as well.
1423
-        foreach ($this->_model_relations as $relation) {
1424
-            $relation->set_timezone($timezone);
1425
-        }
1426
-        // and finally we do the same for any datetime fields
1427
-        foreach ($this->_fields as $field) {
1428
-            if ($field instanceof EE_Datetime_Field) {
1429
-                $field->set_timezone($timezone);
1430
-            }
1431
-        }
1432
-    }
1433
-
1434
-
1435
-
1436
-    /**
1437
-     * This just returns whatever is set for the current timezone.
1438
-     *
1439
-     * @access public
1440
-     * @return string
1441
-     */
1442
-    public function get_timezone()
1443
-    {
1444
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
-        if (empty($this->_timezone)) {
1446
-            foreach ($this->_fields as $field) {
1447
-                if ($field instanceof EE_Datetime_Field) {
1448
-                    $this->set_timezone($field->get_timezone());
1449
-                    break;
1450
-                }
1451
-            }
1452
-        }
1453
-        // if timezone STILL empty then return the default timezone for the site.
1454
-        if (empty($this->_timezone)) {
1455
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
-        }
1457
-        return $this->_timezone;
1458
-    }
1459
-
1460
-
1461
-
1462
-    /**
1463
-     * This returns the date formats set for the given field name and also ensures that
1464
-     * $this->_timezone property is set correctly.
1465
-     *
1466
-     * @since 4.6.x
1467
-     * @param string $field_name The name of the field the formats are being retrieved for.
1468
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
-     * @return array formats in an array with the date format first, and the time format last.
1471
-     */
1472
-    public function get_formats_for($field_name, $pretty = false)
1473
-    {
1474
-        $field_settings = $this->field_settings_for($field_name);
1475
-        // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1477
-            throw new EE_Error(sprintf(esc_html__(
1478
-                '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.',
1479
-                'event_espresso'
1480
-            ), $field_name));
1481
-        }
1482
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
-        // the field.
1484
-        $this->_timezone = $field_settings->get_timezone();
1485
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
-    }
1487
-
1488
-
1489
-
1490
-    /**
1491
-     * This returns the current time in a format setup for a query on this model.
1492
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
-     * it will return:
1494
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
-     *  NOW
1496
-     *  - or a unix timestamp (equivalent to time())
1497
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
-     * @since 4.6.x
1501
-     * @param string $field_name       The field the current time is needed for.
1502
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
-     *                                 formatted string matching the set format for the field in the set timezone will
1504
-     *                                 be returned.
1505
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
-     *                                 exception is triggered.
1509
-     */
1510
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
-    {
1512
-        $formats = $this->get_formats_for($field_name);
1513
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
-        if ($timestamp) {
1515
-            return $DateTime->format('U');
1516
-        }
1517
-        // not returning timestamp, so return formatted string in timezone.
1518
-        switch ($what) {
1519
-            case 'time':
1520
-                return $DateTime->format($formats[1]);
1521
-                break;
1522
-            case 'date':
1523
-                return $DateTime->format($formats[0]);
1524
-                break;
1525
-            default:
1526
-                return $DateTime->format(implode(' ', $formats));
1527
-                break;
1528
-        }
1529
-    }
1530
-
1531
-
1532
-
1533
-    /**
1534
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
-     * for the model are.  Returns a DateTime object.
1536
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
-     * ignored.
1539
-     *
1540
-     * @param string $field_name      The field being setup.
1541
-     * @param string $timestring      The date time string being used.
1542
-     * @param string $incoming_format The format for the time string.
1543
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
-     *                                format is
1546
-     *                                'U', this is ignored.
1547
-     * @return DateTime
1548
-     * @throws EE_Error
1549
-     */
1550
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
-    {
1552
-        // just using this to ensure the timezone is set correctly internally
1553
-        $this->get_formats_for($field_name);
1554
-        // load EEH_DTT_Helper
1555
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
-     *
1566
-     * @return EE_Table_Base[]
1567
-     */
1568
-    public function get_tables()
1569
-    {
1570
-        return $this->_tables;
1571
-    }
1572
-
1573
-
1574
-
1575
-    /**
1576
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
-     * model object with EVT_ID = 1
1582
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
-     * are not specified)
1587
-     *
1588
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1593
-     *                                         ID=34, we'd use this method as follows:
1594
-     *                                         EEM_Transaction::instance()->update(
1595
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
-     *                                         array(array('TXN_ID'=>34)));
1597
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
-     *                                         TRUE, it is assumed that you've already called
1604
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
-     *                                         malicious javascript. However, if
1606
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
-     *                                         and every other field, before insertion. We provide this parameter
1609
-     *                                         because model objects perform their prepare_for_set function on all
1610
-     *                                         their values, and so don't need to be called again (and in many cases,
1611
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
-     *                                         prepare_for_set method...)
1613
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
-     *                                         in this model's entity map according to $fields_n_values that match
1615
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1616
-     *                                         by setting this to FALSE, but be aware that model objects being used
1617
-     *                                         could get out-of-sync with the database
1618
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
-     *                                         bad)
1621
-     * @throws EE_Error
1622
-     */
1623
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
-    {
1625
-        if (! is_array($query_params)) {
1626
-            EE_Error::doing_it_wrong(
1627
-                'EEM_Base::update',
1628
-                sprintf(
1629
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
-                    gettype($query_params)
1631
-                ),
1632
-                '4.6.0'
1633
-            );
1634
-            $query_params = array();
1635
-        }
1636
-        /**
1637
-         * Action called before a model update call has been made.
1638
-         *
1639
-         * @param EEM_Base $model
1640
-         * @param array    $fields_n_values the updated fields and their new values
1641
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
-         */
1643
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
-        /**
1645
-         * Filters the fields about to be updated given the query parameters. You can provide the
1646
-         * $query_params to $this->get_all() to find exactly which records will be updated
1647
-         *
1648
-         * @param array    $fields_n_values fields and their new values
1649
-         * @param EEM_Base $model           the model being queried
1650
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
-         */
1652
-        $fields_n_values = (array) apply_filters(
1653
-            'FHEE__EEM_Base__update__fields_n_values',
1654
-            $fields_n_values,
1655
-            $this,
1656
-            $query_params
1657
-        );
1658
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
-        // to do that, for each table, verify that it's PK isn't null.
1660
-        $tables = $this->get_tables();
1661
-        // 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
1662
-        // NOTE: we should make this code more efficient by NOT querying twice
1663
-        // before the real update, but that needs to first go through ALPHA testing
1664
-        // as it's dangerous. says Mike August 8 2014
1665
-        // we want to make sure the default_where strategy is ignored
1666
-        $this->_ignore_where_strategy = true;
1667
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
-        foreach ($wpdb_select_results as $wpdb_result) {
1669
-            // type cast stdClass as array
1670
-            $wpdb_result = (array) $wpdb_result;
1671
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
-            if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
-            } else {
1675
-                // 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)
1676
-                $main_table_pk_value = null;
1677
-            }
1678
-            // 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
1679
-            // 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
1680
-            if (count($tables) > 1) {
1681
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
-                // in that table, and so we'll want to insert one
1683
-                foreach ($tables as $table_obj) {
1684
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
-                    // if there is no private key for this table on the results, it means there's no entry
1686
-                    // in this table, right? so insert a row in the current table, using any fields available
1687
-                    if (
1688
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1690
-                    ) {
1691
-                        $success = $this->_insert_into_specific_table(
1692
-                            $table_obj,
1693
-                            $fields_n_values,
1694
-                            $main_table_pk_value
1695
-                        );
1696
-                        // if we died here, report the error
1697
-                        if (! $success) {
1698
-                            return false;
1699
-                        }
1700
-                    }
1701
-                }
1702
-            }
1703
-            //              //and now check that if we have cached any models by that ID on the model, that
1704
-            //              //they also get updated properly
1705
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
-            //              if( $model_object ){
1707
-            //                  foreach( $fields_n_values as $field => $value ){
1708
-            //                      $model_object->set($field, $value);
1709
-            // let's make sure default_where strategy is followed now
1710
-            $this->_ignore_where_strategy = false;
1711
-        }
1712
-        // if we want to keep model objects in sync, AND
1713
-        // if this wasn't called from a model object (to update itself)
1714
-        // then we want to make sure we keep all the existing
1715
-        // model objects in sync with the db
1716
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
-            if ($this->has_primary_key_field()) {
1718
-                $model_objs_affected_ids = $this->get_col($query_params);
1719
-            } else {
1720
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
-                $model_objs_affected_ids = array();
1723
-                foreach ($models_affected_key_columns as $row) {
1724
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
-                }
1727
-            }
1728
-            if (! $model_objs_affected_ids) {
1729
-                // wait wait wait- if nothing was affected let's stop here
1730
-                return 0;
1731
-            }
1732
-            foreach ($model_objs_affected_ids as $id) {
1733
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
-                if ($model_obj_in_entity_map) {
1735
-                    foreach ($fields_n_values as $field => $new_value) {
1736
-                        $model_obj_in_entity_map->set($field, $new_value);
1737
-                    }
1738
-                }
1739
-            }
1740
-            // if there is a primary key on this model, we can now do a slight optimization
1741
-            if ($this->has_primary_key_field()) {
1742
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
-                $query_params = array(
1744
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
-                    'limit'                    => count($model_objs_affected_ids),
1746
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
-                );
1748
-            }
1749
-        }
1750
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
-        $SQL = "UPDATE "
1752
-               . $model_query_info->get_full_join_sql()
1753
-               . " SET "
1754
-               . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
-        /**
1758
-         * Action called after a model update call has been made.
1759
-         *
1760
-         * @param EEM_Base $model
1761
-         * @param array    $fields_n_values the updated fields and their new values
1762
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
-         * @param int      $rows_affected
1764
-         */
1765
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1767
-    }
1768
-
1769
-
1770
-
1771
-    /**
1772
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
-     * are teh values of the field specified (or by default the primary key field)
1774
-     * that matched the query params. Note that you should pass the name of the
1775
-     * model FIELD, not the database table's column name.
1776
-     *
1777
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
-     * @param string $field_to_select
1779
-     * @return array just like $wpdb->get_col()
1780
-     * @throws EE_Error
1781
-     */
1782
-    public function get_col($query_params = array(), $field_to_select = null)
1783
-    {
1784
-        if ($field_to_select) {
1785
-            $field = $this->field_settings_for($field_to_select);
1786
-        } elseif ($this->has_primary_key_field()) {
1787
-            $field = $this->get_primary_key_field();
1788
-        } else {
1789
-            // no primary key, just grab the first column
1790
-            $field = reset($this->field_settings());
1791
-        }
1792
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1793
-        $select_expressions = $field->get_qualified_column();
1794
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1795
-        return $this->_do_wpdb_query('get_col', array($SQL));
1796
-    }
1797
-
1798
-
1799
-
1800
-    /**
1801
-     * Returns a single column value for a single row from the database
1802
-     *
1803
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1804
-     * @param string $field_to_select @see EEM_Base::get_col()
1805
-     * @return string
1806
-     * @throws EE_Error
1807
-     */
1808
-    public function get_var($query_params = array(), $field_to_select = null)
1809
-    {
1810
-        $query_params['limit'] = 1;
1811
-        $col = $this->get_col($query_params, $field_to_select);
1812
-        if (! empty($col)) {
1813
-            return reset($col);
1814
-        }
1815
-        return null;
1816
-    }
1817
-
1818
-
1819
-
1820
-    /**
1821
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1822
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1823
-     * injection, but currently no further filtering is done
1824
-     *
1825
-     * @global      $wpdb
1826
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1827
-     *                               be updated to in the DB
1828
-     * @return string of SQL
1829
-     * @throws EE_Error
1830
-     */
1831
-    public function _construct_update_sql($fields_n_values)
1832
-    {
1833
-        /** @type WPDB $wpdb */
1834
-        global $wpdb;
1835
-        $cols_n_values = array();
1836
-        foreach ($fields_n_values as $field_name => $value) {
1837
-            $field_obj = $this->field_settings_for($field_name);
1838
-            // if the value is NULL, we want to assign the value to that.
1839
-            // wpdb->prepare doesn't really handle that properly
1840
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841
-            $value_sql = $prepared_value === null ? 'NULL'
1842
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1844
-        }
1845
-        return implode(",", $cols_n_values);
1846
-    }
1847
-
1848
-
1849
-
1850
-    /**
1851
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1852
-     * Performs a HARD delete, meaning the database row should always be removed,
1853
-     * not just have a flag field on it switched
1854
-     * Wrapper for EEM_Base::delete_permanently()
1855
-     *
1856
-     * @param mixed $id
1857
-     * @param boolean $allow_blocking
1858
-     * @return int the number of rows deleted
1859
-     * @throws EE_Error
1860
-     */
1861
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1862
-    {
1863
-        return $this->delete_permanently(
1864
-            array(
1865
-                array($this->get_primary_key_field()->get_name() => $id),
1866
-                'limit' => 1,
1867
-            ),
1868
-            $allow_blocking
1869
-        );
1870
-    }
1871
-
1872
-
1873
-
1874
-    /**
1875
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1876
-     * Wrapper for EEM_Base::delete()
1877
-     *
1878
-     * @param mixed $id
1879
-     * @param boolean $allow_blocking
1880
-     * @return int the number of rows deleted
1881
-     * @throws EE_Error
1882
-     */
1883
-    public function delete_by_ID($id, $allow_blocking = true)
1884
-    {
1885
-        return $this->delete(
1886
-            array(
1887
-                array($this->get_primary_key_field()->get_name() => $id),
1888
-                'limit' => 1,
1889
-            ),
1890
-            $allow_blocking
1891
-        );
1892
-    }
1893
-
1894
-
1895
-
1896
-    /**
1897
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1898
-     * meaning if the model has a field that indicates its been "trashed" or
1899
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1900
-     *
1901
-     * @see EEM_Base::delete_permanently
1902
-     * @param array   $query_params
1903
-     * @param boolean $allow_blocking
1904
-     * @return int how many rows got deleted
1905
-     * @throws EE_Error
1906
-     */
1907
-    public function delete($query_params, $allow_blocking = true)
1908
-    {
1909
-        return $this->delete_permanently($query_params, $allow_blocking);
1910
-    }
1911
-
1912
-
1913
-
1914
-    /**
1915
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1916
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1917
-     * as archived, not actually deleted
1918
-     *
1919
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1920
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1921
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1922
-     *                                deletes regardless of other objects which may depend on it. Its generally
1923
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1924
-     *                                DB
1925
-     * @return int how many rows got deleted
1926
-     * @throws EE_Error
1927
-     */
1928
-    public function delete_permanently($query_params, $allow_blocking = true)
1929
-    {
1930
-        /**
1931
-         * Action called just before performing a real deletion query. You can use the
1932
-         * model and its $query_params to find exactly which items will be deleted
1933
-         *
1934
-         * @param EEM_Base $model
1935
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1936
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1937
-         *                                 to block (prevent) this deletion
1938
-         */
1939
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1940
-        // some MySQL databases may be running safe mode, which may restrict
1941
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1942
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1943
-        // to delete them
1944
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1945
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1946
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1947
-            $columns_and_ids_for_deleting
1948
-        );
1949
-        /**
1950
-         * Allows client code to act on the items being deleted before the query is actually executed.
1951
-         *
1952
-         * @param EEM_Base $this  The model instance being acted on.
1953
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1954
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1955
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1956
-         *                                                  derived from the incoming query parameters.
1957
-         *                                                  @see details on the structure of this array in the phpdocs
1958
-         *                                                  for the `_get_ids_for_delete_method`
1959
-         *
1960
-         */
1961
-        do_action(
1962
-            'AHEE__EEM_Base__delete__before_query',
1963
-            $this,
1964
-            $query_params,
1965
-            $allow_blocking,
1966
-            $columns_and_ids_for_deleting
1967
-        );
1968
-        if ($deletion_where_query_part) {
1969
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1970
-            $table_aliases = array_keys($this->_tables);
1971
-            $SQL = "DELETE "
1972
-                   . implode(", ", $table_aliases)
1973
-                   . " FROM "
1974
-                   . $model_query_info->get_full_join_sql()
1975
-                   . " WHERE "
1976
-                   . $deletion_where_query_part;
1977
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1978
-        } else {
1979
-            $rows_deleted = 0;
1980
-        }
1981
-
1982
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1983
-        // there was no error with the delete query.
1984
-        if (
1985
-            $this->has_primary_key_field()
1986
-            && $rows_deleted !== false
1987
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1988
-        ) {
1989
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1990
-            foreach ($ids_for_removal as $id) {
1991
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1993
-                }
1994
-            }
1995
-
1996
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1997
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1998
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1999
-            // (although it is possible).
2000
-            // Note this can be skipped by using the provided filter and returning false.
2001
-            if (
2002
-                apply_filters(
2003
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2004
-                    ! $this instanceof EEM_Extra_Meta,
2005
-                    $this
2006
-                )
2007
-            ) {
2008
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2009
-                    0 => array(
2010
-                        'EXM_type' => $this->get_this_model_name(),
2011
-                        'OBJ_ID'   => array(
2012
-                            'IN',
2013
-                            $ids_for_removal
2014
-                        )
2015
-                    )
2016
-                ));
2017
-            }
2018
-        }
2019
-
2020
-        /**
2021
-         * Action called just after performing a real deletion query. Although at this point the
2022
-         * items should have been deleted
2023
-         *
2024
-         * @param EEM_Base $model
2025
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2026
-         * @param int      $rows_deleted
2027
-         */
2028
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
-        return $rows_deleted;// how many supposedly got deleted
2030
-    }
2031
-
2032
-
2033
-
2034
-    /**
2035
-     * Checks all the relations that throw error messages when there are blocking related objects
2036
-     * for related model objects. If there are any related model objects on those relations,
2037
-     * adds an EE_Error, and return true
2038
-     *
2039
-     * @param EE_Base_Class|int $this_model_obj_or_id
2040
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
-     *                                                 should be ignored when determining whether there are related
2042
-     *                                                 model objects which block this model object's deletion. Useful
2043
-     *                                                 if you know A is related to B and are considering deleting A,
2044
-     *                                                 but want to see if A has any other objects blocking its deletion
2045
-     *                                                 before removing the relation between A and B
2046
-     * @return boolean
2047
-     * @throws EE_Error
2048
-     */
2049
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
-    {
2051
-        // first, if $ignore_this_model_obj was supplied, get its model
2052
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
-            $ignored_model = $ignore_this_model_obj->get_model();
2054
-        } else {
2055
-            $ignored_model = null;
2056
-        }
2057
-        // now check all the relations of $this_model_obj_or_id and see if there
2058
-        // are any related model objects blocking it?
2059
-        $is_blocked = false;
2060
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2062
-                // if $ignore_this_model_obj was supplied, then for the query
2063
-                // on that model needs to be told to ignore $ignore_this_model_obj
2064
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
-                        array(
2067
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2068
-                                '!=',
2069
-                                $ignore_this_model_obj->ID(),
2070
-                            ),
2071
-                        ),
2072
-                    ));
2073
-                } else {
2074
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
-                }
2076
-                if ($related_model_objects) {
2077
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
-                    $is_blocked = true;
2079
-                }
2080
-            }
2081
-        }
2082
-        return $is_blocked;
2083
-    }
2084
-
2085
-
2086
-    /**
2087
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
-     * @param array $row_results_for_deleting
2089
-     * @param bool  $allow_blocking
2090
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
-     *                 deleted. Example:
2094
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2095
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
-     *                 where each element is a group of columns and values that get deleted. Example:
2097
-     *                      array(
2098
-     *                          0 => array(
2099
-     *                              'Term_Relationship.object_id' => 1
2100
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2101
-     *                          ),
2102
-     *                          1 => array(
2103
-     *                              'Term_Relationship.object_id' => 1
2104
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2105
-     *                          )
2106
-     *                      )
2107
-     * @throws EE_Error
2108
-     */
2109
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
-    {
2111
-        $ids_to_delete_indexed_by_column = array();
2112
-        if ($this->has_primary_key_field()) {
2113
-            $primary_table = $this->_get_main_table();
2114
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
-            $other_tables = $this->_get_other_tables();
2116
-            $ids_to_delete_indexed_by_column = $query = array();
2117
-            foreach ($row_results_for_deleting as $item_to_delete) {
2118
-                // before we mark this item for deletion,
2119
-                // make sure there's no related entities blocking its deletion (if we're checking)
2120
-                if (
2121
-                    $allow_blocking
2122
-                    && $this->delete_is_blocked_by_related_models(
2123
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2124
-                    )
2125
-                ) {
2126
-                    continue;
2127
-                }
2128
-                // primary table deletes
2129
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2132
-                }
2133
-            }
2134
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
-            $fields = $this->get_combined_primary_key_fields();
2136
-            foreach ($row_results_for_deleting as $item_to_delete) {
2137
-                $ids_to_delete_indexed_by_column_for_row = array();
2138
-                foreach ($fields as $cpk_field) {
2139
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2140
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2142
-                    }
2143
-                }
2144
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
-            }
2146
-        } else {
2147
-            // so there's no primary key and no combined key...
2148
-            // sorry, can't help you
2149
-            throw new EE_Error(
2150
-                sprintf(
2151
-                    esc_html__(
2152
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
-                        "event_espresso"
2154
-                    ),
2155
-                    get_class($this)
2156
-                )
2157
-            );
2158
-        }
2159
-        return $ids_to_delete_indexed_by_column;
2160
-    }
2161
-
2162
-
2163
-    /**
2164
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2165
-     * the corresponding query_part for the query performing the delete.
2166
-     *
2167
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2168
-     * @return string
2169
-     * @throws EE_Error
2170
-     */
2171
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2172
-    {
2173
-        $query_part = '';
2174
-        if (empty($ids_to_delete_indexed_by_column)) {
2175
-            return $query_part;
2176
-        } elseif ($this->has_primary_key_field()) {
2177
-            $query = array();
2178
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2180
-            }
2181
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
-            $ways_to_identify_a_row = array();
2184
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
-                $values_for_each_combined_primary_key_for_a_row = array();
2186
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
-                }
2189
-                $ways_to_identify_a_row[] = '('
2190
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
-                                            . ')';
2192
-            }
2193
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2194
-        }
2195
-        return $query_part;
2196
-    }
2197
-
2198
-
2199
-
2200
-    /**
2201
-     * Gets the model field by the fully qualified name
2202
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
-     * @return EE_Model_Field_Base
2204
-     */
2205
-    public function get_field_by_column($qualified_column_name)
2206
-    {
2207
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2208
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2209
-                return $field_obj;
2210
-            }
2211
-        }
2212
-        throw new EE_Error(
2213
-            sprintf(
2214
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
-                $this->get_this_model_name(),
2216
-                $qualified_column_name
2217
-            )
2218
-        );
2219
-    }
2220
-
2221
-
2222
-
2223
-    /**
2224
-     * Count all the rows that match criteria the model query params.
2225
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
-     * column
2227
-     *
2228
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2229
-     * @param string $field_to_count field on model to count by (not column name)
2230
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
-     *                               that by the setting $distinct to TRUE;
2232
-     * @return int
2233
-     * @throws EE_Error
2234
-     */
2235
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
-    {
2237
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
-        if ($field_to_count) {
2239
-            $field_obj = $this->field_settings_for($field_to_count);
2240
-            $column_to_count = $field_obj->get_qualified_column();
2241
-        } elseif ($this->has_primary_key_field()) {
2242
-            $pk_field_obj = $this->get_primary_key_field();
2243
-            $column_to_count = $pk_field_obj->get_qualified_column();
2244
-        } else {
2245
-            // there's no primary key
2246
-            // if we're counting distinct items, and there's no primary key,
2247
-            // we need to list out the columns for distinction;
2248
-            // otherwise we can just use star
2249
-            if ($distinct) {
2250
-                $columns_to_use = array();
2251
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2253
-                }
2254
-                $column_to_count = implode(',', $columns_to_use);
2255
-            } else {
2256
-                $column_to_count = '*';
2257
-            }
2258
-        }
2259
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262
-    }
2263
-
2264
-
2265
-
2266
-    /**
2267
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
-     *
2269
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2270
-     * @param string $field_to_sum name of field (array key in $_fields array)
2271
-     * @return float
2272
-     * @throws EE_Error
2273
-     */
2274
-    public function sum($query_params, $field_to_sum = null)
2275
-    {
2276
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
-        if ($field_to_sum) {
2278
-            $field_obj = $this->field_settings_for($field_to_sum);
2279
-        } else {
2280
-            $field_obj = $this->get_primary_key_field();
2281
-        }
2282
-        $column_to_count = $field_obj->get_qualified_column();
2283
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
-        $data_type = $field_obj->get_wpdb_data_type();
2286
-        if ($data_type === '%d' || $data_type === '%s') {
2287
-            return (float) $return_value;
2288
-        }
2289
-        // must be %f
2290
-        return (float) $return_value;
2291
-    }
2292
-
2293
-
2294
-
2295
-    /**
2296
-     * Just calls the specified method on $wpdb with the given arguments
2297
-     * Consolidates a little extra error handling code
2298
-     *
2299
-     * @param string $wpdb_method
2300
-     * @param array  $arguments_to_provide
2301
-     * @throws EE_Error
2302
-     * @global wpdb  $wpdb
2303
-     * @return mixed
2304
-     */
2305
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
-    {
2307
-        // if we're in maintenance mode level 2, DON'T run any queries
2308
-        // because level 2 indicates the database needs updating and
2309
-        // is probably out of sync with the code
2310
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
-            throw new EE_Error(sprintf(esc_html__(
2312
-                "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.",
2313
-                "event_espresso"
2314
-            )));
2315
-        }
2316
-        /** @type WPDB $wpdb */
2317
-        global $wpdb;
2318
-        if (! method_exists($wpdb, $wpdb_method)) {
2319
-            throw new EE_Error(sprintf(esc_html__(
2320
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2321
-                'event_espresso'
2322
-            ), $wpdb_method));
2323
-        }
2324
-        if (WP_DEBUG) {
2325
-            $old_show_errors_value = $wpdb->show_errors;
2326
-            $wpdb->show_errors(false);
2327
-        }
2328
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2329
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2330
-        if (WP_DEBUG) {
2331
-            $wpdb->show_errors($old_show_errors_value);
2332
-            if (! empty($wpdb->last_error)) {
2333
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334
-            }
2335
-            if ($result === false) {
2336
-                throw new EE_Error(sprintf(esc_html__(
2337
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2338
-                    'event_espresso'
2339
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2340
-            }
2341
-        } elseif ($result === false) {
2342
-            EE_Error::add_error(
2343
-                sprintf(
2344
-                    esc_html__(
2345
-                        '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"',
2346
-                        'event_espresso'
2347
-                    ),
2348
-                    $wpdb_method,
2349
-                    var_export($arguments_to_provide, true),
2350
-                    $wpdb->last_error
2351
-                ),
2352
-                __FILE__,
2353
-                __FUNCTION__,
2354
-                __LINE__
2355
-            );
2356
-        }
2357
-        return $result;
2358
-    }
2359
-
2360
-
2361
-
2362
-    /**
2363
-     * Attempts to run the indicated WPDB method with the provided arguments,
2364
-     * and if there's an error tries to verify the DB is correct. Uses
2365
-     * the static property EEM_Base::$_db_verification_level to determine whether
2366
-     * we should try to fix the EE core db, the addons, or just give up
2367
-     *
2368
-     * @param string $wpdb_method
2369
-     * @param array  $arguments_to_provide
2370
-     * @return mixed
2371
-     */
2372
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2373
-    {
2374
-        /** @type WPDB $wpdb */
2375
-        global $wpdb;
2376
-        $wpdb->last_error = null;
2377
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2378
-        // was there an error running the query? but we don't care on new activations
2379
-        // (we're going to setup the DB anyway on new activations)
2380
-        if (
2381
-            ($result === false || ! empty($wpdb->last_error))
2382
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2383
-        ) {
2384
-            switch (EEM_Base::$_db_verification_level) {
2385
-                case EEM_Base::db_verified_none:
2386
-                    // let's double-check core's DB
2387
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2388
-                    break;
2389
-                case EEM_Base::db_verified_core:
2390
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2391
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2392
-                    break;
2393
-                case EEM_Base::db_verified_addons:
2394
-                    // ummmm... you in trouble
2395
-                    return $result;
2396
-                    break;
2397
-            }
2398
-            if (! empty($error_message)) {
2399
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400
-                trigger_error($error_message);
2401
-            }
2402
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2403
-        }
2404
-        return $result;
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Verifies the EE core database is up-to-date and records that we've done it on
2411
-     * EEM_Base::$_db_verification_level
2412
-     *
2413
-     * @param string $wpdb_method
2414
-     * @param array  $arguments_to_provide
2415
-     * @return string
2416
-     */
2417
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2418
-    {
2419
-        /** @type WPDB $wpdb */
2420
-        global $wpdb;
2421
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2422
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2423
-        $error_message = sprintf(
2424
-            esc_html__(
2425
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2426
-                'event_espresso'
2427
-            ),
2428
-            $wpdb->last_error,
2429
-            $wpdb_method,
2430
-            wp_json_encode($arguments_to_provide)
2431
-        );
2432
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2433
-        return $error_message;
2434
-    }
2435
-
2436
-
2437
-
2438
-    /**
2439
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2440
-     * EEM_Base::$_db_verification_level
2441
-     *
2442
-     * @param $wpdb_method
2443
-     * @param $arguments_to_provide
2444
-     * @return string
2445
-     */
2446
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2447
-    {
2448
-        /** @type WPDB $wpdb */
2449
-        global $wpdb;
2450
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2451
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2452
-        $error_message = sprintf(
2453
-            esc_html__(
2454
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
-                'event_espresso'
2456
-            ),
2457
-            $wpdb->last_error,
2458
-            $wpdb_method,
2459
-            wp_json_encode($arguments_to_provide)
2460
-        );
2461
-        EE_System::instance()->initialize_addons();
2462
-        return $error_message;
2463
-    }
2464
-
2465
-
2466
-
2467
-    /**
2468
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2469
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2470
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2471
-     * ..."
2472
-     *
2473
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2474
-     * @return string
2475
-     */
2476
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477
-    {
2478
-        return " FROM " . $model_query_info->get_full_join_sql() .
2479
-               $model_query_info->get_where_sql() .
2480
-               $model_query_info->get_group_by_sql() .
2481
-               $model_query_info->get_having_sql() .
2482
-               $model_query_info->get_order_by_sql() .
2483
-               $model_query_info->get_limit_sql();
2484
-    }
2485
-
2486
-
2487
-
2488
-    /**
2489
-     * Set to easily debug the next X queries ran from this model.
2490
-     *
2491
-     * @param int $count
2492
-     */
2493
-    public function show_next_x_db_queries($count = 1)
2494
-    {
2495
-        $this->_show_next_x_db_queries = $count;
2496
-    }
2497
-
2498
-
2499
-
2500
-    /**
2501
-     * @param $sql_query
2502
-     */
2503
-    public function show_db_query_if_previously_requested($sql_query)
2504
-    {
2505
-        if ($this->_show_next_x_db_queries > 0) {
2506
-            echo esc_html($sql_query);
2507
-            $this->_show_next_x_db_queries--;
2508
-        }
2509
-    }
2510
-
2511
-
2512
-
2513
-    /**
2514
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2515
-     * There are the 3 cases:
2516
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2517
-     * $otherModelObject has no ID, it is first saved.
2518
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2519
-     * has no ID, it is first saved.
2520
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2521
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2522
-     * join table
2523
-     *
2524
-     * @param        EE_Base_Class                     /int $thisModelObject
2525
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2526
-     * @param string $relationName                     , key in EEM_Base::_relations
2527
-     *                                                 an attendee to a group, you also want to specify which role they
2528
-     *                                                 will have in that group. So you would use this parameter to
2529
-     *                                                 specify array('role-column-name'=>'role-id')
2530
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2531
-     *                                                 to for relation to methods that allow you to further specify
2532
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2533
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2534
-     *                                                 because these will be inserted in any new rows created as well.
2535
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2536
-     * @throws EE_Error
2537
-     */
2538
-    public function add_relationship_to(
2539
-        $id_or_obj,
2540
-        $other_model_id_or_obj,
2541
-        $relationName,
2542
-        $extra_join_model_fields_n_values = array()
2543
-    ) {
2544
-        $relation_obj = $this->related_settings_for($relationName);
2545
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2546
-    }
2547
-
2548
-
2549
-
2550
-    /**
2551
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2552
-     * There are the 3 cases:
2553
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2554
-     * error
2555
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2556
-     * an error
2557
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2558
-     *
2559
-     * @param        EE_Base_Class /int $id_or_obj
2560
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2561
-     * @param string $relationName key in EEM_Base::_relations
2562
-     * @return boolean of success
2563
-     * @throws EE_Error
2564
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2565
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2566
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2567
-     *                             because these will be inserted in any new rows created as well.
2568
-     */
2569
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2570
-    {
2571
-        $relation_obj = $this->related_settings_for($relationName);
2572
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2573
-    }
2574
-
2575
-
2576
-
2577
-    /**
2578
-     * @param mixed           $id_or_obj
2579
-     * @param string          $relationName
2580
-     * @param array           $where_query_params
2581
-     * @param EE_Base_Class[] objects to which relations were removed
2582
-     * @return \EE_Base_Class[]
2583
-     * @throws EE_Error
2584
-     */
2585
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2586
-    {
2587
-        $relation_obj = $this->related_settings_for($relationName);
2588
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2589
-    }
2590
-
2591
-
2592
-
2593
-    /**
2594
-     * Gets all the related items of the specified $model_name, using $query_params.
2595
-     * Note: by default, we remove the "default query params"
2596
-     * because we want to get even deleted items etc.
2597
-     *
2598
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2599
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2600
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2601
-     * @return EE_Base_Class[]
2602
-     * @throws EE_Error
2603
-     */
2604
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2605
-    {
2606
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2607
-        $relation_settings = $this->related_settings_for($model_name);
2608
-        return $relation_settings->get_all_related($model_obj, $query_params);
2609
-    }
2610
-
2611
-
2612
-
2613
-    /**
2614
-     * Deletes all the model objects across the relation indicated by $model_name
2615
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2616
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2617
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2618
-     *
2619
-     * @param EE_Base_Class|int|string $id_or_obj
2620
-     * @param string                   $model_name
2621
-     * @param array                    $query_params
2622
-     * @return int how many deleted
2623
-     * @throws EE_Error
2624
-     */
2625
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2626
-    {
2627
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2628
-        $relation_settings = $this->related_settings_for($model_name);
2629
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2630
-    }
2631
-
2632
-
2633
-
2634
-    /**
2635
-     * Hard deletes all the model objects across the relation indicated by $model_name
2636
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2637
-     * the model objects can't be hard deleted because of blocking related model objects,
2638
-     * just does a soft-delete on them instead.
2639
-     *
2640
-     * @param EE_Base_Class|int|string $id_or_obj
2641
-     * @param string                   $model_name
2642
-     * @param array                    $query_params
2643
-     * @return int how many deleted
2644
-     * @throws EE_Error
2645
-     */
2646
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2647
-    {
2648
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2649
-        $relation_settings = $this->related_settings_for($model_name);
2650
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2651
-    }
2652
-
2653
-
2654
-
2655
-    /**
2656
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2657
-     * unless otherwise specified in the $query_params
2658
-     *
2659
-     * @param        int             /EE_Base_Class $id_or_obj
2660
-     * @param string $model_name     like 'Event', or 'Registration'
2661
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2662
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2663
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2664
-     *                               that by the setting $distinct to TRUE;
2665
-     * @return int
2666
-     * @throws EE_Error
2667
-     */
2668
-    public function count_related(
2669
-        $id_or_obj,
2670
-        $model_name,
2671
-        $query_params = array(),
2672
-        $field_to_count = null,
2673
-        $distinct = false
2674
-    ) {
2675
-        $related_model = $this->get_related_model_obj($model_name);
2676
-        // we're just going to use the query params on the related model's normal get_all query,
2677
-        // except add a condition to say to match the current mod
2678
-        if (! isset($query_params['default_where_conditions'])) {
2679
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680
-        }
2681
-        $this_model_name = $this->get_this_model_name();
2682
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2684
-        return $related_model->count($query_params, $field_to_count, $distinct);
2685
-    }
2686
-
2687
-
2688
-
2689
-    /**
2690
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2691
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2692
-     *
2693
-     * @param        int           /EE_Base_Class $id_or_obj
2694
-     * @param string $model_name   like 'Event', or 'Registration'
2695
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2696
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2697
-     * @return float
2698
-     * @throws EE_Error
2699
-     */
2700
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701
-    {
2702
-        $related_model = $this->get_related_model_obj($model_name);
2703
-        if (! is_array($query_params)) {
2704
-            EE_Error::doing_it_wrong(
2705
-                'EEM_Base::sum_related',
2706
-                sprintf(
2707
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2708
-                    gettype($query_params)
2709
-                ),
2710
-                '4.6.0'
2711
-            );
2712
-            $query_params = array();
2713
-        }
2714
-        // we're just going to use the query params on the related model's normal get_all query,
2715
-        // except add a condition to say to match the current mod
2716
-        if (! isset($query_params['default_where_conditions'])) {
2717
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718
-        }
2719
-        $this_model_name = $this->get_this_model_name();
2720
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2722
-        return $related_model->sum($query_params, $field_to_sum);
2723
-    }
2724
-
2725
-
2726
-
2727
-    /**
2728
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2729
-     * $modelObject
2730
-     *
2731
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2732
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2733
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2734
-     * @return EE_Base_Class
2735
-     * @throws EE_Error
2736
-     */
2737
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2738
-    {
2739
-        $query_params['limit'] = 1;
2740
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2741
-        if ($results) {
2742
-            return array_shift($results);
2743
-        }
2744
-        return null;
2745
-    }
2746
-
2747
-
2748
-
2749
-    /**
2750
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2751
-     *
2752
-     * @return string
2753
-     */
2754
-    public function get_this_model_name()
2755
-    {
2756
-        return str_replace("EEM_", "", get_class($this));
2757
-    }
2758
-
2759
-
2760
-
2761
-    /**
2762
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2763
-     *
2764
-     * @return EE_Any_Foreign_Model_Name_Field
2765
-     * @throws EE_Error
2766
-     */
2767
-    public function get_field_containing_related_model_name()
2768
-    {
2769
-        foreach ($this->field_settings(true) as $field) {
2770
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2771
-                $field_with_model_name = $field;
2772
-            }
2773
-        }
2774
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2775
-            throw new EE_Error(sprintf(
2776
-                esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777
-                $this->get_this_model_name()
2778
-            ));
2779
-        }
2780
-        return $field_with_model_name;
2781
-    }
2782
-
2783
-
2784
-
2785
-    /**
2786
-     * Inserts a new entry into the database, for each table.
2787
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2788
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2789
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2790
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2791
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2792
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2793
-     *
2794
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2795
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2796
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2797
-     *                              of EEM_Base)
2798
-     * @return int|string new primary key on main table that got inserted
2799
-     * @throws EE_Error
2800
-     */
2801
-    public function insert($field_n_values)
2802
-    {
2803
-        /**
2804
-         * Filters the fields and their values before inserting an item using the models
2805
-         *
2806
-         * @param array    $fields_n_values keys are the fields and values are their new values
2807
-         * @param EEM_Base $model           the model used
2808
-         */
2809
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2810
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2811
-            $main_table = $this->_get_main_table();
2812
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2813
-            if ($new_id !== false) {
2814
-                foreach ($this->_get_other_tables() as $other_table) {
2815
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2816
-                }
2817
-            }
2818
-            /**
2819
-             * Done just after attempting to insert a new model object
2820
-             *
2821
-             * @param EEM_Base   $model           used
2822
-             * @param array      $fields_n_values fields and their values
2823
-             * @param int|string the              ID of the newly-inserted model object
2824
-             */
2825
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2826
-            return $new_id;
2827
-        }
2828
-        return false;
2829
-    }
2830
-
2831
-
2832
-
2833
-    /**
2834
-     * Checks that the result would satisfy the unique indexes on this model
2835
-     *
2836
-     * @param array  $field_n_values
2837
-     * @param string $action
2838
-     * @return boolean
2839
-     * @throws EE_Error
2840
-     */
2841
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2842
-    {
2843
-        foreach ($this->unique_indexes() as $index_name => $index) {
2844
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2845
-            if ($this->exists(array($uniqueness_where_params))) {
2846
-                EE_Error::add_error(
2847
-                    sprintf(
2848
-                        esc_html__(
2849
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2850
-                            "event_espresso"
2851
-                        ),
2852
-                        $action,
2853
-                        $this->_get_class_name(),
2854
-                        $index_name,
2855
-                        implode(",", $index->field_names()),
2856
-                        http_build_query($uniqueness_where_params)
2857
-                    ),
2858
-                    __FILE__,
2859
-                    __FUNCTION__,
2860
-                    __LINE__
2861
-                );
2862
-                return false;
2863
-            }
2864
-        }
2865
-        return true;
2866
-    }
2867
-
2868
-
2869
-
2870
-    /**
2871
-     * Checks the database for an item that conflicts (ie, if this item were
2872
-     * saved to the DB would break some uniqueness requirement, like a primary key
2873
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2874
-     * can be either an EE_Base_Class or an array of fields n values
2875
-     *
2876
-     * @param EE_Base_Class|array $obj_or_fields_array
2877
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2878
-     *                                                 when looking for conflicts
2879
-     *                                                 (ie, if false, we ignore the model object's primary key
2880
-     *                                                 when finding "conflicts". If true, it's also considered).
2881
-     *                                                 Only works for INT primary key,
2882
-     *                                                 STRING primary keys cannot be ignored
2883
-     * @throws EE_Error
2884
-     * @return EE_Base_Class|array
2885
-     */
2886
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2887
-    {
2888
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2889
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2890
-        } elseif (is_array($obj_or_fields_array)) {
2891
-            $fields_n_values = $obj_or_fields_array;
2892
-        } else {
2893
-            throw new EE_Error(
2894
-                sprintf(
2895
-                    esc_html__(
2896
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2897
-                        "event_espresso"
2898
-                    ),
2899
-                    get_class($this),
2900
-                    $obj_or_fields_array
2901
-                )
2902
-            );
2903
-        }
2904
-        $query_params = array();
2905
-        if (
2906
-            $this->has_primary_key_field()
2907
-            && ($include_primary_key
2908
-                || $this->get_primary_key_field()
2909
-                   instanceof
2910
-                   EE_Primary_Key_String_Field)
2911
-            && isset($fields_n_values[ $this->primary_key_name() ])
2912
-        ) {
2913
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2914
-        }
2915
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2918
-        }
2919
-        // if there is nothing to base this search on, then we shouldn't find anything
2920
-        if (empty($query_params)) {
2921
-            return array();
2922
-        }
2923
-        return $this->get_one($query_params);
2924
-    }
2925
-
2926
-
2927
-
2928
-    /**
2929
-     * Like count, but is optimized and returns a boolean instead of an int
2930
-     *
2931
-     * @param array $query_params
2932
-     * @return boolean
2933
-     * @throws EE_Error
2934
-     */
2935
-    public function exists($query_params)
2936
-    {
2937
-        $query_params['limit'] = 1;
2938
-        return $this->count($query_params) > 0;
2939
-    }
2940
-
2941
-
2942
-
2943
-    /**
2944
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2945
-     *
2946
-     * @param int|string $id
2947
-     * @return boolean
2948
-     * @throws EE_Error
2949
-     */
2950
-    public function exists_by_ID($id)
2951
-    {
2952
-        return $this->exists(
2953
-            array(
2954
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2955
-                array(
2956
-                    $this->primary_key_name() => $id,
2957
-                ),
2958
-            )
2959
-        );
2960
-    }
2961
-
2962
-
2963
-
2964
-    /**
2965
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2966
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2967
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2968
-     * on the main table)
2969
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2970
-     * cases where we want to call it directly rather than via insert().
2971
-     *
2972
-     * @access   protected
2973
-     * @param EE_Table_Base $table
2974
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2975
-     *                                       float
2976
-     * @param int           $new_id          for now we assume only int keys
2977
-     * @throws EE_Error
2978
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2979
-     * @return int ID of new row inserted, or FALSE on failure
2980
-     */
2981
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2982
-    {
2983
-        global $wpdb;
2984
-        $insertion_col_n_values = array();
2985
-        $format_for_insertion = array();
2986
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2987
-        foreach ($fields_on_table as $field_name => $field_obj) {
2988
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2989
-            if ($field_obj->is_auto_increment()) {
2990
-                continue;
2991
-            }
2992
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2994
-            if ($prepared_value !== null) {
2995
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2996
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997
-            }
2998
-        }
2999
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3000
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3001
-            // so add the fk to the main table as a column
3002
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
-        }
3005
-        // insert the new entry
3006
-        $result = $this->_do_wpdb_query(
3007
-            'insert',
3008
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3009
-        );
3010
-        if ($result === false) {
3011
-            return false;
3012
-        }
3013
-        // ok, now what do we return for the ID of the newly-inserted thing?
3014
-        if ($this->has_primary_key_field()) {
3015
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3016
-                return $wpdb->insert_id;
3017
-            }
3018
-            // it's not an auto-increment primary key, so
3019
-            // it must have been supplied
3020
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3021
-        }
3022
-        // we can't return a  primary key because there is none. instead return
3023
-        // a unique string indicating this model
3024
-        return $this->get_index_primary_key_string($fields_n_values);
3025
-    }
3026
-
3027
-
3028
-
3029
-    /**
3030
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3031
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3032
-     * and there is no default, we pass it along. WPDB will take care of it)
3033
-     *
3034
-     * @param EE_Model_Field_Base $field_obj
3035
-     * @param array               $fields_n_values
3036
-     * @return mixed string|int|float depending on what the table column will be expecting
3037
-     * @throws EE_Error
3038
-     */
3039
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3040
-    {
3041
-        // if this field doesn't allow nullable, don't allow it
3042
-        if (
3043
-            ! $field_obj->is_nullable()
3044
-            && (
3045
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3046
-                || $fields_n_values[ $field_obj->get_name() ] === null
3047
-            )
3048
-        ) {
3049
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3050
-        }
3051
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
-            ? $fields_n_values[ $field_obj->get_name() ]
3053
-            : null;
3054
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055
-    }
3056
-
3057
-
3058
-
3059
-    /**
3060
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3061
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3062
-     * the field's prepare_for_set() method.
3063
-     *
3064
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3065
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3066
-     *                                   top of file)
3067
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3068
-     *                                   $value is a custom selection
3069
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3070
-     */
3071
-    private function _prepare_value_for_use_in_db($value, $field)
3072
-    {
3073
-        if ($field && $field instanceof EE_Model_Field_Base) {
3074
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3075
-            switch ($this->_values_already_prepared_by_model_object) {
3076
-                /** @noinspection PhpMissingBreakStatementInspection */
3077
-                case self::not_prepared_by_model_object:
3078
-                    $value = $field->prepare_for_set($value);
3079
-                // purposefully left out "return"
3080
-                case self::prepared_by_model_object:
3081
-                    /** @noinspection SuspiciousAssignmentsInspection */
3082
-                    $value = $field->prepare_for_use_in_db($value);
3083
-                case self::prepared_for_use_in_db:
3084
-                    // leave the value alone
3085
-            }
3086
-            return $value;
3087
-            // phpcs:enable
3088
-        }
3089
-        return $value;
3090
-    }
3091
-
3092
-
3093
-
3094
-    /**
3095
-     * Returns the main table on this model
3096
-     *
3097
-     * @return EE_Primary_Table
3098
-     * @throws EE_Error
3099
-     */
3100
-    protected function _get_main_table()
3101
-    {
3102
-        foreach ($this->_tables as $table) {
3103
-            if ($table instanceof EE_Primary_Table) {
3104
-                return $table;
3105
-            }
3106
-        }
3107
-        throw new EE_Error(sprintf(esc_html__(
3108
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3109
-            'event_espresso'
3110
-        ), get_class($this)));
3111
-    }
3112
-
3113
-
3114
-
3115
-    /**
3116
-     * table
3117
-     * returns EE_Primary_Table table name
3118
-     *
3119
-     * @return string
3120
-     * @throws EE_Error
3121
-     */
3122
-    public function table()
3123
-    {
3124
-        return $this->_get_main_table()->get_table_name();
3125
-    }
3126
-
3127
-
3128
-
3129
-    /**
3130
-     * table
3131
-     * returns first EE_Secondary_Table table name
3132
-     *
3133
-     * @return string
3134
-     */
3135
-    public function second_table()
3136
-    {
3137
-        // grab second table from tables array
3138
-        $second_table = end($this->_tables);
3139
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3140
-    }
3141
-
3142
-
3143
-
3144
-    /**
3145
-     * get_table_obj_by_alias
3146
-     * returns table name given it's alias
3147
-     *
3148
-     * @param string $table_alias
3149
-     * @return EE_Primary_Table | EE_Secondary_Table
3150
-     */
3151
-    public function get_table_obj_by_alias($table_alias = '')
3152
-    {
3153
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3160
-     *
3161
-     * @return EE_Secondary_Table[]
3162
-     */
3163
-    protected function _get_other_tables()
3164
-    {
3165
-        $other_tables = array();
3166
-        foreach ($this->_tables as $table_alias => $table) {
3167
-            if ($table instanceof EE_Secondary_Table) {
3168
-                $other_tables[ $table_alias ] = $table;
3169
-            }
3170
-        }
3171
-        return $other_tables;
3172
-    }
3173
-
3174
-
3175
-
3176
-    /**
3177
-     * Finds all the fields that correspond to the given table
3178
-     *
3179
-     * @param string $table_alias , array key in EEM_Base::_tables
3180
-     * @return EE_Model_Field_Base[]
3181
-     */
3182
-    public function _get_fields_for_table($table_alias)
3183
-    {
3184
-        return $this->_fields[ $table_alias ];
3185
-    }
3186
-
3187
-
3188
-
3189
-    /**
3190
-     * Recurses through all the where parameters, and finds all the related models we'll need
3191
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3192
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3193
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3194
-     * related Registration, Transaction, and Payment models.
3195
-     *
3196
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3197
-     * @return EE_Model_Query_Info_Carrier
3198
-     * @throws EE_Error
3199
-     */
3200
-    public function _extract_related_models_from_query($query_params)
3201
-    {
3202
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3203
-        if (array_key_exists(0, $query_params)) {
3204
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3205
-        }
3206
-        if (array_key_exists('group_by', $query_params)) {
3207
-            if (is_array($query_params['group_by'])) {
3208
-                $this->_extract_related_models_from_sub_params_array_values(
3209
-                    $query_params['group_by'],
3210
-                    $query_info_carrier,
3211
-                    'group_by'
3212
-                );
3213
-            } elseif (! empty($query_params['group_by'])) {
3214
-                $this->_extract_related_model_info_from_query_param(
3215
-                    $query_params['group_by'],
3216
-                    $query_info_carrier,
3217
-                    'group_by'
3218
-                );
3219
-            }
3220
-        }
3221
-        if (array_key_exists('having', $query_params)) {
3222
-            $this->_extract_related_models_from_sub_params_array_keys(
3223
-                $query_params[0],
3224
-                $query_info_carrier,
3225
-                'having'
3226
-            );
3227
-        }
3228
-        if (array_key_exists('order_by', $query_params)) {
3229
-            if (is_array($query_params['order_by'])) {
3230
-                $this->_extract_related_models_from_sub_params_array_keys(
3231
-                    $query_params['order_by'],
3232
-                    $query_info_carrier,
3233
-                    'order_by'
3234
-                );
3235
-            } elseif (! empty($query_params['order_by'])) {
3236
-                $this->_extract_related_model_info_from_query_param(
3237
-                    $query_params['order_by'],
3238
-                    $query_info_carrier,
3239
-                    'order_by'
3240
-                );
3241
-            }
3242
-        }
3243
-        if (array_key_exists('force_join', $query_params)) {
3244
-            $this->_extract_related_models_from_sub_params_array_values(
3245
-                $query_params['force_join'],
3246
-                $query_info_carrier,
3247
-                'force_join'
3248
-            );
3249
-        }
3250
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3251
-        return $query_info_carrier;
3252
-    }
3253
-
3254
-
3255
-
3256
-    /**
3257
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3258
-     *
3259
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3260
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3261
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3262
-     * @throws EE_Error
3263
-     * @return \EE_Model_Query_Info_Carrier
3264
-     */
3265
-    private function _extract_related_models_from_sub_params_array_keys(
3266
-        $sub_query_params,
3267
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268
-        $query_param_type
3269
-    ) {
3270
-        if (! empty($sub_query_params)) {
3271
-            $sub_query_params = (array) $sub_query_params;
3272
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3274
-                $this->_extract_related_model_info_from_query_param(
3275
-                    $param,
3276
-                    $model_query_info_carrier,
3277
-                    $query_param_type
3278
-                );
3279
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
-                // of array('Registration.TXN_ID'=>23)
3283
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3286
-                        throw new EE_Error(sprintf(
3287
-                            esc_html__(
3288
-                                "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'))",
3289
-                                "event_espresso"
3290
-                            ),
3291
-                            $param,
3292
-                            $possibly_array_of_params
3293
-                        ));
3294
-                    }
3295
-                    $this->_extract_related_models_from_sub_params_array_keys(
3296
-                        $possibly_array_of_params,
3297
-                        $model_query_info_carrier,
3298
-                        $query_param_type
3299
-                    );
3300
-                } elseif (
3301
-                    $query_param_type === 0 // ie WHERE
3302
-                          && is_array($possibly_array_of_params)
3303
-                          && isset($possibly_array_of_params[2])
3304
-                          && $possibly_array_of_params[2] == true
3305
-                ) {
3306
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3308
-                    // from which we should extract query parameters!
3309
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310
-                        throw new EE_Error(sprintf(esc_html__(
3311
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312
-                            "event_espresso"
3313
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3314
-                    }
3315
-                    $this->_extract_related_model_info_from_query_param(
3316
-                        $possibly_array_of_params[1],
3317
-                        $model_query_info_carrier,
3318
-                        $query_param_type
3319
-                    );
3320
-                }
3321
-            }
3322
-        }
3323
-        return $model_query_info_carrier;
3324
-    }
3325
-
3326
-
3327
-
3328
-    /**
3329
-     * For extracting related models from forced_joins, where the array values contain the info about what
3330
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3331
-     *
3332
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3333
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3334
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3335
-     * @throws EE_Error
3336
-     * @return \EE_Model_Query_Info_Carrier
3337
-     */
3338
-    private function _extract_related_models_from_sub_params_array_values(
3339
-        $sub_query_params,
3340
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341
-        $query_param_type
3342
-    ) {
3343
-        if (! empty($sub_query_params)) {
3344
-            if (! is_array($sub_query_params)) {
3345
-                throw new EE_Error(sprintf(
3346
-                    esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347
-                    $sub_query_params
3348
-                ));
3349
-            }
3350
-            foreach ($sub_query_params as $param) {
3351
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3352
-                $this->_extract_related_model_info_from_query_param(
3353
-                    $param,
3354
-                    $model_query_info_carrier,
3355
-                    $query_param_type
3356
-                );
3357
-            }
3358
-        }
3359
-        return $model_query_info_carrier;
3360
-    }
3361
-
3362
-
3363
-    /**
3364
-     * Extract all the query parts from  model query params
3365
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3366
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3367
-     * but use them in a different order. Eg, we need to know what models we are querying
3368
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3369
-     * other models before we can finalize the where clause SQL.
3370
-     *
3371
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3372
-     * @throws EE_Error
3373
-     * @return EE_Model_Query_Info_Carrier
3374
-     * @throws ModelConfigurationException
3375
-     */
3376
-    public function _create_model_query_info_carrier($query_params)
3377
-    {
3378
-        if (! is_array($query_params)) {
3379
-            EE_Error::doing_it_wrong(
3380
-                'EEM_Base::_create_model_query_info_carrier',
3381
-                sprintf(
3382
-                    esc_html__(
3383
-                        '$query_params should be an array, you passed a variable of type %s',
3384
-                        'event_espresso'
3385
-                    ),
3386
-                    gettype($query_params)
3387
-                ),
3388
-                '4.6.0'
3389
-            );
3390
-            $query_params = array();
3391
-        }
3392
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3393
-        // first check if we should alter the query to account for caps or not
3394
-        // because the caps might require us to do extra joins
3395
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3396
-            $query_params[0] = array_replace_recursive(
3397
-                $query_params[0],
3398
-                $this->caps_where_conditions(
3399
-                    $query_params['caps']
3400
-                )
3401
-            );
3402
-        }
3403
-
3404
-        // check if we should alter the query to remove data related to protected
3405
-        // custom post types
3406
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3407
-            $where_param_key_for_password = $this->modelChainAndPassword();
3408
-            // only include if related to a cpt where no password has been set
3409
-            $query_params[0]['OR*nopassword'] = array(
3410
-                $where_param_key_for_password => '',
3411
-                $where_param_key_for_password . '*' => array('IS_NULL')
3412
-            );
3413
-        }
3414
-        $query_object = $this->_extract_related_models_from_query($query_params);
3415
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3416
-        foreach ($query_params[0] as $key => $value) {
3417
-            if (is_int($key)) {
3418
-                throw new EE_Error(
3419
-                    sprintf(
3420
-                        esc_html__(
3421
-                            "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.",
3422
-                            "event_espresso"
3423
-                        ),
3424
-                        $key,
3425
-                        var_export($value, true),
3426
-                        var_export($query_params, true),
3427
-                        get_class($this)
3428
-                    )
3429
-                );
3430
-            }
3431
-        }
3432
-        if (
3433
-            array_key_exists('default_where_conditions', $query_params)
3434
-            && ! empty($query_params['default_where_conditions'])
3435
-        ) {
3436
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3437
-        } else {
3438
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3439
-        }
3440
-        $query_params[0] = array_merge(
3441
-            $this->_get_default_where_conditions_for_models_in_query(
3442
-                $query_object,
3443
-                $use_default_where_conditions,
3444
-                $query_params[0]
3445
-            ),
3446
-            $query_params[0]
3447
-        );
3448
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3449
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3450
-        // So we need to setup a subquery and use that for the main join.
3451
-        // Note for now this only works on the primary table for the model.
3452
-        // So for instance, you could set the limit array like this:
3453
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3454
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3455
-            $query_object->set_main_model_join_sql(
3456
-                $this->_construct_limit_join_select(
3457
-                    $query_params['on_join_limit'][0],
3458
-                    $query_params['on_join_limit'][1]
3459
-                )
3460
-            );
3461
-        }
3462
-        // set limit
3463
-        if (array_key_exists('limit', $query_params)) {
3464
-            if (is_array($query_params['limit'])) {
3465
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466
-                    $e = sprintf(
3467
-                        esc_html__(
3468
-                            "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)",
3469
-                            "event_espresso"
3470
-                        ),
3471
-                        http_build_query($query_params['limit'])
3472
-                    );
3473
-                    throw new EE_Error($e . "|" . $e);
3474
-                }
3475
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
-            } elseif (! empty($query_params['limit'])) {
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3479
-            }
3480
-        }
3481
-        // set order by
3482
-        if (array_key_exists('order_by', $query_params)) {
3483
-            if (is_array($query_params['order_by'])) {
3484
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3485
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3486
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3487
-                if (array_key_exists('order', $query_params)) {
3488
-                    throw new EE_Error(
3489
-                        sprintf(
3490
-                            esc_html__(
3491
-                                "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 ",
3492
-                                "event_espresso"
3493
-                            ),
3494
-                            get_class($this),
3495
-                            implode(", ", array_keys($query_params['order_by'])),
3496
-                            implode(", ", $query_params['order_by']),
3497
-                            $query_params['order']
3498
-                        )
3499
-                    );
3500
-                }
3501
-                $this->_extract_related_models_from_sub_params_array_keys(
3502
-                    $query_params['order_by'],
3503
-                    $query_object,
3504
-                    'order_by'
3505
-                );
3506
-                // assume it's an array of fields to order by
3507
-                $order_array = array();
3508
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509
-                    $order = $this->_extract_order($order);
3510
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3511
-                }
3512
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
-            } elseif (! empty($query_params['order_by'])) {
3514
-                $this->_extract_related_model_info_from_query_param(
3515
-                    $query_params['order_by'],
3516
-                    $query_object,
3517
-                    'order',
3518
-                    $query_params['order_by']
3519
-                );
3520
-                $order = isset($query_params['order'])
3521
-                    ? $this->_extract_order($query_params['order'])
3522
-                    : 'DESC';
3523
-                $query_object->set_order_by_sql(
3524
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3525
-                );
3526
-            }
3527
-        }
3528
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3529
-        if (
3530
-            ! array_key_exists('order_by', $query_params)
3531
-            && array_key_exists('order', $query_params)
3532
-            && ! empty($query_params['order'])
3533
-        ) {
3534
-            $pk_field = $this->get_primary_key_field();
3535
-            $order = $this->_extract_order($query_params['order']);
3536
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3537
-        }
3538
-        // set group by
3539
-        if (array_key_exists('group_by', $query_params)) {
3540
-            if (is_array($query_params['group_by'])) {
3541
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3542
-                $group_by_array = array();
3543
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545
-                }
3546
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
-            } elseif (! empty($query_params['group_by'])) {
3548
-                $query_object->set_group_by_sql(
3549
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3550
-                );
3551
-            }
3552
-        }
3553
-        // set having
3554
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3555
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3556
-        }
3557
-        // now, just verify they didn't pass anything wack
3558
-        foreach ($query_params as $query_key => $query_value) {
3559
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3560
-                throw new EE_Error(
3561
-                    sprintf(
3562
-                        esc_html__(
3563
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3564
-                            'event_espresso'
3565
-                        ),
3566
-                        $query_key,
3567
-                        get_class($this),
3568
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3569
-                        implode(',', $this->_allowed_query_params)
3570
-                    )
3571
-                );
3572
-            }
3573
-        }
3574
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3575
-        if (empty($main_model_join_sql)) {
3576
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3577
-        }
3578
-        return $query_object;
3579
-    }
3580
-
3581
-
3582
-
3583
-    /**
3584
-     * Gets the where conditions that should be imposed on the query based on the
3585
-     * context (eg reading frontend, backend, edit or delete).
3586
-     *
3587
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3588
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3589
-     * @throws EE_Error
3590
-     */
3591
-    public function caps_where_conditions($context = self::caps_read)
3592
-    {
3593
-        EEM_Base::verify_is_valid_cap_context($context);
3594
-        $cap_where_conditions = array();
3595
-        $cap_restrictions = $this->caps_missing($context);
3596
-        /**
3597
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3598
-         */
3599
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3600
-            $cap_where_conditions = array_replace_recursive(
3601
-                $cap_where_conditions,
3602
-                $restriction_if_no_cap->get_default_where_conditions()
3603
-            );
3604
-        }
3605
-        return apply_filters(
3606
-            'FHEE__EEM_Base__caps_where_conditions__return',
3607
-            $cap_where_conditions,
3608
-            $this,
3609
-            $context,
3610
-            $cap_restrictions
3611
-        );
3612
-    }
3613
-
3614
-
3615
-
3616
-    /**
3617
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3618
-     * otherwise throws an exception
3619
-     *
3620
-     * @param string $should_be_order_string
3621
-     * @return string either ASC, asc, DESC or desc
3622
-     * @throws EE_Error
3623
-     */
3624
-    private function _extract_order($should_be_order_string)
3625
-    {
3626
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3627
-            return $should_be_order_string;
3628
-        }
3629
-        throw new EE_Error(
3630
-            sprintf(
3631
-                esc_html__(
3632
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3633
-                    "event_espresso"
3634
-                ),
3635
-                get_class($this),
3636
-                $should_be_order_string
3637
-            )
3638
-        );
3639
-    }
3640
-
3641
-
3642
-
3643
-    /**
3644
-     * Looks at all the models which are included in this query, and asks each
3645
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3646
-     * so they can be merged
3647
-     *
3648
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3649
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3650
-     *                                                                  'none' means NO default where conditions will
3651
-     *                                                                  be used AT ALL during this query.
3652
-     *                                                                  'other_models_only' means default where
3653
-     *                                                                  conditions from other models will be used, but
3654
-     *                                                                  not for this primary model. 'all', the default,
3655
-     *                                                                  means default where conditions will apply as
3656
-     *                                                                  normal
3657
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3658
-     * @throws EE_Error
3659
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
-     */
3661
-    private function _get_default_where_conditions_for_models_in_query(
3662
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3663
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3664
-        $where_query_params = array()
3665
-    ) {
3666
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668
-            throw new EE_Error(sprintf(
3669
-                esc_html__(
3670
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3671
-                    "event_espresso"
3672
-                ),
3673
-                $use_default_where_conditions,
3674
-                implode(", ", $allowed_used_default_where_conditions_values)
3675
-            ));
3676
-        }
3677
-        $universal_query_params = array();
3678
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3679
-            $universal_query_params = $this->_get_default_where_conditions();
3680
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3681
-            $universal_query_params = $this->_get_minimum_where_conditions();
3682
-        }
3683
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3684
-            $related_model = $this->get_related_model_obj($model_name);
3685
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3686
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3687
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3688
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3689
-            } else {
3690
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3691
-                continue;
3692
-            }
3693
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3694
-                $related_model_universal_where_params,
3695
-                $where_query_params,
3696
-                $related_model,
3697
-                $model_relation_path
3698
-            );
3699
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3700
-                $universal_query_params,
3701
-                $overrides
3702
-            );
3703
-        }
3704
-        return $universal_query_params;
3705
-    }
3706
-
3707
-
3708
-
3709
-    /**
3710
-     * Determines whether or not we should use default where conditions for the model in question
3711
-     * (this model, or other related models).
3712
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3713
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3714
-     * We should use default where conditions on related models when they requested to use default where conditions
3715
-     * on all models, or specifically just on other related models
3716
-     * @param      $default_where_conditions_value
3717
-     * @param bool $for_this_model false means this is for OTHER related models
3718
-     * @return bool
3719
-     */
3720
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
-    {
3722
-        return (
3723
-                   $for_this_model
3724
-                   && in_array(
3725
-                       $default_where_conditions_value,
3726
-                       array(
3727
-                           EEM_Base::default_where_conditions_all,
3728
-                           EEM_Base::default_where_conditions_this_only,
3729
-                           EEM_Base::default_where_conditions_minimum_others,
3730
-                       ),
3731
-                       true
3732
-                   )
3733
-               )
3734
-               || (
3735
-                   ! $for_this_model
3736
-                   && in_array(
3737
-                       $default_where_conditions_value,
3738
-                       array(
3739
-                           EEM_Base::default_where_conditions_all,
3740
-                           EEM_Base::default_where_conditions_others_only,
3741
-                       ),
3742
-                       true
3743
-                   )
3744
-               );
3745
-    }
3746
-
3747
-    /**
3748
-     * Determines whether or not we should use default minimum conditions for the model in question
3749
-     * (this model, or other related models).
3750
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3751
-     * where conditions.
3752
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3753
-     * on this model or others
3754
-     * @param      $default_where_conditions_value
3755
-     * @param bool $for_this_model false means this is for OTHER related models
3756
-     * @return bool
3757
-     */
3758
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3759
-    {
3760
-        return (
3761
-                   $for_this_model
3762
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3763
-               )
3764
-               || (
3765
-                   ! $for_this_model
3766
-                   && in_array(
3767
-                       $default_where_conditions_value,
3768
-                       array(
3769
-                           EEM_Base::default_where_conditions_minimum_others,
3770
-                           EEM_Base::default_where_conditions_minimum_all,
3771
-                       ),
3772
-                       true
3773
-                   )
3774
-               );
3775
-    }
3776
-
3777
-
3778
-    /**
3779
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3780
-     * then we also add a special where condition which allows for that model's primary key
3781
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3782
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3783
-     *
3784
-     * @param array    $default_where_conditions
3785
-     * @param array    $provided_where_conditions
3786
-     * @param EEM_Base $model
3787
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3788
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3789
-     * @throws EE_Error
3790
-     */
3791
-    private function _override_defaults_or_make_null_friendly(
3792
-        $default_where_conditions,
3793
-        $provided_where_conditions,
3794
-        $model,
3795
-        $model_relation_path
3796
-    ) {
3797
-        $null_friendly_where_conditions = array();
3798
-        $none_overridden = true;
3799
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3800
-        foreach ($default_where_conditions as $key => $val) {
3801
-            if (isset($provided_where_conditions[ $key ])) {
3802
-                $none_overridden = false;
3803
-            } else {
3804
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3805
-            }
3806
-        }
3807
-        if ($none_overridden && $default_where_conditions) {
3808
-            if ($model->has_primary_key_field()) {
3809
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3810
-                                                                                . "."
3811
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3812
-            }/*else{
39
+	/**
40
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
43
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
+	 *
45
+	 * @var boolean
46
+	 */
47
+	private $_values_already_prepared_by_model_object = 0;
48
+
49
+	/**
50
+	 * when $_values_already_prepared_by_model_object equals this, we assume
51
+	 * the data is just like form input that needs to have the model fields'
52
+	 * prepare_for_set and prepare_for_use_in_db called on it
53
+	 */
54
+	const not_prepared_by_model_object = 0;
55
+
56
+	/**
57
+	 * when $_values_already_prepared_by_model_object equals this, we
58
+	 * assume this value is coming from a model object and doesn't need to have
59
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
60
+	 */
61
+	const prepared_by_model_object = 1;
62
+
63
+	/**
64
+	 * when $_values_already_prepared_by_model_object equals this, we assume
65
+	 * the values are already to be used in the database (ie no processing is done
66
+	 * on them by the model's fields)
67
+	 */
68
+	const prepared_for_use_in_db = 2;
69
+
70
+
71
+	protected $singular_item = 'Item';
72
+
73
+	protected $plural_item   = 'Items';
74
+
75
+	/**
76
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
+	 */
78
+	protected $_tables;
79
+
80
+	/**
81
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
+	 *
85
+	 * @var \EE_Model_Field_Base[][] $_fields
86
+	 */
87
+	protected $_fields;
88
+
89
+	/**
90
+	 * array of different kinds of relations
91
+	 *
92
+	 * @var \EE_Model_Relation_Base[] $_model_relations
93
+	 */
94
+	protected $_model_relations;
95
+
96
+	/**
97
+	 * @var \EE_Index[] $_indexes
98
+	 */
99
+	protected $_indexes = array();
100
+
101
+	/**
102
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
103
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
+	 * by setting the same columns as used in these queries in the query yourself.
105
+	 *
106
+	 * @var EE_Default_Where_Conditions
107
+	 */
108
+	protected $_default_where_conditions_strategy;
109
+
110
+	/**
111
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
+	 * This is particularly useful when you want something between 'none' and 'default'
113
+	 *
114
+	 * @var EE_Default_Where_Conditions
115
+	 */
116
+	protected $_minimum_where_conditions_strategy;
117
+
118
+	/**
119
+	 * String describing how to find the "owner" of this model's objects.
120
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
+	 * But when there isn't, this indicates which related model, or transiently-related model,
122
+	 * has the foreign key to the wp_users table.
123
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
+	 * related to events, and events have a foreign key to wp_users.
125
+	 * On EEM_Transaction, this would be 'Transaction.Event'
126
+	 *
127
+	 * @var string
128
+	 */
129
+	protected $_model_chain_to_wp_user = '';
130
+
131
+	/**
132
+	 * String describing how to find the model with a password controlling access to this model. This property has the
133
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
+	 * This value is the path of models to follow to arrive at the model with the password field.
135
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
+	 * model with a password that should affect reading this on the front-end.
137
+	 * Eg this is an empty string for the Event model because it has a password.
138
+	 * This is null for the Registration model, because its event's password has no bearing on whether
139
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
+	 * should hide tickets for datetimes for events that have a password set.
142
+	 * @var string |null
143
+	 */
144
+	protected $model_chain_to_password = null;
145
+
146
+	/**
147
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
+	 * don't need it (particularly CPT models)
149
+	 *
150
+	 * @var bool
151
+	 */
152
+	protected $_ignore_where_strategy = false;
153
+
154
+	/**
155
+	 * String used in caps relating to this model. Eg, if the caps relating to this
156
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
+	 *
158
+	 * @var string. If null it hasn't been initialized yet. If false then we
159
+	 * have indicated capabilities don't apply to this
160
+	 */
161
+	protected $_caps_slug = null;
162
+
163
+	/**
164
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
+	 * and next-level keys are capability names, and each's value is a
166
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
168
+	 * and then each capability in the corresponding sub-array that they're missing
169
+	 * adds the where conditions onto the query.
170
+	 *
171
+	 * @var array
172
+	 */
173
+	protected $_cap_restrictions = array(
174
+		self::caps_read       => array(),
175
+		self::caps_read_admin => array(),
176
+		self::caps_edit       => array(),
177
+		self::caps_delete     => array(),
178
+	);
179
+
180
+	/**
181
+	 * Array defining which cap restriction generators to use to create default
182
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
183
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
+	 * automatically set this to false (not just null).
186
+	 *
187
+	 * @var EE_Restriction_Generator_Base[]
188
+	 */
189
+	protected $_cap_restriction_generators = array();
190
+
191
+	/**
192
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
+	 */
194
+	const caps_read       = 'read';
195
+
196
+	const caps_read_admin = 'read_admin';
197
+
198
+	const caps_edit       = 'edit';
199
+
200
+	const caps_delete     = 'delete';
201
+
202
+	/**
203
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
+	 * maps to 'read' because when looking for relevant permissions we're going to use
206
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
207
+	 *
208
+	 * @var array
209
+	 */
210
+	protected $_cap_contexts_to_cap_action_map = array(
211
+		self::caps_read       => 'read',
212
+		self::caps_read_admin => 'read',
213
+		self::caps_edit       => 'edit',
214
+		self::caps_delete     => 'delete',
215
+	);
216
+
217
+	/**
218
+	 * Timezone
219
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
+	 * EE_Datetime_Field data type will have access to it.
223
+	 *
224
+	 * @var string
225
+	 */
226
+	protected $_timezone;
227
+
228
+
229
+	/**
230
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
+	 * multisite.
232
+	 *
233
+	 * @var int
234
+	 */
235
+	protected static $_model_query_blog_id;
236
+
237
+	/**
238
+	 * A copy of _fields, except the array keys are the model names pointed to by
239
+	 * the field
240
+	 *
241
+	 * @var EE_Model_Field_Base[]
242
+	 */
243
+	private $_cache_foreign_key_to_fields = array();
244
+
245
+	/**
246
+	 * Cached list of all the fields on the model, indexed by their name
247
+	 *
248
+	 * @var EE_Model_Field_Base[]
249
+	 */
250
+	private $_cached_fields = null;
251
+
252
+	/**
253
+	 * Cached list of all the fields on the model, except those that are
254
+	 * marked as only pertinent to the database
255
+	 *
256
+	 * @var EE_Model_Field_Base[]
257
+	 */
258
+	private $_cached_fields_non_db_only = null;
259
+
260
+	/**
261
+	 * A cached reference to the primary key for quick lookup
262
+	 *
263
+	 * @var EE_Model_Field_Base
264
+	 */
265
+	private $_primary_key_field = null;
266
+
267
+	/**
268
+	 * Flag indicating whether this model has a primary key or not
269
+	 *
270
+	 * @var boolean
271
+	 */
272
+	protected $_has_primary_key_field = null;
273
+
274
+	/**
275
+	 * array in the format:  [ FK alias => full PK ]
276
+	 * where keys are local column name aliases for foreign keys
277
+	 * and values are the fully qualified column name for the primary key they represent
278
+	 *  ex:
279
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
+	 *
281
+	 * @var array $foreign_key_aliases
282
+	 */
283
+	protected $foreign_key_aliases = [];
284
+
285
+	/**
286
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
287
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
+	 * This should be true for models that deal with data that should exist independent of EE.
289
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
291
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
293
+	 * @var boolean
294
+	 */
295
+	protected $_wp_core_model = false;
296
+
297
+	/**
298
+	 * @var bool stores whether this model has a password field or not.
299
+	 * null until initialized by hasPasswordField()
300
+	 */
301
+	protected $has_password_field;
302
+
303
+	/**
304
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
+	 */
306
+	protected $password_field;
307
+
308
+	/**
309
+	 *    List of valid operators that can be used for querying.
310
+	 * The keys are all operators we'll accept, the values are the real SQL
311
+	 * operators used
312
+	 *
313
+	 * @var array
314
+	 */
315
+	protected $_valid_operators = array(
316
+		'='           => '=',
317
+		'<='          => '<=',
318
+		'<'           => '<',
319
+		'>='          => '>=',
320
+		'>'           => '>',
321
+		'!='          => '!=',
322
+		'LIKE'        => 'LIKE',
323
+		'like'        => 'LIKE',
324
+		'NOT_LIKE'    => 'NOT LIKE',
325
+		'not_like'    => 'NOT LIKE',
326
+		'NOT LIKE'    => 'NOT LIKE',
327
+		'not like'    => 'NOT LIKE',
328
+		'IN'          => 'IN',
329
+		'in'          => 'IN',
330
+		'NOT_IN'      => 'NOT IN',
331
+		'not_in'      => 'NOT IN',
332
+		'NOT IN'      => 'NOT IN',
333
+		'not in'      => 'NOT IN',
334
+		'between'     => 'BETWEEN',
335
+		'BETWEEN'     => 'BETWEEN',
336
+		'IS_NOT_NULL' => 'IS NOT NULL',
337
+		'is_not_null' => 'IS NOT NULL',
338
+		'IS NOT NULL' => 'IS NOT NULL',
339
+		'is not null' => 'IS NOT NULL',
340
+		'IS_NULL'     => 'IS NULL',
341
+		'is_null'     => 'IS NULL',
342
+		'IS NULL'     => 'IS NULL',
343
+		'is null'     => 'IS NULL',
344
+		'REGEXP'      => 'REGEXP',
345
+		'regexp'      => 'REGEXP',
346
+		'NOT_REGEXP'  => 'NOT REGEXP',
347
+		'not_regexp'  => 'NOT REGEXP',
348
+		'NOT REGEXP'  => 'NOT REGEXP',
349
+		'not regexp'  => 'NOT REGEXP',
350
+	);
351
+
352
+	/**
353
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
+	 *
355
+	 * @var array
356
+	 */
357
+	protected $_in_style_operators = array('IN', 'NOT IN');
358
+
359
+	/**
360
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
+	 * '12-31-2012'"
362
+	 *
363
+	 * @var array
364
+	 */
365
+	protected $_between_style_operators = array('BETWEEN');
366
+
367
+	/**
368
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
+	 * @var array
370
+	 */
371
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
+	/**
373
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
+	 * on a join table.
375
+	 *
376
+	 * @var array
377
+	 */
378
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
+
380
+	/**
381
+	 * Allowed values for $query_params['order'] for ordering in queries
382
+	 *
383
+	 * @var array
384
+	 */
385
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
+
387
+	/**
388
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
390
+	 *
391
+	 * @var array
392
+	 */
393
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
+
395
+	/**
396
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
398
+	 *
399
+	 * @var array
400
+	 */
401
+	private $_allowed_query_params = array(
402
+		0,
403
+		'limit',
404
+		'order_by',
405
+		'group_by',
406
+		'having',
407
+		'force_join',
408
+		'order',
409
+		'on_join_limit',
410
+		'default_where_conditions',
411
+		'caps',
412
+		'extra_selects',
413
+		'exclude_protected',
414
+	);
415
+
416
+	/**
417
+	 * All the data types that can be used in $wpdb->prepare statements.
418
+	 *
419
+	 * @var array
420
+	 */
421
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
+
423
+	/**
424
+	 * @var EE_Registry $EE
425
+	 */
426
+	protected $EE = null;
427
+
428
+
429
+	/**
430
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
+	 *
432
+	 * @var int
433
+	 */
434
+	protected $_show_next_x_db_queries = 0;
435
+
436
+	/**
437
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
+	 * WHERE, GROUP_BY, etc.
440
+	 *
441
+	 * @var CustomSelects
442
+	 */
443
+	protected $_custom_selections = array();
444
+
445
+	/**
446
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
+	 * caches every model object we've fetched from the DB on this request
448
+	 *
449
+	 * @var array
450
+	 */
451
+	protected $_entity_map;
452
+
453
+	/**
454
+	 * @var LoaderInterface $loader
455
+	 */
456
+	protected static $loader;
457
+
458
+
459
+	/**
460
+	 * constant used to show EEM_Base has not yet verified the db on this http request
461
+	 */
462
+	const db_verified_none = 0;
463
+
464
+	/**
465
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
466
+	 * but not the addons' dbs
467
+	 */
468
+	const db_verified_core = 1;
469
+
470
+	/**
471
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
+	 * the EE core db too)
473
+	 */
474
+	const db_verified_addons = 2;
475
+
476
+	/**
477
+	 * indicates whether an EEM_Base child has already re-verified the DB
478
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
479
+	 * looking like EEM_Base::db_verified_*
480
+	 *
481
+	 * @var int - 0 = none, 1 = core, 2 = addons
482
+	 */
483
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
484
+
485
+	/**
486
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
489
+	 */
490
+	const default_where_conditions_all = 'all';
491
+
492
+	/**
493
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
+	 *        models which share tables with other models, this can return data for the wrong model.
498
+	 */
499
+	const default_where_conditions_this_only = 'this_model_only';
500
+
501
+	/**
502
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
+	 */
506
+	const default_where_conditions_others_only = 'other_models_only';
507
+
508
+	/**
509
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
512
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
+	 *        (regardless of whether those events and venues are trashed)
514
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
+	 *        events.
516
+	 */
517
+	const default_where_conditions_minimum_all = 'minimum';
518
+
519
+	/**
520
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
+	 *        not)
524
+	 */
525
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
+
527
+	/**
528
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
+	 *        it's possible it will return table entries for other models. You should use
531
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
532
+	 */
533
+	const default_where_conditions_none = 'none';
534
+
535
+
536
+
537
+	/**
538
+	 * About all child constructors:
539
+	 * they should define the _tables, _fields and _model_relations arrays.
540
+	 * Should ALWAYS be called after child constructor.
541
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
542
+	 * finalizes constructing all the object's attributes.
543
+	 * Generally, rather than requiring a child to code
544
+	 * $this->_tables = array(
545
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
+	 *        ...);
547
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
+	 * each EE_Table has a function to set the table's alias after the constructor, using
549
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
+	 * do something similar.
551
+	 *
552
+	 * @param null $timezone
553
+	 * @throws EE_Error
554
+	 */
555
+	protected function __construct($timezone = null)
556
+	{
557
+		// check that the model has not been loaded too soon
558
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
+			throw new EE_Error(
560
+				sprintf(
561
+					esc_html__(
562
+						'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.',
563
+						'event_espresso'
564
+					),
565
+					get_class($this)
566
+				)
567
+			);
568
+		}
569
+		/**
570
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
+		 */
572
+		if (empty(EEM_Base::$_model_query_blog_id)) {
573
+			EEM_Base::set_model_query_blog_id();
574
+		}
575
+		/**
576
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
+		 * just use EE_Register_Model_Extension
578
+		 *
579
+		 * @var EE_Table_Base[] $_tables
580
+		 */
581
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
+		foreach ($this->_tables as $table_alias => $table_obj) {
583
+			/** @var $table_obj EE_Table_Base */
584
+			$table_obj->_construct_finalize_with_alias($table_alias);
585
+			if ($table_obj instanceof EE_Secondary_Table) {
586
+				/** @var $table_obj EE_Secondary_Table */
587
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
+			}
589
+		}
590
+		/**
591
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
+		 * EE_Register_Model_Extension
593
+		 *
594
+		 * @param EE_Model_Field_Base[] $_fields
595
+		 */
596
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
+		$this->_invalidate_field_caches();
598
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
599
+			if (! array_key_exists($table_alias, $this->_tables)) {
600
+				throw new EE_Error(sprintf(esc_html__(
601
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
+					'event_espresso'
603
+				), $table_alias, implode(",", $this->_fields)));
604
+			}
605
+			foreach ($fields_for_table as $field_name => $field_obj) {
606
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
+				// primary key field base has a slightly different _construct_finalize
608
+				/** @var $field_obj EE_Model_Field_Base */
609
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
+			}
611
+		}
612
+		// everything is related to Extra_Meta
613
+		if (get_class($this) !== 'EEM_Extra_Meta') {
614
+			// make extra meta related to everything, but don't block deleting things just
615
+			// because they have related extra meta info. For now just orphan those extra meta
616
+			// in the future we should automatically delete them
617
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
+		}
619
+		// and change logs
620
+		if (get_class($this) !== 'EEM_Change_Log') {
621
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
+		}
623
+		/**
624
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
+		 * EE_Register_Model_Extension
626
+		 *
627
+		 * @param EE_Model_Relation_Base[] $_model_relations
628
+		 */
629
+		$this->_model_relations = (array) apply_filters(
630
+			'FHEE__' . get_class($this) . '__construct__model_relations',
631
+			$this->_model_relations
632
+		);
633
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
634
+			/** @var $relation_obj EE_Model_Relation_Base */
635
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
+		}
637
+		foreach ($this->_indexes as $index_name => $index_obj) {
638
+			/** @var $index_obj EE_Index */
639
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
+		}
641
+		$this->set_timezone($timezone);
642
+		// finalize default where condition strategy, or set default
643
+		if (! $this->_default_where_conditions_strategy) {
644
+			// nothing was set during child constructor, so set default
645
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
+		}
647
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
648
+		if (! $this->_minimum_where_conditions_strategy) {
649
+			// nothing was set during child constructor, so set default
650
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
+		}
652
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
654
+		// to indicate to NOT set it, set it to the logical default
655
+		if ($this->_caps_slug === null) {
656
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
+		}
658
+		// initialize the standard cap restriction generators if none were specified by the child constructor
659
+		if ($this->_cap_restriction_generators !== false) {
660
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
+						new EE_Restriction_Generator_Protected(),
665
+						$cap_context,
666
+						$this
667
+					);
668
+				}
669
+			}
670
+		}
671
+		// if there are cap restriction generators, use them to make the default cap restrictions
672
+		if ($this->_cap_restriction_generators !== false) {
673
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
+				if (! $generator_object) {
675
+					continue;
676
+				}
677
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
+					throw new EE_Error(
679
+						sprintf(
680
+							esc_html__(
681
+								'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.',
682
+								'event_espresso'
683
+							),
684
+							$context,
685
+							$this->get_this_model_name()
686
+						)
687
+					);
688
+				}
689
+				$action = $this->cap_action_for_context($context);
690
+				if (! $generator_object->construction_finalized()) {
691
+					$generator_object->_construct_finalize($this, $action);
692
+				}
693
+			}
694
+		}
695
+		do_action('AHEE__' . get_class($this) . '__construct__end');
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * Used to set the $_model_query_blog_id static property.
702
+	 *
703
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
+	 *                      value for get_current_blog_id() will be used.
705
+	 */
706
+	public static function set_model_query_blog_id($blog_id = 0)
707
+	{
708
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
+	}
710
+
711
+
712
+
713
+	/**
714
+	 * Returns whatever is set as the internal $model_query_blog_id.
715
+	 *
716
+	 * @return int
717
+	 */
718
+	public static function get_model_query_blog_id()
719
+	{
720
+		return EEM_Base::$_model_query_blog_id;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * This function is a singleton method used to instantiate the Espresso_model object
727
+	 *
728
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
+	 *                                (and any incoming timezone data that gets saved).
730
+	 *                                Note this just sends the timezone info to the date time model field objects.
731
+	 *                                Default is NULL
732
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
+	 * @return static (as in the concrete child class)
734
+	 * @throws EE_Error
735
+	 * @throws InvalidArgumentException
736
+	 * @throws InvalidDataTypeException
737
+	 * @throws InvalidInterfaceException
738
+	 */
739
+	public static function instance($timezone = null)
740
+	{
741
+		// check if instance of Espresso_model already exists
742
+		if (! static::$_instance instanceof static) {
743
+			// instantiate Espresso_model
744
+			static::$_instance = new static(
745
+				$timezone,
746
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
+			);
748
+		}
749
+		// we might have a timezone set, let set_timezone decide what to do with it
750
+		static::$_instance->set_timezone($timezone);
751
+		// Espresso_model object
752
+		return static::$_instance;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * resets the model and returns it
759
+	 *
760
+	 * @param null | string $timezone
761
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
+	 * all its properties reset; if it wasn't instantiated, returns null)
763
+	 * @throws EE_Error
764
+	 * @throws ReflectionException
765
+	 * @throws InvalidArgumentException
766
+	 * @throws InvalidDataTypeException
767
+	 * @throws InvalidInterfaceException
768
+	 */
769
+	public static function reset($timezone = null)
770
+	{
771
+		if (static::$_instance instanceof EEM_Base) {
772
+			// let's try to NOT swap out the current instance for a new one
773
+			// because if someone has a reference to it, we can't remove their reference
774
+			// so it's best to keep using the same reference, but change the original object
775
+			// reset all its properties to their original values as defined in the class
776
+			$r = new ReflectionClass(get_class(static::$_instance));
777
+			$static_properties = $r->getStaticProperties();
778
+			foreach ($r->getDefaultProperties() as $property => $value) {
779
+				// don't set instance to null like it was originally,
780
+				// but it's static anyways, and we're ignoring static properties (for now at least)
781
+				if (! isset($static_properties[ $property ])) {
782
+					static::$_instance->{$property} = $value;
783
+				}
784
+			}
785
+			// and then directly call its constructor again, like we would if we were creating a new one
786
+			static::$_instance->__construct(
787
+				$timezone,
788
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
+			);
790
+			return self::instance();
791
+		}
792
+		return null;
793
+	}
794
+
795
+
796
+
797
+	/**
798
+	 * @return LoaderInterface
799
+	 * @throws InvalidArgumentException
800
+	 * @throws InvalidDataTypeException
801
+	 * @throws InvalidInterfaceException
802
+	 */
803
+	private static function getLoader()
804
+	{
805
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
806
+			EEM_Base::$loader = LoaderFactory::getLoader();
807
+		}
808
+		return EEM_Base::$loader;
809
+	}
810
+
811
+
812
+
813
+	/**
814
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
+	 *
816
+	 * @param  boolean $translated return localized strings or JUST the array.
817
+	 * @return array
818
+	 * @throws EE_Error
819
+	 * @throws InvalidArgumentException
820
+	 * @throws InvalidDataTypeException
821
+	 * @throws InvalidInterfaceException
822
+	 */
823
+	public function status_array($translated = false)
824
+	{
825
+		if (! array_key_exists('Status', $this->_model_relations)) {
826
+			return array();
827
+		}
828
+		$model_name = $this->get_this_model_name();
829
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
+		$status_array = array();
832
+		foreach ($stati as $status) {
833
+			$status_array[ $status->ID() ] = $status->get('STS_code');
834
+		}
835
+		return $translated
836
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
+			: $status_array;
838
+	}
839
+
840
+
841
+
842
+	/**
843
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
+	 *
845
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
+	 *                             or if you have the development copy of EE you can view this at the path:
847
+	 *                             /docs/G--Model-System/model-query-params.md
848
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
+	 *                                        array( array(
853
+	 *                                        'OR'=>array(
854
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
+	 *                                        )
857
+	 *                                        ),
858
+	 *                                        'limit'=>10,
859
+	 *                                        'group_by'=>'TXN_ID'
860
+	 *                                        ));
861
+	 *                                        get all the answers to the question titled "shirt size" for event with id
862
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
+	 *                                        'Question.QST_display_text'=>'shirt size',
864
+	 *                                        'Registration.Event.EVT_ID'=>12
865
+	 *                                        ),
866
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
867
+	 *                                        ));
868
+	 * @throws EE_Error
869
+	 */
870
+	public function get_all($query_params = array())
871
+	{
872
+		if (
873
+			isset($query_params['limit'])
874
+			&& ! isset($query_params['group_by'])
875
+		) {
876
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
+		}
878
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * Modifies the query parameters so we only get back model objects
885
+	 * that "belong" to the current user
886
+	 *
887
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
+	 */
890
+	public function alter_query_params_to_only_include_mine($query_params = array())
891
+	{
892
+		$wp_user_field_name = $this->wp_user_field_name();
893
+		if ($wp_user_field_name) {
894
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
+		}
896
+		return $query_params;
897
+	}
898
+
899
+
900
+
901
+	/**
902
+	 * Returns the name of the field's name that points to the WP_User table
903
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
+	 * foreign key to the WP_User table)
905
+	 *
906
+	 * @return string|boolean string on success, boolean false when there is no
907
+	 * foreign key to the WP_User table
908
+	 */
909
+	public function wp_user_field_name()
910
+	{
911
+		try {
912
+			if (! empty($this->_model_chain_to_wp_user)) {
913
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
+				$last_model_name = end($models_to_follow_to_wp_users);
915
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
+			} else {
918
+				$model_with_fk_to_wp_users = $this;
919
+				$model_chain_to_wp_user = '';
920
+			}
921
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
923
+		} catch (EE_Error $e) {
924
+			return false;
925
+		}
926
+	}
927
+
928
+
929
+
930
+	/**
931
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
932
+	 * (or transiently-related model) has a foreign key to the wp_users table;
933
+	 * useful for finding if model objects of this type are 'owned' by the current user.
934
+	 * This is an empty string when the foreign key is on this model and when it isn't,
935
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
936
+	 * (or transiently-related model)
937
+	 *
938
+	 * @return string
939
+	 */
940
+	public function model_chain_to_wp_user()
941
+	{
942
+		return $this->_model_chain_to_wp_user;
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
+	 * like how registrations don't have a foreign key to wp_users, but the
950
+	 * events they are for are), or is unrelated to wp users.
951
+	 * generally available
952
+	 *
953
+	 * @return boolean
954
+	 */
955
+	public function is_owned()
956
+	{
957
+		if ($this->model_chain_to_wp_user()) {
958
+			return true;
959
+		}
960
+		try {
961
+			$this->get_foreign_key_to('WP_User');
962
+			return true;
963
+		} catch (EE_Error $e) {
964
+			return false;
965
+		}
966
+	}
967
+
968
+
969
+	/**
970
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
+	 * the model)
973
+	 *
974
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
978
+	 *                                  override this and set the select to "*", or a specific column name, like
979
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
+	 *                                  the aliases used to refer to this selection, and values are to be
982
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
+	 * @throws EE_Error
986
+	 * @throws InvalidArgumentException
987
+	 */
988
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
+	{
990
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
+		;
992
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
993
+		$select_expressions = $columns_to_select === null
994
+			? $this->_construct_default_select_sql($model_query_info)
995
+			: '';
996
+		if ($this->_custom_selections instanceof CustomSelects) {
997
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
+			$select_expressions .= $select_expressions
999
+				? ', ' . $custom_expressions
1000
+				: $custom_expressions;
1001
+		}
1002
+
1003
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
+	 * method of including extra select information.
1012
+	 *
1013
+	 * @param array             $query_params
1014
+	 * @param null|array|string $columns_to_select
1015
+	 * @return null|CustomSelects
1016
+	 * @throws InvalidArgumentException
1017
+	 */
1018
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
+	{
1020
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
+			return null;
1022
+		}
1023
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
+		return new CustomSelects($selects);
1026
+	}
1027
+
1028
+
1029
+
1030
+	/**
1031
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1032
+	 * but you can use the model query params to more easily
1033
+	 * take care of joins, field preparation etc.
1034
+	 *
1035
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1039
+	 *                                  override this and set the select to "*", or a specific column name, like
1040
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
+	 *                                  the aliases used to refer to this selection, and values are to be
1043
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
+	 * @throws EE_Error
1047
+	 */
1048
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
+	{
1050
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
+	}
1052
+
1053
+
1054
+
1055
+	/**
1056
+	 * For creating a custom select statement
1057
+	 *
1058
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
+	 *                                 SQL, and 1=>is the datatype
1061
+	 * @throws EE_Error
1062
+	 * @return string
1063
+	 */
1064
+	private function _construct_select_from_input($columns_to_select)
1065
+	{
1066
+		if (is_array($columns_to_select)) {
1067
+			$select_sql_array = array();
1068
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
+					throw new EE_Error(
1071
+						sprintf(
1072
+							esc_html__(
1073
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
+								'event_espresso'
1075
+							),
1076
+							$selection_and_datatype,
1077
+							$alias
1078
+						)
1079
+					);
1080
+				}
1081
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype[1],
1089
+							$selection_and_datatype[0],
1090
+							$alias,
1091
+							implode(', ', $this->_valid_wpdb_data_types)
1092
+						)
1093
+					);
1094
+				}
1095
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
+			}
1097
+			$columns_to_select_string = implode(', ', $select_sql_array);
1098
+		} else {
1099
+			$columns_to_select_string = $columns_to_select;
1100
+		}
1101
+		return $columns_to_select_string;
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
+	 *
1109
+	 * @return string
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function primary_key_name()
1113
+	{
1114
+		return $this->get_primary_key_field()->get_name();
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
+	 * If there is no primary key on this model, $id is treated as primary key string
1121
+	 *
1122
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1123
+	 * @return EE_Base_Class
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public function get_one_by_ID($id)
1127
+	{
1128
+		if ($this->get_from_entity_map($id)) {
1129
+			return $this->get_from_entity_map($id);
1130
+		}
1131
+		$model_object = $this->get_one(
1132
+			$this->alter_query_params_to_restrict_by_ID(
1133
+				$id,
1134
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
+			)
1136
+		);
1137
+		$className = $this->_get_class_name();
1138
+		if ($model_object instanceof $className) {
1139
+			// make sure valid objects get added to the entity map
1140
+			// so that the next call to this method doesn't trigger another trip to the db
1141
+			$this->add_to_entity_map($model_object);
1142
+		}
1143
+		return $model_object;
1144
+	}
1145
+
1146
+
1147
+
1148
+	/**
1149
+	 * Alters query parameters to only get items with this ID are returned.
1150
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
+	 * or could just be a simple primary key ID
1152
+	 *
1153
+	 * @param int   $id
1154
+	 * @param array $query_params
1155
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
+	 * @throws EE_Error
1157
+	 */
1158
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
+	{
1160
+		if (! isset($query_params[0])) {
1161
+			$query_params[0] = array();
1162
+		}
1163
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1164
+		if ($conditions_from_id === null) {
1165
+			$query_params[0][ $this->primary_key_name() ] = $id;
1166
+		} else {
1167
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1168
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
+		}
1170
+		return $query_params;
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
+	 * array. If no item is found, null is returned.
1178
+	 *
1179
+	 * @param array $query_params like EEM_Base's $query_params variable.
1180
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
+	 * @throws EE_Error
1182
+	 */
1183
+	public function get_one($query_params = array())
1184
+	{
1185
+		if (! is_array($query_params)) {
1186
+			EE_Error::doing_it_wrong(
1187
+				'EEM_Base::get_one',
1188
+				sprintf(
1189
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
+					gettype($query_params)
1191
+				),
1192
+				'4.6.0'
1193
+			);
1194
+			$query_params = array();
1195
+		}
1196
+		$query_params['limit'] = 1;
1197
+		$items = $this->get_all($query_params);
1198
+		if (empty($items)) {
1199
+			return null;
1200
+		}
1201
+		return array_shift($items);
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Returns the next x number of items in sequence from the given value as
1208
+	 * found in the database matching the given query conditions.
1209
+	 *
1210
+	 * @param mixed $current_field_value    Value used for the reference point.
1211
+	 * @param null  $field_to_order_by      What field is used for the
1212
+	 *                                      reference point.
1213
+	 * @param int   $limit                  How many to return.
1214
+	 * @param array $query_params           Extra conditions on the query.
1215
+	 * @param null  $columns_to_select      If left null, then an array of
1216
+	 *                                      EE_Base_Class objects is returned,
1217
+	 *                                      otherwise you can indicate just the
1218
+	 *                                      columns you want returned.
1219
+	 * @return EE_Base_Class[]|array
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function next_x(
1223
+		$current_field_value,
1224
+		$field_to_order_by = null,
1225
+		$limit = 1,
1226
+		$query_params = array(),
1227
+		$columns_to_select = null
1228
+	) {
1229
+		return $this->_get_consecutive(
1230
+			$current_field_value,
1231
+			'>',
1232
+			$field_to_order_by,
1233
+			$limit,
1234
+			$query_params,
1235
+			$columns_to_select
1236
+		);
1237
+	}
1238
+
1239
+
1240
+
1241
+	/**
1242
+	 * Returns the previous x number of items in sequence from the given value
1243
+	 * as found in the database matching the given query conditions.
1244
+	 *
1245
+	 * @param mixed $current_field_value    Value used for the reference point.
1246
+	 * @param null  $field_to_order_by      What field is used for the
1247
+	 *                                      reference point.
1248
+	 * @param int   $limit                  How many to return.
1249
+	 * @param array $query_params           Extra conditions on the query.
1250
+	 * @param null  $columns_to_select      If left null, then an array of
1251
+	 *                                      EE_Base_Class objects is returned,
1252
+	 *                                      otherwise you can indicate just the
1253
+	 *                                      columns you want returned.
1254
+	 * @return EE_Base_Class[]|array
1255
+	 * @throws EE_Error
1256
+	 */
1257
+	public function previous_x(
1258
+		$current_field_value,
1259
+		$field_to_order_by = null,
1260
+		$limit = 1,
1261
+		$query_params = array(),
1262
+		$columns_to_select = null
1263
+	) {
1264
+		return $this->_get_consecutive(
1265
+			$current_field_value,
1266
+			'<',
1267
+			$field_to_order_by,
1268
+			$limit,
1269
+			$query_params,
1270
+			$columns_to_select
1271
+		);
1272
+	}
1273
+
1274
+
1275
+
1276
+	/**
1277
+	 * Returns the next item in sequence from the given value as found in the
1278
+	 * database matching the given query conditions.
1279
+	 *
1280
+	 * @param mixed $current_field_value    Value used for the reference point.
1281
+	 * @param null  $field_to_order_by      What field is used for the
1282
+	 *                                      reference point.
1283
+	 * @param array $query_params           Extra conditions on the query.
1284
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
+	 *                                      object is returned, otherwise you
1286
+	 *                                      can indicate just the columns you
1287
+	 *                                      want and a single array indexed by
1288
+	 *                                      the columns will be returned.
1289
+	 * @return EE_Base_Class|null|array()
1290
+	 * @throws EE_Error
1291
+	 */
1292
+	public function next(
1293
+		$current_field_value,
1294
+		$field_to_order_by = null,
1295
+		$query_params = array(),
1296
+		$columns_to_select = null
1297
+	) {
1298
+		$results = $this->_get_consecutive(
1299
+			$current_field_value,
1300
+			'>',
1301
+			$field_to_order_by,
1302
+			1,
1303
+			$query_params,
1304
+			$columns_to_select
1305
+		);
1306
+		return empty($results) ? null : reset($results);
1307
+	}
1308
+
1309
+
1310
+
1311
+	/**
1312
+	 * Returns the previous item in sequence from the given value as found in
1313
+	 * the database matching the given query conditions.
1314
+	 *
1315
+	 * @param mixed $current_field_value    Value used for the reference point.
1316
+	 * @param null  $field_to_order_by      What field is used for the
1317
+	 *                                      reference point.
1318
+	 * @param array $query_params           Extra conditions on the query.
1319
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
+	 *                                      object is returned, otherwise you
1321
+	 *                                      can indicate just the columns you
1322
+	 *                                      want and a single array indexed by
1323
+	 *                                      the columns will be returned.
1324
+	 * @return EE_Base_Class|null|array()
1325
+	 * @throws EE_Error
1326
+	 */
1327
+	public function previous(
1328
+		$current_field_value,
1329
+		$field_to_order_by = null,
1330
+		$query_params = array(),
1331
+		$columns_to_select = null
1332
+	) {
1333
+		$results = $this->_get_consecutive(
1334
+			$current_field_value,
1335
+			'<',
1336
+			$field_to_order_by,
1337
+			1,
1338
+			$query_params,
1339
+			$columns_to_select
1340
+		);
1341
+		return empty($results) ? null : reset($results);
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * Returns the a consecutive number of items in sequence from the given
1348
+	 * value as found in the database matching the given query conditions.
1349
+	 *
1350
+	 * @param mixed  $current_field_value   Value used for the reference point.
1351
+	 * @param string $operand               What operand is used for the sequence.
1352
+	 * @param string $field_to_order_by     What field is used for the reference point.
1353
+	 * @param int    $limit                 How many to return.
1354
+	 * @param array  $query_params          Extra conditions on the query.
1355
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
+	 *                                      otherwise you can indicate just the columns you want returned.
1357
+	 * @return EE_Base_Class[]|array
1358
+	 * @throws EE_Error
1359
+	 */
1360
+	protected function _get_consecutive(
1361
+		$current_field_value,
1362
+		$operand = '>',
1363
+		$field_to_order_by = null,
1364
+		$limit = 1,
1365
+		$query_params = array(),
1366
+		$columns_to_select = null
1367
+	) {
1368
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
+		if (empty($field_to_order_by)) {
1370
+			if ($this->has_primary_key_field()) {
1371
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1372
+			} else {
1373
+				if (WP_DEBUG) {
1374
+					throw new EE_Error(esc_html__(
1375
+						'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).',
1376
+						'event_espresso'
1377
+					));
1378
+				}
1379
+				EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
+				return array();
1381
+			}
1382
+		}
1383
+		if (! is_array($query_params)) {
1384
+			EE_Error::doing_it_wrong(
1385
+				'EEM_Base::_get_consecutive',
1386
+				sprintf(
1387
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
+					gettype($query_params)
1389
+				),
1390
+				'4.6.0'
1391
+			);
1392
+			$query_params = array();
1393
+		}
1394
+		// let's add the where query param for consecutive look up.
1395
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
+		$query_params['limit'] = $limit;
1397
+		// set direction
1398
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
+		$query_params['order_by'] = $operand === '>'
1400
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
+		if (empty($columns_to_select)) {
1404
+			return $this->get_all($query_params);
1405
+		}
1406
+		// getting just the fields
1407
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
+	}
1409
+
1410
+
1411
+
1412
+	/**
1413
+	 * This sets the _timezone property after model object has been instantiated.
1414
+	 *
1415
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
+	 */
1417
+	public function set_timezone($timezone)
1418
+	{
1419
+		if ($timezone !== null) {
1420
+			$this->_timezone = $timezone;
1421
+		}
1422
+		// note we need to loop through relations and set the timezone on those objects as well.
1423
+		foreach ($this->_model_relations as $relation) {
1424
+			$relation->set_timezone($timezone);
1425
+		}
1426
+		// and finally we do the same for any datetime fields
1427
+		foreach ($this->_fields as $field) {
1428
+			if ($field instanceof EE_Datetime_Field) {
1429
+				$field->set_timezone($timezone);
1430
+			}
1431
+		}
1432
+	}
1433
+
1434
+
1435
+
1436
+	/**
1437
+	 * This just returns whatever is set for the current timezone.
1438
+	 *
1439
+	 * @access public
1440
+	 * @return string
1441
+	 */
1442
+	public function get_timezone()
1443
+	{
1444
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
+		if (empty($this->_timezone)) {
1446
+			foreach ($this->_fields as $field) {
1447
+				if ($field instanceof EE_Datetime_Field) {
1448
+					$this->set_timezone($field->get_timezone());
1449
+					break;
1450
+				}
1451
+			}
1452
+		}
1453
+		// if timezone STILL empty then return the default timezone for the site.
1454
+		if (empty($this->_timezone)) {
1455
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
+		}
1457
+		return $this->_timezone;
1458
+	}
1459
+
1460
+
1461
+
1462
+	/**
1463
+	 * This returns the date formats set for the given field name and also ensures that
1464
+	 * $this->_timezone property is set correctly.
1465
+	 *
1466
+	 * @since 4.6.x
1467
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1468
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
+	 * @return array formats in an array with the date format first, and the time format last.
1471
+	 */
1472
+	public function get_formats_for($field_name, $pretty = false)
1473
+	{
1474
+		$field_settings = $this->field_settings_for($field_name);
1475
+		// if not a valid EE_Datetime_Field then throw error
1476
+		if (! $field_settings instanceof EE_Datetime_Field) {
1477
+			throw new EE_Error(sprintf(esc_html__(
1478
+				'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.',
1479
+				'event_espresso'
1480
+			), $field_name));
1481
+		}
1482
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
+		// the field.
1484
+		$this->_timezone = $field_settings->get_timezone();
1485
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
+	}
1487
+
1488
+
1489
+
1490
+	/**
1491
+	 * This returns the current time in a format setup for a query on this model.
1492
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
+	 * it will return:
1494
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
+	 *  NOW
1496
+	 *  - or a unix timestamp (equivalent to time())
1497
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
+	 * @since 4.6.x
1501
+	 * @param string $field_name       The field the current time is needed for.
1502
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
+	 *                                 formatted string matching the set format for the field in the set timezone will
1504
+	 *                                 be returned.
1505
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
+	 *                                 exception is triggered.
1509
+	 */
1510
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
+	{
1512
+		$formats = $this->get_formats_for($field_name);
1513
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
+		if ($timestamp) {
1515
+			return $DateTime->format('U');
1516
+		}
1517
+		// not returning timestamp, so return formatted string in timezone.
1518
+		switch ($what) {
1519
+			case 'time':
1520
+				return $DateTime->format($formats[1]);
1521
+				break;
1522
+			case 'date':
1523
+				return $DateTime->format($formats[0]);
1524
+				break;
1525
+			default:
1526
+				return $DateTime->format(implode(' ', $formats));
1527
+				break;
1528
+		}
1529
+	}
1530
+
1531
+
1532
+
1533
+	/**
1534
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
+	 * for the model are.  Returns a DateTime object.
1536
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
+	 * ignored.
1539
+	 *
1540
+	 * @param string $field_name      The field being setup.
1541
+	 * @param string $timestring      The date time string being used.
1542
+	 * @param string $incoming_format The format for the time string.
1543
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
+	 *                                format is
1546
+	 *                                'U', this is ignored.
1547
+	 * @return DateTime
1548
+	 * @throws EE_Error
1549
+	 */
1550
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
+	{
1552
+		// just using this to ensure the timezone is set correctly internally
1553
+		$this->get_formats_for($field_name);
1554
+		// load EEH_DTT_Helper
1555
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
+	 *
1566
+	 * @return EE_Table_Base[]
1567
+	 */
1568
+	public function get_tables()
1569
+	{
1570
+		return $this->_tables;
1571
+	}
1572
+
1573
+
1574
+
1575
+	/**
1576
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
+	 * model object with EVT_ID = 1
1582
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
+	 * are not specified)
1587
+	 *
1588
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1593
+	 *                                         ID=34, we'd use this method as follows:
1594
+	 *                                         EEM_Transaction::instance()->update(
1595
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
+	 *                                         array(array('TXN_ID'=>34)));
1597
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
+	 *                                         TRUE, it is assumed that you've already called
1604
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
+	 *                                         malicious javascript. However, if
1606
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
+	 *                                         and every other field, before insertion. We provide this parameter
1609
+	 *                                         because model objects perform their prepare_for_set function on all
1610
+	 *                                         their values, and so don't need to be called again (and in many cases,
1611
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
+	 *                                         prepare_for_set method...)
1613
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
+	 *                                         in this model's entity map according to $fields_n_values that match
1615
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1616
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1617
+	 *                                         could get out-of-sync with the database
1618
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
+	 *                                         bad)
1621
+	 * @throws EE_Error
1622
+	 */
1623
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
+	{
1625
+		if (! is_array($query_params)) {
1626
+			EE_Error::doing_it_wrong(
1627
+				'EEM_Base::update',
1628
+				sprintf(
1629
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
+					gettype($query_params)
1631
+				),
1632
+				'4.6.0'
1633
+			);
1634
+			$query_params = array();
1635
+		}
1636
+		/**
1637
+		 * Action called before a model update call has been made.
1638
+		 *
1639
+		 * @param EEM_Base $model
1640
+		 * @param array    $fields_n_values the updated fields and their new values
1641
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
+		 */
1643
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
+		/**
1645
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1646
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1647
+		 *
1648
+		 * @param array    $fields_n_values fields and their new values
1649
+		 * @param EEM_Base $model           the model being queried
1650
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
+		 */
1652
+		$fields_n_values = (array) apply_filters(
1653
+			'FHEE__EEM_Base__update__fields_n_values',
1654
+			$fields_n_values,
1655
+			$this,
1656
+			$query_params
1657
+		);
1658
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
+		// to do that, for each table, verify that it's PK isn't null.
1660
+		$tables = $this->get_tables();
1661
+		// 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
1662
+		// NOTE: we should make this code more efficient by NOT querying twice
1663
+		// before the real update, but that needs to first go through ALPHA testing
1664
+		// as it's dangerous. says Mike August 8 2014
1665
+		// we want to make sure the default_where strategy is ignored
1666
+		$this->_ignore_where_strategy = true;
1667
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
+		foreach ($wpdb_select_results as $wpdb_result) {
1669
+			// type cast stdClass as array
1670
+			$wpdb_result = (array) $wpdb_result;
1671
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
+			if ($this->has_primary_key_field()) {
1673
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
+			} else {
1675
+				// 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)
1676
+				$main_table_pk_value = null;
1677
+			}
1678
+			// 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
1679
+			// 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
1680
+			if (count($tables) > 1) {
1681
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
+				// in that table, and so we'll want to insert one
1683
+				foreach ($tables as $table_obj) {
1684
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
+					// if there is no private key for this table on the results, it means there's no entry
1686
+					// in this table, right? so insert a row in the current table, using any fields available
1687
+					if (
1688
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
+						   && $wpdb_result[ $this_table_pk_column ])
1690
+					) {
1691
+						$success = $this->_insert_into_specific_table(
1692
+							$table_obj,
1693
+							$fields_n_values,
1694
+							$main_table_pk_value
1695
+						);
1696
+						// if we died here, report the error
1697
+						if (! $success) {
1698
+							return false;
1699
+						}
1700
+					}
1701
+				}
1702
+			}
1703
+			//              //and now check that if we have cached any models by that ID on the model, that
1704
+			//              //they also get updated properly
1705
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
+			//              if( $model_object ){
1707
+			//                  foreach( $fields_n_values as $field => $value ){
1708
+			//                      $model_object->set($field, $value);
1709
+			// let's make sure default_where strategy is followed now
1710
+			$this->_ignore_where_strategy = false;
1711
+		}
1712
+		// if we want to keep model objects in sync, AND
1713
+		// if this wasn't called from a model object (to update itself)
1714
+		// then we want to make sure we keep all the existing
1715
+		// model objects in sync with the db
1716
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
+			if ($this->has_primary_key_field()) {
1718
+				$model_objs_affected_ids = $this->get_col($query_params);
1719
+			} else {
1720
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
+				$model_objs_affected_ids = array();
1723
+				foreach ($models_affected_key_columns as $row) {
1724
+					$combined_index_key = $this->get_index_primary_key_string($row);
1725
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
+				}
1727
+			}
1728
+			if (! $model_objs_affected_ids) {
1729
+				// wait wait wait- if nothing was affected let's stop here
1730
+				return 0;
1731
+			}
1732
+			foreach ($model_objs_affected_ids as $id) {
1733
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
+				if ($model_obj_in_entity_map) {
1735
+					foreach ($fields_n_values as $field => $new_value) {
1736
+						$model_obj_in_entity_map->set($field, $new_value);
1737
+					}
1738
+				}
1739
+			}
1740
+			// if there is a primary key on this model, we can now do a slight optimization
1741
+			if ($this->has_primary_key_field()) {
1742
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
+				$query_params = array(
1744
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
+					'limit'                    => count($model_objs_affected_ids),
1746
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
+				);
1748
+			}
1749
+		}
1750
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
+		$SQL = "UPDATE "
1752
+			   . $model_query_info->get_full_join_sql()
1753
+			   . " SET "
1754
+			   . $this->_construct_update_sql($fields_n_values)
1755
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
+		/**
1758
+		 * Action called after a model update call has been made.
1759
+		 *
1760
+		 * @param EEM_Base $model
1761
+		 * @param array    $fields_n_values the updated fields and their new values
1762
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
+		 * @param int      $rows_affected
1764
+		 */
1765
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
+		return $rows_affected;// how many supposedly got updated
1767
+	}
1768
+
1769
+
1770
+
1771
+	/**
1772
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
+	 * are teh values of the field specified (or by default the primary key field)
1774
+	 * that matched the query params. Note that you should pass the name of the
1775
+	 * model FIELD, not the database table's column name.
1776
+	 *
1777
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
+	 * @param string $field_to_select
1779
+	 * @return array just like $wpdb->get_col()
1780
+	 * @throws EE_Error
1781
+	 */
1782
+	public function get_col($query_params = array(), $field_to_select = null)
1783
+	{
1784
+		if ($field_to_select) {
1785
+			$field = $this->field_settings_for($field_to_select);
1786
+		} elseif ($this->has_primary_key_field()) {
1787
+			$field = $this->get_primary_key_field();
1788
+		} else {
1789
+			// no primary key, just grab the first column
1790
+			$field = reset($this->field_settings());
1791
+		}
1792
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1793
+		$select_expressions = $field->get_qualified_column();
1794
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1795
+		return $this->_do_wpdb_query('get_col', array($SQL));
1796
+	}
1797
+
1798
+
1799
+
1800
+	/**
1801
+	 * Returns a single column value for a single row from the database
1802
+	 *
1803
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1804
+	 * @param string $field_to_select @see EEM_Base::get_col()
1805
+	 * @return string
1806
+	 * @throws EE_Error
1807
+	 */
1808
+	public function get_var($query_params = array(), $field_to_select = null)
1809
+	{
1810
+		$query_params['limit'] = 1;
1811
+		$col = $this->get_col($query_params, $field_to_select);
1812
+		if (! empty($col)) {
1813
+			return reset($col);
1814
+		}
1815
+		return null;
1816
+	}
1817
+
1818
+
1819
+
1820
+	/**
1821
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1822
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1823
+	 * injection, but currently no further filtering is done
1824
+	 *
1825
+	 * @global      $wpdb
1826
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1827
+	 *                               be updated to in the DB
1828
+	 * @return string of SQL
1829
+	 * @throws EE_Error
1830
+	 */
1831
+	public function _construct_update_sql($fields_n_values)
1832
+	{
1833
+		/** @type WPDB $wpdb */
1834
+		global $wpdb;
1835
+		$cols_n_values = array();
1836
+		foreach ($fields_n_values as $field_name => $value) {
1837
+			$field_obj = $this->field_settings_for($field_name);
1838
+			// if the value is NULL, we want to assign the value to that.
1839
+			// wpdb->prepare doesn't really handle that properly
1840
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841
+			$value_sql = $prepared_value === null ? 'NULL'
1842
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1844
+		}
1845
+		return implode(",", $cols_n_values);
1846
+	}
1847
+
1848
+
1849
+
1850
+	/**
1851
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1852
+	 * Performs a HARD delete, meaning the database row should always be removed,
1853
+	 * not just have a flag field on it switched
1854
+	 * Wrapper for EEM_Base::delete_permanently()
1855
+	 *
1856
+	 * @param mixed $id
1857
+	 * @param boolean $allow_blocking
1858
+	 * @return int the number of rows deleted
1859
+	 * @throws EE_Error
1860
+	 */
1861
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1862
+	{
1863
+		return $this->delete_permanently(
1864
+			array(
1865
+				array($this->get_primary_key_field()->get_name() => $id),
1866
+				'limit' => 1,
1867
+			),
1868
+			$allow_blocking
1869
+		);
1870
+	}
1871
+
1872
+
1873
+
1874
+	/**
1875
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1876
+	 * Wrapper for EEM_Base::delete()
1877
+	 *
1878
+	 * @param mixed $id
1879
+	 * @param boolean $allow_blocking
1880
+	 * @return int the number of rows deleted
1881
+	 * @throws EE_Error
1882
+	 */
1883
+	public function delete_by_ID($id, $allow_blocking = true)
1884
+	{
1885
+		return $this->delete(
1886
+			array(
1887
+				array($this->get_primary_key_field()->get_name() => $id),
1888
+				'limit' => 1,
1889
+			),
1890
+			$allow_blocking
1891
+		);
1892
+	}
1893
+
1894
+
1895
+
1896
+	/**
1897
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1898
+	 * meaning if the model has a field that indicates its been "trashed" or
1899
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1900
+	 *
1901
+	 * @see EEM_Base::delete_permanently
1902
+	 * @param array   $query_params
1903
+	 * @param boolean $allow_blocking
1904
+	 * @return int how many rows got deleted
1905
+	 * @throws EE_Error
1906
+	 */
1907
+	public function delete($query_params, $allow_blocking = true)
1908
+	{
1909
+		return $this->delete_permanently($query_params, $allow_blocking);
1910
+	}
1911
+
1912
+
1913
+
1914
+	/**
1915
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1916
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1917
+	 * as archived, not actually deleted
1918
+	 *
1919
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1920
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1921
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1922
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1923
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1924
+	 *                                DB
1925
+	 * @return int how many rows got deleted
1926
+	 * @throws EE_Error
1927
+	 */
1928
+	public function delete_permanently($query_params, $allow_blocking = true)
1929
+	{
1930
+		/**
1931
+		 * Action called just before performing a real deletion query. You can use the
1932
+		 * model and its $query_params to find exactly which items will be deleted
1933
+		 *
1934
+		 * @param EEM_Base $model
1935
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1936
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1937
+		 *                                 to block (prevent) this deletion
1938
+		 */
1939
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1940
+		// some MySQL databases may be running safe mode, which may restrict
1941
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1942
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1943
+		// to delete them
1944
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1945
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1946
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1947
+			$columns_and_ids_for_deleting
1948
+		);
1949
+		/**
1950
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1951
+		 *
1952
+		 * @param EEM_Base $this  The model instance being acted on.
1953
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1954
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1955
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1956
+		 *                                                  derived from the incoming query parameters.
1957
+		 *                                                  @see details on the structure of this array in the phpdocs
1958
+		 *                                                  for the `_get_ids_for_delete_method`
1959
+		 *
1960
+		 */
1961
+		do_action(
1962
+			'AHEE__EEM_Base__delete__before_query',
1963
+			$this,
1964
+			$query_params,
1965
+			$allow_blocking,
1966
+			$columns_and_ids_for_deleting
1967
+		);
1968
+		if ($deletion_where_query_part) {
1969
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1970
+			$table_aliases = array_keys($this->_tables);
1971
+			$SQL = "DELETE "
1972
+				   . implode(", ", $table_aliases)
1973
+				   . " FROM "
1974
+				   . $model_query_info->get_full_join_sql()
1975
+				   . " WHERE "
1976
+				   . $deletion_where_query_part;
1977
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1978
+		} else {
1979
+			$rows_deleted = 0;
1980
+		}
1981
+
1982
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1983
+		// there was no error with the delete query.
1984
+		if (
1985
+			$this->has_primary_key_field()
1986
+			&& $rows_deleted !== false
1987
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1988
+		) {
1989
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1990
+			foreach ($ids_for_removal as $id) {
1991
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1993
+				}
1994
+			}
1995
+
1996
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1997
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1998
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1999
+			// (although it is possible).
2000
+			// Note this can be skipped by using the provided filter and returning false.
2001
+			if (
2002
+				apply_filters(
2003
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2004
+					! $this instanceof EEM_Extra_Meta,
2005
+					$this
2006
+				)
2007
+			) {
2008
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2009
+					0 => array(
2010
+						'EXM_type' => $this->get_this_model_name(),
2011
+						'OBJ_ID'   => array(
2012
+							'IN',
2013
+							$ids_for_removal
2014
+						)
2015
+					)
2016
+				));
2017
+			}
2018
+		}
2019
+
2020
+		/**
2021
+		 * Action called just after performing a real deletion query. Although at this point the
2022
+		 * items should have been deleted
2023
+		 *
2024
+		 * @param EEM_Base $model
2025
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2026
+		 * @param int      $rows_deleted
2027
+		 */
2028
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
+		return $rows_deleted;// how many supposedly got deleted
2030
+	}
2031
+
2032
+
2033
+
2034
+	/**
2035
+	 * Checks all the relations that throw error messages when there are blocking related objects
2036
+	 * for related model objects. If there are any related model objects on those relations,
2037
+	 * adds an EE_Error, and return true
2038
+	 *
2039
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2040
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
+	 *                                                 should be ignored when determining whether there are related
2042
+	 *                                                 model objects which block this model object's deletion. Useful
2043
+	 *                                                 if you know A is related to B and are considering deleting A,
2044
+	 *                                                 but want to see if A has any other objects blocking its deletion
2045
+	 *                                                 before removing the relation between A and B
2046
+	 * @return boolean
2047
+	 * @throws EE_Error
2048
+	 */
2049
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
+	{
2051
+		// first, if $ignore_this_model_obj was supplied, get its model
2052
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
+			$ignored_model = $ignore_this_model_obj->get_model();
2054
+		} else {
2055
+			$ignored_model = null;
2056
+		}
2057
+		// now check all the relations of $this_model_obj_or_id and see if there
2058
+		// are any related model objects blocking it?
2059
+		$is_blocked = false;
2060
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2062
+				// if $ignore_this_model_obj was supplied, then for the query
2063
+				// on that model needs to be told to ignore $ignore_this_model_obj
2064
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
+						array(
2067
+							$ignored_model->get_primary_key_field()->get_name() => array(
2068
+								'!=',
2069
+								$ignore_this_model_obj->ID(),
2070
+							),
2071
+						),
2072
+					));
2073
+				} else {
2074
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
+				}
2076
+				if ($related_model_objects) {
2077
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
+					$is_blocked = true;
2079
+				}
2080
+			}
2081
+		}
2082
+		return $is_blocked;
2083
+	}
2084
+
2085
+
2086
+	/**
2087
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
+	 * @param array $row_results_for_deleting
2089
+	 * @param bool  $allow_blocking
2090
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
+	 *                 deleted. Example:
2094
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2095
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
+	 *                 where each element is a group of columns and values that get deleted. Example:
2097
+	 *                      array(
2098
+	 *                          0 => array(
2099
+	 *                              'Term_Relationship.object_id' => 1
2100
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2101
+	 *                          ),
2102
+	 *                          1 => array(
2103
+	 *                              'Term_Relationship.object_id' => 1
2104
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2105
+	 *                          )
2106
+	 *                      )
2107
+	 * @throws EE_Error
2108
+	 */
2109
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
+	{
2111
+		$ids_to_delete_indexed_by_column = array();
2112
+		if ($this->has_primary_key_field()) {
2113
+			$primary_table = $this->_get_main_table();
2114
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
+			$other_tables = $this->_get_other_tables();
2116
+			$ids_to_delete_indexed_by_column = $query = array();
2117
+			foreach ($row_results_for_deleting as $item_to_delete) {
2118
+				// before we mark this item for deletion,
2119
+				// make sure there's no related entities blocking its deletion (if we're checking)
2120
+				if (
2121
+					$allow_blocking
2122
+					&& $this->delete_is_blocked_by_related_models(
2123
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2124
+					)
2125
+				) {
2126
+					continue;
2127
+				}
2128
+				// primary table deletes
2129
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2132
+				}
2133
+			}
2134
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
+			$fields = $this->get_combined_primary_key_fields();
2136
+			foreach ($row_results_for_deleting as $item_to_delete) {
2137
+				$ids_to_delete_indexed_by_column_for_row = array();
2138
+				foreach ($fields as $cpk_field) {
2139
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2140
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2142
+					}
2143
+				}
2144
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
+			}
2146
+		} else {
2147
+			// so there's no primary key and no combined key...
2148
+			// sorry, can't help you
2149
+			throw new EE_Error(
2150
+				sprintf(
2151
+					esc_html__(
2152
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
+						"event_espresso"
2154
+					),
2155
+					get_class($this)
2156
+				)
2157
+			);
2158
+		}
2159
+		return $ids_to_delete_indexed_by_column;
2160
+	}
2161
+
2162
+
2163
+	/**
2164
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2165
+	 * the corresponding query_part for the query performing the delete.
2166
+	 *
2167
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2168
+	 * @return string
2169
+	 * @throws EE_Error
2170
+	 */
2171
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2172
+	{
2173
+		$query_part = '';
2174
+		if (empty($ids_to_delete_indexed_by_column)) {
2175
+			return $query_part;
2176
+		} elseif ($this->has_primary_key_field()) {
2177
+			$query = array();
2178
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2180
+			}
2181
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
+			$ways_to_identify_a_row = array();
2184
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
+				$values_for_each_combined_primary_key_for_a_row = array();
2186
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
+				}
2189
+				$ways_to_identify_a_row[] = '('
2190
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
+											. ')';
2192
+			}
2193
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2194
+		}
2195
+		return $query_part;
2196
+	}
2197
+
2198
+
2199
+
2200
+	/**
2201
+	 * Gets the model field by the fully qualified name
2202
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
+	 * @return EE_Model_Field_Base
2204
+	 */
2205
+	public function get_field_by_column($qualified_column_name)
2206
+	{
2207
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2208
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2209
+				return $field_obj;
2210
+			}
2211
+		}
2212
+		throw new EE_Error(
2213
+			sprintf(
2214
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
+				$this->get_this_model_name(),
2216
+				$qualified_column_name
2217
+			)
2218
+		);
2219
+	}
2220
+
2221
+
2222
+
2223
+	/**
2224
+	 * Count all the rows that match criteria the model query params.
2225
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
+	 * column
2227
+	 *
2228
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2229
+	 * @param string $field_to_count field on model to count by (not column name)
2230
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
+	 *                               that by the setting $distinct to TRUE;
2232
+	 * @return int
2233
+	 * @throws EE_Error
2234
+	 */
2235
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
+	{
2237
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
+		if ($field_to_count) {
2239
+			$field_obj = $this->field_settings_for($field_to_count);
2240
+			$column_to_count = $field_obj->get_qualified_column();
2241
+		} elseif ($this->has_primary_key_field()) {
2242
+			$pk_field_obj = $this->get_primary_key_field();
2243
+			$column_to_count = $pk_field_obj->get_qualified_column();
2244
+		} else {
2245
+			// there's no primary key
2246
+			// if we're counting distinct items, and there's no primary key,
2247
+			// we need to list out the columns for distinction;
2248
+			// otherwise we can just use star
2249
+			if ($distinct) {
2250
+				$columns_to_use = array();
2251
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
+					$columns_to_use[] = $field_obj->get_qualified_column();
2253
+				}
2254
+				$column_to_count = implode(',', $columns_to_use);
2255
+			} else {
2256
+				$column_to_count = '*';
2257
+			}
2258
+		}
2259
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262
+	}
2263
+
2264
+
2265
+
2266
+	/**
2267
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
+	 *
2269
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2270
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2271
+	 * @return float
2272
+	 * @throws EE_Error
2273
+	 */
2274
+	public function sum($query_params, $field_to_sum = null)
2275
+	{
2276
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
+		if ($field_to_sum) {
2278
+			$field_obj = $this->field_settings_for($field_to_sum);
2279
+		} else {
2280
+			$field_obj = $this->get_primary_key_field();
2281
+		}
2282
+		$column_to_count = $field_obj->get_qualified_column();
2283
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
+		$data_type = $field_obj->get_wpdb_data_type();
2286
+		if ($data_type === '%d' || $data_type === '%s') {
2287
+			return (float) $return_value;
2288
+		}
2289
+		// must be %f
2290
+		return (float) $return_value;
2291
+	}
2292
+
2293
+
2294
+
2295
+	/**
2296
+	 * Just calls the specified method on $wpdb with the given arguments
2297
+	 * Consolidates a little extra error handling code
2298
+	 *
2299
+	 * @param string $wpdb_method
2300
+	 * @param array  $arguments_to_provide
2301
+	 * @throws EE_Error
2302
+	 * @global wpdb  $wpdb
2303
+	 * @return mixed
2304
+	 */
2305
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
+	{
2307
+		// if we're in maintenance mode level 2, DON'T run any queries
2308
+		// because level 2 indicates the database needs updating and
2309
+		// is probably out of sync with the code
2310
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
+			throw new EE_Error(sprintf(esc_html__(
2312
+				"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.",
2313
+				"event_espresso"
2314
+			)));
2315
+		}
2316
+		/** @type WPDB $wpdb */
2317
+		global $wpdb;
2318
+		if (! method_exists($wpdb, $wpdb_method)) {
2319
+			throw new EE_Error(sprintf(esc_html__(
2320
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2321
+				'event_espresso'
2322
+			), $wpdb_method));
2323
+		}
2324
+		if (WP_DEBUG) {
2325
+			$old_show_errors_value = $wpdb->show_errors;
2326
+			$wpdb->show_errors(false);
2327
+		}
2328
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2329
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2330
+		if (WP_DEBUG) {
2331
+			$wpdb->show_errors($old_show_errors_value);
2332
+			if (! empty($wpdb->last_error)) {
2333
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334
+			}
2335
+			if ($result === false) {
2336
+				throw new EE_Error(sprintf(esc_html__(
2337
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2338
+					'event_espresso'
2339
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2340
+			}
2341
+		} elseif ($result === false) {
2342
+			EE_Error::add_error(
2343
+				sprintf(
2344
+					esc_html__(
2345
+						'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"',
2346
+						'event_espresso'
2347
+					),
2348
+					$wpdb_method,
2349
+					var_export($arguments_to_provide, true),
2350
+					$wpdb->last_error
2351
+				),
2352
+				__FILE__,
2353
+				__FUNCTION__,
2354
+				__LINE__
2355
+			);
2356
+		}
2357
+		return $result;
2358
+	}
2359
+
2360
+
2361
+
2362
+	/**
2363
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2364
+	 * and if there's an error tries to verify the DB is correct. Uses
2365
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2366
+	 * we should try to fix the EE core db, the addons, or just give up
2367
+	 *
2368
+	 * @param string $wpdb_method
2369
+	 * @param array  $arguments_to_provide
2370
+	 * @return mixed
2371
+	 */
2372
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2373
+	{
2374
+		/** @type WPDB $wpdb */
2375
+		global $wpdb;
2376
+		$wpdb->last_error = null;
2377
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2378
+		// was there an error running the query? but we don't care on new activations
2379
+		// (we're going to setup the DB anyway on new activations)
2380
+		if (
2381
+			($result === false || ! empty($wpdb->last_error))
2382
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2383
+		) {
2384
+			switch (EEM_Base::$_db_verification_level) {
2385
+				case EEM_Base::db_verified_none:
2386
+					// let's double-check core's DB
2387
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2388
+					break;
2389
+				case EEM_Base::db_verified_core:
2390
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2391
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2392
+					break;
2393
+				case EEM_Base::db_verified_addons:
2394
+					// ummmm... you in trouble
2395
+					return $result;
2396
+					break;
2397
+			}
2398
+			if (! empty($error_message)) {
2399
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400
+				trigger_error($error_message);
2401
+			}
2402
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2403
+		}
2404
+		return $result;
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2411
+	 * EEM_Base::$_db_verification_level
2412
+	 *
2413
+	 * @param string $wpdb_method
2414
+	 * @param array  $arguments_to_provide
2415
+	 * @return string
2416
+	 */
2417
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2418
+	{
2419
+		/** @type WPDB $wpdb */
2420
+		global $wpdb;
2421
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2422
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2423
+		$error_message = sprintf(
2424
+			esc_html__(
2425
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2426
+				'event_espresso'
2427
+			),
2428
+			$wpdb->last_error,
2429
+			$wpdb_method,
2430
+			wp_json_encode($arguments_to_provide)
2431
+		);
2432
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2433
+		return $error_message;
2434
+	}
2435
+
2436
+
2437
+
2438
+	/**
2439
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2440
+	 * EEM_Base::$_db_verification_level
2441
+	 *
2442
+	 * @param $wpdb_method
2443
+	 * @param $arguments_to_provide
2444
+	 * @return string
2445
+	 */
2446
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2447
+	{
2448
+		/** @type WPDB $wpdb */
2449
+		global $wpdb;
2450
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2451
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2452
+		$error_message = sprintf(
2453
+			esc_html__(
2454
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
+				'event_espresso'
2456
+			),
2457
+			$wpdb->last_error,
2458
+			$wpdb_method,
2459
+			wp_json_encode($arguments_to_provide)
2460
+		);
2461
+		EE_System::instance()->initialize_addons();
2462
+		return $error_message;
2463
+	}
2464
+
2465
+
2466
+
2467
+	/**
2468
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2469
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2470
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2471
+	 * ..."
2472
+	 *
2473
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2474
+	 * @return string
2475
+	 */
2476
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477
+	{
2478
+		return " FROM " . $model_query_info->get_full_join_sql() .
2479
+			   $model_query_info->get_where_sql() .
2480
+			   $model_query_info->get_group_by_sql() .
2481
+			   $model_query_info->get_having_sql() .
2482
+			   $model_query_info->get_order_by_sql() .
2483
+			   $model_query_info->get_limit_sql();
2484
+	}
2485
+
2486
+
2487
+
2488
+	/**
2489
+	 * Set to easily debug the next X queries ran from this model.
2490
+	 *
2491
+	 * @param int $count
2492
+	 */
2493
+	public function show_next_x_db_queries($count = 1)
2494
+	{
2495
+		$this->_show_next_x_db_queries = $count;
2496
+	}
2497
+
2498
+
2499
+
2500
+	/**
2501
+	 * @param $sql_query
2502
+	 */
2503
+	public function show_db_query_if_previously_requested($sql_query)
2504
+	{
2505
+		if ($this->_show_next_x_db_queries > 0) {
2506
+			echo esc_html($sql_query);
2507
+			$this->_show_next_x_db_queries--;
2508
+		}
2509
+	}
2510
+
2511
+
2512
+
2513
+	/**
2514
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2515
+	 * There are the 3 cases:
2516
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2517
+	 * $otherModelObject has no ID, it is first saved.
2518
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2519
+	 * has no ID, it is first saved.
2520
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2521
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2522
+	 * join table
2523
+	 *
2524
+	 * @param        EE_Base_Class                     /int $thisModelObject
2525
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2526
+	 * @param string $relationName                     , key in EEM_Base::_relations
2527
+	 *                                                 an attendee to a group, you also want to specify which role they
2528
+	 *                                                 will have in that group. So you would use this parameter to
2529
+	 *                                                 specify array('role-column-name'=>'role-id')
2530
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2531
+	 *                                                 to for relation to methods that allow you to further specify
2532
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2533
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2534
+	 *                                                 because these will be inserted in any new rows created as well.
2535
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2536
+	 * @throws EE_Error
2537
+	 */
2538
+	public function add_relationship_to(
2539
+		$id_or_obj,
2540
+		$other_model_id_or_obj,
2541
+		$relationName,
2542
+		$extra_join_model_fields_n_values = array()
2543
+	) {
2544
+		$relation_obj = $this->related_settings_for($relationName);
2545
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2546
+	}
2547
+
2548
+
2549
+
2550
+	/**
2551
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2552
+	 * There are the 3 cases:
2553
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2554
+	 * error
2555
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2556
+	 * an error
2557
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2558
+	 *
2559
+	 * @param        EE_Base_Class /int $id_or_obj
2560
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2561
+	 * @param string $relationName key in EEM_Base::_relations
2562
+	 * @return boolean of success
2563
+	 * @throws EE_Error
2564
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2565
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2566
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2567
+	 *                             because these will be inserted in any new rows created as well.
2568
+	 */
2569
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2570
+	{
2571
+		$relation_obj = $this->related_settings_for($relationName);
2572
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2573
+	}
2574
+
2575
+
2576
+
2577
+	/**
2578
+	 * @param mixed           $id_or_obj
2579
+	 * @param string          $relationName
2580
+	 * @param array           $where_query_params
2581
+	 * @param EE_Base_Class[] objects to which relations were removed
2582
+	 * @return \EE_Base_Class[]
2583
+	 * @throws EE_Error
2584
+	 */
2585
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2586
+	{
2587
+		$relation_obj = $this->related_settings_for($relationName);
2588
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2589
+	}
2590
+
2591
+
2592
+
2593
+	/**
2594
+	 * Gets all the related items of the specified $model_name, using $query_params.
2595
+	 * Note: by default, we remove the "default query params"
2596
+	 * because we want to get even deleted items etc.
2597
+	 *
2598
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2599
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2600
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2601
+	 * @return EE_Base_Class[]
2602
+	 * @throws EE_Error
2603
+	 */
2604
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2605
+	{
2606
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2607
+		$relation_settings = $this->related_settings_for($model_name);
2608
+		return $relation_settings->get_all_related($model_obj, $query_params);
2609
+	}
2610
+
2611
+
2612
+
2613
+	/**
2614
+	 * Deletes all the model objects across the relation indicated by $model_name
2615
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2616
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2617
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2618
+	 *
2619
+	 * @param EE_Base_Class|int|string $id_or_obj
2620
+	 * @param string                   $model_name
2621
+	 * @param array                    $query_params
2622
+	 * @return int how many deleted
2623
+	 * @throws EE_Error
2624
+	 */
2625
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2626
+	{
2627
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2628
+		$relation_settings = $this->related_settings_for($model_name);
2629
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2630
+	}
2631
+
2632
+
2633
+
2634
+	/**
2635
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2636
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2637
+	 * the model objects can't be hard deleted because of blocking related model objects,
2638
+	 * just does a soft-delete on them instead.
2639
+	 *
2640
+	 * @param EE_Base_Class|int|string $id_or_obj
2641
+	 * @param string                   $model_name
2642
+	 * @param array                    $query_params
2643
+	 * @return int how many deleted
2644
+	 * @throws EE_Error
2645
+	 */
2646
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2647
+	{
2648
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2649
+		$relation_settings = $this->related_settings_for($model_name);
2650
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2651
+	}
2652
+
2653
+
2654
+
2655
+	/**
2656
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2657
+	 * unless otherwise specified in the $query_params
2658
+	 *
2659
+	 * @param        int             /EE_Base_Class $id_or_obj
2660
+	 * @param string $model_name     like 'Event', or 'Registration'
2661
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2662
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2663
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2664
+	 *                               that by the setting $distinct to TRUE;
2665
+	 * @return int
2666
+	 * @throws EE_Error
2667
+	 */
2668
+	public function count_related(
2669
+		$id_or_obj,
2670
+		$model_name,
2671
+		$query_params = array(),
2672
+		$field_to_count = null,
2673
+		$distinct = false
2674
+	) {
2675
+		$related_model = $this->get_related_model_obj($model_name);
2676
+		// we're just going to use the query params on the related model's normal get_all query,
2677
+		// except add a condition to say to match the current mod
2678
+		if (! isset($query_params['default_where_conditions'])) {
2679
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680
+		}
2681
+		$this_model_name = $this->get_this_model_name();
2682
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2684
+		return $related_model->count($query_params, $field_to_count, $distinct);
2685
+	}
2686
+
2687
+
2688
+
2689
+	/**
2690
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2691
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2692
+	 *
2693
+	 * @param        int           /EE_Base_Class $id_or_obj
2694
+	 * @param string $model_name   like 'Event', or 'Registration'
2695
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2696
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2697
+	 * @return float
2698
+	 * @throws EE_Error
2699
+	 */
2700
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701
+	{
2702
+		$related_model = $this->get_related_model_obj($model_name);
2703
+		if (! is_array($query_params)) {
2704
+			EE_Error::doing_it_wrong(
2705
+				'EEM_Base::sum_related',
2706
+				sprintf(
2707
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2708
+					gettype($query_params)
2709
+				),
2710
+				'4.6.0'
2711
+			);
2712
+			$query_params = array();
2713
+		}
2714
+		// we're just going to use the query params on the related model's normal get_all query,
2715
+		// except add a condition to say to match the current mod
2716
+		if (! isset($query_params['default_where_conditions'])) {
2717
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718
+		}
2719
+		$this_model_name = $this->get_this_model_name();
2720
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2722
+		return $related_model->sum($query_params, $field_to_sum);
2723
+	}
2724
+
2725
+
2726
+
2727
+	/**
2728
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2729
+	 * $modelObject
2730
+	 *
2731
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2732
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2733
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2734
+	 * @return EE_Base_Class
2735
+	 * @throws EE_Error
2736
+	 */
2737
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2738
+	{
2739
+		$query_params['limit'] = 1;
2740
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2741
+		if ($results) {
2742
+			return array_shift($results);
2743
+		}
2744
+		return null;
2745
+	}
2746
+
2747
+
2748
+
2749
+	/**
2750
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2751
+	 *
2752
+	 * @return string
2753
+	 */
2754
+	public function get_this_model_name()
2755
+	{
2756
+		return str_replace("EEM_", "", get_class($this));
2757
+	}
2758
+
2759
+
2760
+
2761
+	/**
2762
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2763
+	 *
2764
+	 * @return EE_Any_Foreign_Model_Name_Field
2765
+	 * @throws EE_Error
2766
+	 */
2767
+	public function get_field_containing_related_model_name()
2768
+	{
2769
+		foreach ($this->field_settings(true) as $field) {
2770
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2771
+				$field_with_model_name = $field;
2772
+			}
2773
+		}
2774
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2775
+			throw new EE_Error(sprintf(
2776
+				esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777
+				$this->get_this_model_name()
2778
+			));
2779
+		}
2780
+		return $field_with_model_name;
2781
+	}
2782
+
2783
+
2784
+
2785
+	/**
2786
+	 * Inserts a new entry into the database, for each table.
2787
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2788
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2789
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2790
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2791
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2792
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2793
+	 *
2794
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2795
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2796
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2797
+	 *                              of EEM_Base)
2798
+	 * @return int|string new primary key on main table that got inserted
2799
+	 * @throws EE_Error
2800
+	 */
2801
+	public function insert($field_n_values)
2802
+	{
2803
+		/**
2804
+		 * Filters the fields and their values before inserting an item using the models
2805
+		 *
2806
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2807
+		 * @param EEM_Base $model           the model used
2808
+		 */
2809
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2810
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2811
+			$main_table = $this->_get_main_table();
2812
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2813
+			if ($new_id !== false) {
2814
+				foreach ($this->_get_other_tables() as $other_table) {
2815
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2816
+				}
2817
+			}
2818
+			/**
2819
+			 * Done just after attempting to insert a new model object
2820
+			 *
2821
+			 * @param EEM_Base   $model           used
2822
+			 * @param array      $fields_n_values fields and their values
2823
+			 * @param int|string the              ID of the newly-inserted model object
2824
+			 */
2825
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2826
+			return $new_id;
2827
+		}
2828
+		return false;
2829
+	}
2830
+
2831
+
2832
+
2833
+	/**
2834
+	 * Checks that the result would satisfy the unique indexes on this model
2835
+	 *
2836
+	 * @param array  $field_n_values
2837
+	 * @param string $action
2838
+	 * @return boolean
2839
+	 * @throws EE_Error
2840
+	 */
2841
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2842
+	{
2843
+		foreach ($this->unique_indexes() as $index_name => $index) {
2844
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2845
+			if ($this->exists(array($uniqueness_where_params))) {
2846
+				EE_Error::add_error(
2847
+					sprintf(
2848
+						esc_html__(
2849
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2850
+							"event_espresso"
2851
+						),
2852
+						$action,
2853
+						$this->_get_class_name(),
2854
+						$index_name,
2855
+						implode(",", $index->field_names()),
2856
+						http_build_query($uniqueness_where_params)
2857
+					),
2858
+					__FILE__,
2859
+					__FUNCTION__,
2860
+					__LINE__
2861
+				);
2862
+				return false;
2863
+			}
2864
+		}
2865
+		return true;
2866
+	}
2867
+
2868
+
2869
+
2870
+	/**
2871
+	 * Checks the database for an item that conflicts (ie, if this item were
2872
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2873
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2874
+	 * can be either an EE_Base_Class or an array of fields n values
2875
+	 *
2876
+	 * @param EE_Base_Class|array $obj_or_fields_array
2877
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2878
+	 *                                                 when looking for conflicts
2879
+	 *                                                 (ie, if false, we ignore the model object's primary key
2880
+	 *                                                 when finding "conflicts". If true, it's also considered).
2881
+	 *                                                 Only works for INT primary key,
2882
+	 *                                                 STRING primary keys cannot be ignored
2883
+	 * @throws EE_Error
2884
+	 * @return EE_Base_Class|array
2885
+	 */
2886
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2887
+	{
2888
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2889
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2890
+		} elseif (is_array($obj_or_fields_array)) {
2891
+			$fields_n_values = $obj_or_fields_array;
2892
+		} else {
2893
+			throw new EE_Error(
2894
+				sprintf(
2895
+					esc_html__(
2896
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2897
+						"event_espresso"
2898
+					),
2899
+					get_class($this),
2900
+					$obj_or_fields_array
2901
+				)
2902
+			);
2903
+		}
2904
+		$query_params = array();
2905
+		if (
2906
+			$this->has_primary_key_field()
2907
+			&& ($include_primary_key
2908
+				|| $this->get_primary_key_field()
2909
+				   instanceof
2910
+				   EE_Primary_Key_String_Field)
2911
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2912
+		) {
2913
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2914
+		}
2915
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2918
+		}
2919
+		// if there is nothing to base this search on, then we shouldn't find anything
2920
+		if (empty($query_params)) {
2921
+			return array();
2922
+		}
2923
+		return $this->get_one($query_params);
2924
+	}
2925
+
2926
+
2927
+
2928
+	/**
2929
+	 * Like count, but is optimized and returns a boolean instead of an int
2930
+	 *
2931
+	 * @param array $query_params
2932
+	 * @return boolean
2933
+	 * @throws EE_Error
2934
+	 */
2935
+	public function exists($query_params)
2936
+	{
2937
+		$query_params['limit'] = 1;
2938
+		return $this->count($query_params) > 0;
2939
+	}
2940
+
2941
+
2942
+
2943
+	/**
2944
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2945
+	 *
2946
+	 * @param int|string $id
2947
+	 * @return boolean
2948
+	 * @throws EE_Error
2949
+	 */
2950
+	public function exists_by_ID($id)
2951
+	{
2952
+		return $this->exists(
2953
+			array(
2954
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2955
+				array(
2956
+					$this->primary_key_name() => $id,
2957
+				),
2958
+			)
2959
+		);
2960
+	}
2961
+
2962
+
2963
+
2964
+	/**
2965
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2966
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2967
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2968
+	 * on the main table)
2969
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2970
+	 * cases where we want to call it directly rather than via insert().
2971
+	 *
2972
+	 * @access   protected
2973
+	 * @param EE_Table_Base $table
2974
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2975
+	 *                                       float
2976
+	 * @param int           $new_id          for now we assume only int keys
2977
+	 * @throws EE_Error
2978
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2979
+	 * @return int ID of new row inserted, or FALSE on failure
2980
+	 */
2981
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2982
+	{
2983
+		global $wpdb;
2984
+		$insertion_col_n_values = array();
2985
+		$format_for_insertion = array();
2986
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2987
+		foreach ($fields_on_table as $field_name => $field_obj) {
2988
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2989
+			if ($field_obj->is_auto_increment()) {
2990
+				continue;
2991
+			}
2992
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2994
+			if ($prepared_value !== null) {
2995
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2996
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997
+			}
2998
+		}
2999
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3000
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3001
+			// so add the fk to the main table as a column
3002
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
+		}
3005
+		// insert the new entry
3006
+		$result = $this->_do_wpdb_query(
3007
+			'insert',
3008
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3009
+		);
3010
+		if ($result === false) {
3011
+			return false;
3012
+		}
3013
+		// ok, now what do we return for the ID of the newly-inserted thing?
3014
+		if ($this->has_primary_key_field()) {
3015
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3016
+				return $wpdb->insert_id;
3017
+			}
3018
+			// it's not an auto-increment primary key, so
3019
+			// it must have been supplied
3020
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3021
+		}
3022
+		// we can't return a  primary key because there is none. instead return
3023
+		// a unique string indicating this model
3024
+		return $this->get_index_primary_key_string($fields_n_values);
3025
+	}
3026
+
3027
+
3028
+
3029
+	/**
3030
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3031
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3032
+	 * and there is no default, we pass it along. WPDB will take care of it)
3033
+	 *
3034
+	 * @param EE_Model_Field_Base $field_obj
3035
+	 * @param array               $fields_n_values
3036
+	 * @return mixed string|int|float depending on what the table column will be expecting
3037
+	 * @throws EE_Error
3038
+	 */
3039
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3040
+	{
3041
+		// if this field doesn't allow nullable, don't allow it
3042
+		if (
3043
+			! $field_obj->is_nullable()
3044
+			&& (
3045
+				! isset($fields_n_values[ $field_obj->get_name() ])
3046
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3047
+			)
3048
+		) {
3049
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3050
+		}
3051
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
+			? $fields_n_values[ $field_obj->get_name() ]
3053
+			: null;
3054
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055
+	}
3056
+
3057
+
3058
+
3059
+	/**
3060
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3061
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3062
+	 * the field's prepare_for_set() method.
3063
+	 *
3064
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3065
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3066
+	 *                                   top of file)
3067
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3068
+	 *                                   $value is a custom selection
3069
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3070
+	 */
3071
+	private function _prepare_value_for_use_in_db($value, $field)
3072
+	{
3073
+		if ($field && $field instanceof EE_Model_Field_Base) {
3074
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3075
+			switch ($this->_values_already_prepared_by_model_object) {
3076
+				/** @noinspection PhpMissingBreakStatementInspection */
3077
+				case self::not_prepared_by_model_object:
3078
+					$value = $field->prepare_for_set($value);
3079
+				// purposefully left out "return"
3080
+				case self::prepared_by_model_object:
3081
+					/** @noinspection SuspiciousAssignmentsInspection */
3082
+					$value = $field->prepare_for_use_in_db($value);
3083
+				case self::prepared_for_use_in_db:
3084
+					// leave the value alone
3085
+			}
3086
+			return $value;
3087
+			// phpcs:enable
3088
+		}
3089
+		return $value;
3090
+	}
3091
+
3092
+
3093
+
3094
+	/**
3095
+	 * Returns the main table on this model
3096
+	 *
3097
+	 * @return EE_Primary_Table
3098
+	 * @throws EE_Error
3099
+	 */
3100
+	protected function _get_main_table()
3101
+	{
3102
+		foreach ($this->_tables as $table) {
3103
+			if ($table instanceof EE_Primary_Table) {
3104
+				return $table;
3105
+			}
3106
+		}
3107
+		throw new EE_Error(sprintf(esc_html__(
3108
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3109
+			'event_espresso'
3110
+		), get_class($this)));
3111
+	}
3112
+
3113
+
3114
+
3115
+	/**
3116
+	 * table
3117
+	 * returns EE_Primary_Table table name
3118
+	 *
3119
+	 * @return string
3120
+	 * @throws EE_Error
3121
+	 */
3122
+	public function table()
3123
+	{
3124
+		return $this->_get_main_table()->get_table_name();
3125
+	}
3126
+
3127
+
3128
+
3129
+	/**
3130
+	 * table
3131
+	 * returns first EE_Secondary_Table table name
3132
+	 *
3133
+	 * @return string
3134
+	 */
3135
+	public function second_table()
3136
+	{
3137
+		// grab second table from tables array
3138
+		$second_table = end($this->_tables);
3139
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3140
+	}
3141
+
3142
+
3143
+
3144
+	/**
3145
+	 * get_table_obj_by_alias
3146
+	 * returns table name given it's alias
3147
+	 *
3148
+	 * @param string $table_alias
3149
+	 * @return EE_Primary_Table | EE_Secondary_Table
3150
+	 */
3151
+	public function get_table_obj_by_alias($table_alias = '')
3152
+	{
3153
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3160
+	 *
3161
+	 * @return EE_Secondary_Table[]
3162
+	 */
3163
+	protected function _get_other_tables()
3164
+	{
3165
+		$other_tables = array();
3166
+		foreach ($this->_tables as $table_alias => $table) {
3167
+			if ($table instanceof EE_Secondary_Table) {
3168
+				$other_tables[ $table_alias ] = $table;
3169
+			}
3170
+		}
3171
+		return $other_tables;
3172
+	}
3173
+
3174
+
3175
+
3176
+	/**
3177
+	 * Finds all the fields that correspond to the given table
3178
+	 *
3179
+	 * @param string $table_alias , array key in EEM_Base::_tables
3180
+	 * @return EE_Model_Field_Base[]
3181
+	 */
3182
+	public function _get_fields_for_table($table_alias)
3183
+	{
3184
+		return $this->_fields[ $table_alias ];
3185
+	}
3186
+
3187
+
3188
+
3189
+	/**
3190
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3191
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3192
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3193
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3194
+	 * related Registration, Transaction, and Payment models.
3195
+	 *
3196
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3197
+	 * @return EE_Model_Query_Info_Carrier
3198
+	 * @throws EE_Error
3199
+	 */
3200
+	public function _extract_related_models_from_query($query_params)
3201
+	{
3202
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3203
+		if (array_key_exists(0, $query_params)) {
3204
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3205
+		}
3206
+		if (array_key_exists('group_by', $query_params)) {
3207
+			if (is_array($query_params['group_by'])) {
3208
+				$this->_extract_related_models_from_sub_params_array_values(
3209
+					$query_params['group_by'],
3210
+					$query_info_carrier,
3211
+					'group_by'
3212
+				);
3213
+			} elseif (! empty($query_params['group_by'])) {
3214
+				$this->_extract_related_model_info_from_query_param(
3215
+					$query_params['group_by'],
3216
+					$query_info_carrier,
3217
+					'group_by'
3218
+				);
3219
+			}
3220
+		}
3221
+		if (array_key_exists('having', $query_params)) {
3222
+			$this->_extract_related_models_from_sub_params_array_keys(
3223
+				$query_params[0],
3224
+				$query_info_carrier,
3225
+				'having'
3226
+			);
3227
+		}
3228
+		if (array_key_exists('order_by', $query_params)) {
3229
+			if (is_array($query_params['order_by'])) {
3230
+				$this->_extract_related_models_from_sub_params_array_keys(
3231
+					$query_params['order_by'],
3232
+					$query_info_carrier,
3233
+					'order_by'
3234
+				);
3235
+			} elseif (! empty($query_params['order_by'])) {
3236
+				$this->_extract_related_model_info_from_query_param(
3237
+					$query_params['order_by'],
3238
+					$query_info_carrier,
3239
+					'order_by'
3240
+				);
3241
+			}
3242
+		}
3243
+		if (array_key_exists('force_join', $query_params)) {
3244
+			$this->_extract_related_models_from_sub_params_array_values(
3245
+				$query_params['force_join'],
3246
+				$query_info_carrier,
3247
+				'force_join'
3248
+			);
3249
+		}
3250
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3251
+		return $query_info_carrier;
3252
+	}
3253
+
3254
+
3255
+
3256
+	/**
3257
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3258
+	 *
3259
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3260
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3261
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3262
+	 * @throws EE_Error
3263
+	 * @return \EE_Model_Query_Info_Carrier
3264
+	 */
3265
+	private function _extract_related_models_from_sub_params_array_keys(
3266
+		$sub_query_params,
3267
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268
+		$query_param_type
3269
+	) {
3270
+		if (! empty($sub_query_params)) {
3271
+			$sub_query_params = (array) $sub_query_params;
3272
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3274
+				$this->_extract_related_model_info_from_query_param(
3275
+					$param,
3276
+					$model_query_info_carrier,
3277
+					$query_param_type
3278
+				);
3279
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
+				// of array('Registration.TXN_ID'=>23)
3283
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
+					if (! is_array($possibly_array_of_params)) {
3286
+						throw new EE_Error(sprintf(
3287
+							esc_html__(
3288
+								"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'))",
3289
+								"event_espresso"
3290
+							),
3291
+							$param,
3292
+							$possibly_array_of_params
3293
+						));
3294
+					}
3295
+					$this->_extract_related_models_from_sub_params_array_keys(
3296
+						$possibly_array_of_params,
3297
+						$model_query_info_carrier,
3298
+						$query_param_type
3299
+					);
3300
+				} elseif (
3301
+					$query_param_type === 0 // ie WHERE
3302
+						  && is_array($possibly_array_of_params)
3303
+						  && isset($possibly_array_of_params[2])
3304
+						  && $possibly_array_of_params[2] == true
3305
+				) {
3306
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307
+					// indicating that $possible_array_of_params[1] is actually a field name,
3308
+					// from which we should extract query parameters!
3309
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310
+						throw new EE_Error(sprintf(esc_html__(
3311
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312
+							"event_espresso"
3313
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3314
+					}
3315
+					$this->_extract_related_model_info_from_query_param(
3316
+						$possibly_array_of_params[1],
3317
+						$model_query_info_carrier,
3318
+						$query_param_type
3319
+					);
3320
+				}
3321
+			}
3322
+		}
3323
+		return $model_query_info_carrier;
3324
+	}
3325
+
3326
+
3327
+
3328
+	/**
3329
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3330
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3331
+	 *
3332
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3333
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3334
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3335
+	 * @throws EE_Error
3336
+	 * @return \EE_Model_Query_Info_Carrier
3337
+	 */
3338
+	private function _extract_related_models_from_sub_params_array_values(
3339
+		$sub_query_params,
3340
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341
+		$query_param_type
3342
+	) {
3343
+		if (! empty($sub_query_params)) {
3344
+			if (! is_array($sub_query_params)) {
3345
+				throw new EE_Error(sprintf(
3346
+					esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347
+					$sub_query_params
3348
+				));
3349
+			}
3350
+			foreach ($sub_query_params as $param) {
3351
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3352
+				$this->_extract_related_model_info_from_query_param(
3353
+					$param,
3354
+					$model_query_info_carrier,
3355
+					$query_param_type
3356
+				);
3357
+			}
3358
+		}
3359
+		return $model_query_info_carrier;
3360
+	}
3361
+
3362
+
3363
+	/**
3364
+	 * Extract all the query parts from  model query params
3365
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3366
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3367
+	 * but use them in a different order. Eg, we need to know what models we are querying
3368
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3369
+	 * other models before we can finalize the where clause SQL.
3370
+	 *
3371
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3372
+	 * @throws EE_Error
3373
+	 * @return EE_Model_Query_Info_Carrier
3374
+	 * @throws ModelConfigurationException
3375
+	 */
3376
+	public function _create_model_query_info_carrier($query_params)
3377
+	{
3378
+		if (! is_array($query_params)) {
3379
+			EE_Error::doing_it_wrong(
3380
+				'EEM_Base::_create_model_query_info_carrier',
3381
+				sprintf(
3382
+					esc_html__(
3383
+						'$query_params should be an array, you passed a variable of type %s',
3384
+						'event_espresso'
3385
+					),
3386
+					gettype($query_params)
3387
+				),
3388
+				'4.6.0'
3389
+			);
3390
+			$query_params = array();
3391
+		}
3392
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3393
+		// first check if we should alter the query to account for caps or not
3394
+		// because the caps might require us to do extra joins
3395
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3396
+			$query_params[0] = array_replace_recursive(
3397
+				$query_params[0],
3398
+				$this->caps_where_conditions(
3399
+					$query_params['caps']
3400
+				)
3401
+			);
3402
+		}
3403
+
3404
+		// check if we should alter the query to remove data related to protected
3405
+		// custom post types
3406
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3407
+			$where_param_key_for_password = $this->modelChainAndPassword();
3408
+			// only include if related to a cpt where no password has been set
3409
+			$query_params[0]['OR*nopassword'] = array(
3410
+				$where_param_key_for_password => '',
3411
+				$where_param_key_for_password . '*' => array('IS_NULL')
3412
+			);
3413
+		}
3414
+		$query_object = $this->_extract_related_models_from_query($query_params);
3415
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3416
+		foreach ($query_params[0] as $key => $value) {
3417
+			if (is_int($key)) {
3418
+				throw new EE_Error(
3419
+					sprintf(
3420
+						esc_html__(
3421
+							"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.",
3422
+							"event_espresso"
3423
+						),
3424
+						$key,
3425
+						var_export($value, true),
3426
+						var_export($query_params, true),
3427
+						get_class($this)
3428
+					)
3429
+				);
3430
+			}
3431
+		}
3432
+		if (
3433
+			array_key_exists('default_where_conditions', $query_params)
3434
+			&& ! empty($query_params['default_where_conditions'])
3435
+		) {
3436
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3437
+		} else {
3438
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3439
+		}
3440
+		$query_params[0] = array_merge(
3441
+			$this->_get_default_where_conditions_for_models_in_query(
3442
+				$query_object,
3443
+				$use_default_where_conditions,
3444
+				$query_params[0]
3445
+			),
3446
+			$query_params[0]
3447
+		);
3448
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3449
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3450
+		// So we need to setup a subquery and use that for the main join.
3451
+		// Note for now this only works on the primary table for the model.
3452
+		// So for instance, you could set the limit array like this:
3453
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3454
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3455
+			$query_object->set_main_model_join_sql(
3456
+				$this->_construct_limit_join_select(
3457
+					$query_params['on_join_limit'][0],
3458
+					$query_params['on_join_limit'][1]
3459
+				)
3460
+			);
3461
+		}
3462
+		// set limit
3463
+		if (array_key_exists('limit', $query_params)) {
3464
+			if (is_array($query_params['limit'])) {
3465
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466
+					$e = sprintf(
3467
+						esc_html__(
3468
+							"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)",
3469
+							"event_espresso"
3470
+						),
3471
+						http_build_query($query_params['limit'])
3472
+					);
3473
+					throw new EE_Error($e . "|" . $e);
3474
+				}
3475
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
+			} elseif (! empty($query_params['limit'])) {
3478
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3479
+			}
3480
+		}
3481
+		// set order by
3482
+		if (array_key_exists('order_by', $query_params)) {
3483
+			if (is_array($query_params['order_by'])) {
3484
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3485
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3486
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3487
+				if (array_key_exists('order', $query_params)) {
3488
+					throw new EE_Error(
3489
+						sprintf(
3490
+							esc_html__(
3491
+								"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 ",
3492
+								"event_espresso"
3493
+							),
3494
+							get_class($this),
3495
+							implode(", ", array_keys($query_params['order_by'])),
3496
+							implode(", ", $query_params['order_by']),
3497
+							$query_params['order']
3498
+						)
3499
+					);
3500
+				}
3501
+				$this->_extract_related_models_from_sub_params_array_keys(
3502
+					$query_params['order_by'],
3503
+					$query_object,
3504
+					'order_by'
3505
+				);
3506
+				// assume it's an array of fields to order by
3507
+				$order_array = array();
3508
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509
+					$order = $this->_extract_order($order);
3510
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3511
+				}
3512
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
+			} elseif (! empty($query_params['order_by'])) {
3514
+				$this->_extract_related_model_info_from_query_param(
3515
+					$query_params['order_by'],
3516
+					$query_object,
3517
+					'order',
3518
+					$query_params['order_by']
3519
+				);
3520
+				$order = isset($query_params['order'])
3521
+					? $this->_extract_order($query_params['order'])
3522
+					: 'DESC';
3523
+				$query_object->set_order_by_sql(
3524
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3525
+				);
3526
+			}
3527
+		}
3528
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3529
+		if (
3530
+			! array_key_exists('order_by', $query_params)
3531
+			&& array_key_exists('order', $query_params)
3532
+			&& ! empty($query_params['order'])
3533
+		) {
3534
+			$pk_field = $this->get_primary_key_field();
3535
+			$order = $this->_extract_order($query_params['order']);
3536
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3537
+		}
3538
+		// set group by
3539
+		if (array_key_exists('group_by', $query_params)) {
3540
+			if (is_array($query_params['group_by'])) {
3541
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3542
+				$group_by_array = array();
3543
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545
+				}
3546
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
+			} elseif (! empty($query_params['group_by'])) {
3548
+				$query_object->set_group_by_sql(
3549
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3550
+				);
3551
+			}
3552
+		}
3553
+		// set having
3554
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3555
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3556
+		}
3557
+		// now, just verify they didn't pass anything wack
3558
+		foreach ($query_params as $query_key => $query_value) {
3559
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3560
+				throw new EE_Error(
3561
+					sprintf(
3562
+						esc_html__(
3563
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3564
+							'event_espresso'
3565
+						),
3566
+						$query_key,
3567
+						get_class($this),
3568
+						//                      print_r( $this->_allowed_query_params, TRUE )
3569
+						implode(',', $this->_allowed_query_params)
3570
+					)
3571
+				);
3572
+			}
3573
+		}
3574
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3575
+		if (empty($main_model_join_sql)) {
3576
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3577
+		}
3578
+		return $query_object;
3579
+	}
3580
+
3581
+
3582
+
3583
+	/**
3584
+	 * Gets the where conditions that should be imposed on the query based on the
3585
+	 * context (eg reading frontend, backend, edit or delete).
3586
+	 *
3587
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3588
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3589
+	 * @throws EE_Error
3590
+	 */
3591
+	public function caps_where_conditions($context = self::caps_read)
3592
+	{
3593
+		EEM_Base::verify_is_valid_cap_context($context);
3594
+		$cap_where_conditions = array();
3595
+		$cap_restrictions = $this->caps_missing($context);
3596
+		/**
3597
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3598
+		 */
3599
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3600
+			$cap_where_conditions = array_replace_recursive(
3601
+				$cap_where_conditions,
3602
+				$restriction_if_no_cap->get_default_where_conditions()
3603
+			);
3604
+		}
3605
+		return apply_filters(
3606
+			'FHEE__EEM_Base__caps_where_conditions__return',
3607
+			$cap_where_conditions,
3608
+			$this,
3609
+			$context,
3610
+			$cap_restrictions
3611
+		);
3612
+	}
3613
+
3614
+
3615
+
3616
+	/**
3617
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3618
+	 * otherwise throws an exception
3619
+	 *
3620
+	 * @param string $should_be_order_string
3621
+	 * @return string either ASC, asc, DESC or desc
3622
+	 * @throws EE_Error
3623
+	 */
3624
+	private function _extract_order($should_be_order_string)
3625
+	{
3626
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3627
+			return $should_be_order_string;
3628
+		}
3629
+		throw new EE_Error(
3630
+			sprintf(
3631
+				esc_html__(
3632
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3633
+					"event_espresso"
3634
+				),
3635
+				get_class($this),
3636
+				$should_be_order_string
3637
+			)
3638
+		);
3639
+	}
3640
+
3641
+
3642
+
3643
+	/**
3644
+	 * Looks at all the models which are included in this query, and asks each
3645
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3646
+	 * so they can be merged
3647
+	 *
3648
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3649
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3650
+	 *                                                                  'none' means NO default where conditions will
3651
+	 *                                                                  be used AT ALL during this query.
3652
+	 *                                                                  'other_models_only' means default where
3653
+	 *                                                                  conditions from other models will be used, but
3654
+	 *                                                                  not for this primary model. 'all', the default,
3655
+	 *                                                                  means default where conditions will apply as
3656
+	 *                                                                  normal
3657
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3658
+	 * @throws EE_Error
3659
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
+	 */
3661
+	private function _get_default_where_conditions_for_models_in_query(
3662
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3663
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3664
+		$where_query_params = array()
3665
+	) {
3666
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668
+			throw new EE_Error(sprintf(
3669
+				esc_html__(
3670
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3671
+					"event_espresso"
3672
+				),
3673
+				$use_default_where_conditions,
3674
+				implode(", ", $allowed_used_default_where_conditions_values)
3675
+			));
3676
+		}
3677
+		$universal_query_params = array();
3678
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3679
+			$universal_query_params = $this->_get_default_where_conditions();
3680
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3681
+			$universal_query_params = $this->_get_minimum_where_conditions();
3682
+		}
3683
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3684
+			$related_model = $this->get_related_model_obj($model_name);
3685
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3686
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3687
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3688
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3689
+			} else {
3690
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3691
+				continue;
3692
+			}
3693
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3694
+				$related_model_universal_where_params,
3695
+				$where_query_params,
3696
+				$related_model,
3697
+				$model_relation_path
3698
+			);
3699
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3700
+				$universal_query_params,
3701
+				$overrides
3702
+			);
3703
+		}
3704
+		return $universal_query_params;
3705
+	}
3706
+
3707
+
3708
+
3709
+	/**
3710
+	 * Determines whether or not we should use default where conditions for the model in question
3711
+	 * (this model, or other related models).
3712
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3713
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3714
+	 * We should use default where conditions on related models when they requested to use default where conditions
3715
+	 * on all models, or specifically just on other related models
3716
+	 * @param      $default_where_conditions_value
3717
+	 * @param bool $for_this_model false means this is for OTHER related models
3718
+	 * @return bool
3719
+	 */
3720
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
+	{
3722
+		return (
3723
+				   $for_this_model
3724
+				   && in_array(
3725
+					   $default_where_conditions_value,
3726
+					   array(
3727
+						   EEM_Base::default_where_conditions_all,
3728
+						   EEM_Base::default_where_conditions_this_only,
3729
+						   EEM_Base::default_where_conditions_minimum_others,
3730
+					   ),
3731
+					   true
3732
+				   )
3733
+			   )
3734
+			   || (
3735
+				   ! $for_this_model
3736
+				   && in_array(
3737
+					   $default_where_conditions_value,
3738
+					   array(
3739
+						   EEM_Base::default_where_conditions_all,
3740
+						   EEM_Base::default_where_conditions_others_only,
3741
+					   ),
3742
+					   true
3743
+				   )
3744
+			   );
3745
+	}
3746
+
3747
+	/**
3748
+	 * Determines whether or not we should use default minimum conditions for the model in question
3749
+	 * (this model, or other related models).
3750
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3751
+	 * where conditions.
3752
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3753
+	 * on this model or others
3754
+	 * @param      $default_where_conditions_value
3755
+	 * @param bool $for_this_model false means this is for OTHER related models
3756
+	 * @return bool
3757
+	 */
3758
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3759
+	{
3760
+		return (
3761
+				   $for_this_model
3762
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3763
+			   )
3764
+			   || (
3765
+				   ! $for_this_model
3766
+				   && in_array(
3767
+					   $default_where_conditions_value,
3768
+					   array(
3769
+						   EEM_Base::default_where_conditions_minimum_others,
3770
+						   EEM_Base::default_where_conditions_minimum_all,
3771
+					   ),
3772
+					   true
3773
+				   )
3774
+			   );
3775
+	}
3776
+
3777
+
3778
+	/**
3779
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3780
+	 * then we also add a special where condition which allows for that model's primary key
3781
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3782
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3783
+	 *
3784
+	 * @param array    $default_where_conditions
3785
+	 * @param array    $provided_where_conditions
3786
+	 * @param EEM_Base $model
3787
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3788
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3789
+	 * @throws EE_Error
3790
+	 */
3791
+	private function _override_defaults_or_make_null_friendly(
3792
+		$default_where_conditions,
3793
+		$provided_where_conditions,
3794
+		$model,
3795
+		$model_relation_path
3796
+	) {
3797
+		$null_friendly_where_conditions = array();
3798
+		$none_overridden = true;
3799
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3800
+		foreach ($default_where_conditions as $key => $val) {
3801
+			if (isset($provided_where_conditions[ $key ])) {
3802
+				$none_overridden = false;
3803
+			} else {
3804
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3805
+			}
3806
+		}
3807
+		if ($none_overridden && $default_where_conditions) {
3808
+			if ($model->has_primary_key_field()) {
3809
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3810
+																				. "."
3811
+																				. $model->primary_key_name() ] = array('IS NULL');
3812
+			}/*else{
3813 3813
                 //@todo NO PK, use other defaults
3814 3814
             }*/
3815
-        }
3816
-        return $null_friendly_where_conditions;
3817
-    }
3818
-
3819
-
3820
-
3821
-    /**
3822
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3823
-     * default where conditions on all get_all, update, and delete queries done by this model.
3824
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3825
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3826
-     *
3827
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3828
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3829
-     */
3830
-    private function _get_default_where_conditions($model_relation_path = null)
3831
-    {
3832
-        if ($this->_ignore_where_strategy) {
3833
-            return array();
3834
-        }
3835
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3836
-    }
3837
-
3838
-
3839
-
3840
-    /**
3841
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3842
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3843
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3844
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3845
-     * Similar to _get_default_where_conditions
3846
-     *
3847
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3848
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3849
-     */
3850
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3851
-    {
3852
-        if ($this->_ignore_where_strategy) {
3853
-            return array();
3854
-        }
3855
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3856
-    }
3857
-
3858
-
3859
-
3860
-    /**
3861
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3862
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3863
-     *
3864
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3865
-     * @return string
3866
-     * @throws EE_Error
3867
-     */
3868
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3869
-    {
3870
-        $selects = $this->_get_columns_to_select_for_this_model();
3871
-        foreach (
3872
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3873
-        ) {
3874
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3875
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3876
-            foreach ($other_model_selects as $key => $value) {
3877
-                $selects[] = $value;
3878
-            }
3879
-        }
3880
-        return implode(", ", $selects);
3881
-    }
3882
-
3883
-
3884
-
3885
-    /**
3886
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3887
-     * So that's going to be the columns for all the fields on the model
3888
-     *
3889
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3890
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3891
-     */
3892
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3893
-    {
3894
-        $fields = $this->field_settings();
3895
-        $selects = array();
3896
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3897
-            $model_relation_chain,
3898
-            $this->get_this_model_name()
3899
-        );
3900
-        foreach ($fields as $field_obj) {
3901
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3902
-                         . $field_obj->get_table_alias()
3903
-                         . "."
3904
-                         . $field_obj->get_table_column()
3905
-                         . " AS '"
3906
-                         . $table_alias_with_model_relation_chain_prefix
3907
-                         . $field_obj->get_table_alias()
3908
-                         . "."
3909
-                         . $field_obj->get_table_column()
3910
-                         . "'";
3911
-        }
3912
-        // make sure we are also getting the PKs of each table
3913
-        $tables = $this->get_tables();
3914
-        if (count($tables) > 1) {
3915
-            foreach ($tables as $table_obj) {
3916
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917
-                                       . $table_obj->get_fully_qualified_pk_column();
3918
-                if (! in_array($qualified_pk_column, $selects)) {
3919
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920
-                }
3921
-            }
3922
-        }
3923
-        return $selects;
3924
-    }
3925
-
3926
-
3927
-
3928
-    /**
3929
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3930
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3931
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3932
-     * SQL for joining, and the data types
3933
-     *
3934
-     * @param null|string                 $original_query_param
3935
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3936
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3937
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3938
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3939
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3940
-     *                                                          or 'Registration's
3941
-     * @param string                      $original_query_param what it originally was (eg
3942
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3943
-     *                                                          matches $query_param
3944
-     * @throws EE_Error
3945
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3946
-     */
3947
-    private function _extract_related_model_info_from_query_param(
3948
-        $query_param,
3949
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3950
-        $query_param_type,
3951
-        $original_query_param = null
3952
-    ) {
3953
-        if ($original_query_param === null) {
3954
-            $original_query_param = $query_param;
3955
-        }
3956
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3957
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3958
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3959
-        $allow_fields = in_array(
3960
-            $query_param_type,
3961
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3962
-            true
3963
-        );
3964
-        // check to see if we have a field on this model
3965
-        $this_model_fields = $this->field_settings(true);
3966
-        if (array_key_exists($query_param, $this_model_fields)) {
3967
-            if ($allow_fields) {
3968
-                return;
3969
-            }
3970
-            throw new EE_Error(
3971
-                sprintf(
3972
-                    esc_html__(
3973
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3974
-                        "event_espresso"
3975
-                    ),
3976
-                    $query_param,
3977
-                    get_class($this),
3978
-                    $query_param_type,
3979
-                    $original_query_param
3980
-                )
3981
-            );
3982
-        }
3983
-        // check if this is a special logic query param
3984
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3985
-            if ($allow_logic_query_params) {
3986
-                return;
3987
-            }
3988
-            throw new EE_Error(
3989
-                sprintf(
3990
-                    esc_html__(
3991
-                        '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',
3992
-                        'event_espresso'
3993
-                    ),
3994
-                    implode('", "', $this->_logic_query_param_keys),
3995
-                    $query_param,
3996
-                    get_class($this),
3997
-                    '<br />',
3998
-                    "\t"
3999
-                    . ' $passed_in_query_info = <pre>'
4000
-                    . print_r($passed_in_query_info, true)
4001
-                    . '</pre>'
4002
-                    . "\n\t"
4003
-                    . ' $query_param_type = '
4004
-                    . $query_param_type
4005
-                    . "\n\t"
4006
-                    . ' $original_query_param = '
4007
-                    . $original_query_param
4008
-                )
4009
-            );
4010
-        }
4011
-        // check if it's a custom selection
4012
-        if (
4013
-            $this->_custom_selections instanceof CustomSelects
4014
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4015
-        ) {
4016
-            return;
4017
-        }
4018
-        // check if has a model name at the beginning
4019
-        // and
4020
-        // check if it's a field on a related model
4021
-        if (
4022
-            $this->extractJoinModelFromQueryParams(
4023
-                $passed_in_query_info,
4024
-                $query_param,
4025
-                $original_query_param,
4026
-                $query_param_type
4027
-            )
4028
-        ) {
4029
-            return;
4030
-        }
4031
-
4032
-        // ok so $query_param didn't start with a model name
4033
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4034
-        // it's wack, that's what it is
4035
-        throw new EE_Error(
4036
-            sprintf(
4037
-                esc_html__(
4038
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4039
-                    "event_espresso"
4040
-                ),
4041
-                $query_param,
4042
-                get_class($this),
4043
-                $query_param_type,
4044
-                $original_query_param
4045
-            )
4046
-        );
4047
-    }
4048
-
4049
-
4050
-    /**
4051
-     * Extracts any possible join model information from the provided possible_join_string.
4052
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4053
-     * parts that should be added to the query.
4054
-     *
4055
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4056
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4057
-     * @param null|string                 $original_query_param
4058
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4059
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4060
-     * @return bool  returns true if a join was added and false if not.
4061
-     * @throws EE_Error
4062
-     */
4063
-    private function extractJoinModelFromQueryParams(
4064
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4065
-        $possible_join_string,
4066
-        $original_query_param,
4067
-        $query_parameter_type
4068
-    ) {
4069
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4071
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4073
-                if ($possible_join_string === '') {
4074
-                    // nothing left to $query_param
4075
-                    // we should actually end in a field name, not a model like this!
4076
-                    throw new EE_Error(
4077
-                        sprintf(
4078
-                            esc_html__(
4079
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4080
-                                "event_espresso"
4081
-                            ),
4082
-                            $possible_join_string,
4083
-                            $query_parameter_type,
4084
-                            get_class($this),
4085
-                            $valid_related_model_name
4086
-                        )
4087
-                    );
4088
-                }
4089
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4090
-                $related_model_obj->_extract_related_model_info_from_query_param(
4091
-                    $possible_join_string,
4092
-                    $query_info_carrier,
4093
-                    $query_parameter_type,
4094
-                    $original_query_param
4095
-                );
4096
-                return true;
4097
-            }
4098
-            if ($possible_join_string === $valid_related_model_name) {
4099
-                $this->_add_join_to_model(
4100
-                    $valid_related_model_name,
4101
-                    $query_info_carrier,
4102
-                    $original_query_param
4103
-                );
4104
-                return true;
4105
-            }
4106
-        }
4107
-        return false;
4108
-    }
4109
-
4110
-
4111
-    /**
4112
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4113
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
-     * @throws EE_Error
4115
-     */
4116
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4117
-    {
4118
-        if (
4119
-            $this->_custom_selections instanceof CustomSelects
4120
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4121
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4122
-            )
4123
-        ) {
4124
-            $original_selects = $this->_custom_selections->originalSelects();
4125
-            foreach ($original_selects as $alias => $select_configuration) {
4126
-                $this->extractJoinModelFromQueryParams(
4127
-                    $query_info_carrier,
4128
-                    $select_configuration[0],
4129
-                    $select_configuration[0],
4130
-                    'custom_selects'
4131
-                );
4132
-            }
4133
-        }
4134
-    }
4135
-
4136
-
4137
-
4138
-    /**
4139
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4140
-     * and store it on $passed_in_query_info
4141
-     *
4142
-     * @param string                      $model_name
4143
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4144
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4145
-     *                                                          model and $model_name. Eg, if we are querying Event,
4146
-     *                                                          and are adding a join to 'Payment' with the original
4147
-     *                                                          query param key
4148
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4149
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4150
-     *                                                          Payment wants to add default query params so that it
4151
-     *                                                          will know what models to prepend onto its default query
4152
-     *                                                          params or in case it wants to rename tables (in case
4153
-     *                                                          there are multiple joins to the same table)
4154
-     * @return void
4155
-     * @throws EE_Error
4156
-     */
4157
-    private function _add_join_to_model(
4158
-        $model_name,
4159
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4160
-        $original_query_param
4161
-    ) {
4162
-        $relation_obj = $this->related_settings_for($model_name);
4163
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4164
-        // check if the relation is HABTM, because then we're essentially doing two joins
4165
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4166
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4167
-            $join_model_obj = $relation_obj->get_join_model();
4168
-            // replace the model specified with the join model for this relation chain, whi
4169
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4170
-                $model_name,
4171
-                $join_model_obj->get_this_model_name(),
4172
-                $model_relation_chain
4173
-            );
4174
-            $passed_in_query_info->merge(
4175
-                new EE_Model_Query_Info_Carrier(
4176
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4177
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4178
-                )
4179
-            );
4180
-        }
4181
-        // now just join to the other table pointed to by the relation object, and add its data types
4182
-        $passed_in_query_info->merge(
4183
-            new EE_Model_Query_Info_Carrier(
4184
-                array($model_relation_chain => $model_name),
4185
-                $relation_obj->get_join_statement($model_relation_chain)
4186
-            )
4187
-        );
4188
-    }
4189
-
4190
-
4191
-
4192
-    /**
4193
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4194
-     *
4195
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4196
-     * @return string of SQL
4197
-     * @throws EE_Error
4198
-     */
4199
-    private function _construct_where_clause($where_params)
4200
-    {
4201
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202
-        if ($SQL) {
4203
-            return " WHERE " . $SQL;
4204
-        }
4205
-        return '';
4206
-    }
4207
-
4208
-
4209
-
4210
-    /**
4211
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4212
-     * and should be passed HAVING parameters, not WHERE parameters
4213
-     *
4214
-     * @param array $having_params
4215
-     * @return string
4216
-     * @throws EE_Error
4217
-     */
4218
-    private function _construct_having_clause($having_params)
4219
-    {
4220
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221
-        if ($SQL) {
4222
-            return " HAVING " . $SQL;
4223
-        }
4224
-        return '';
4225
-    }
4226
-
4227
-
4228
-    /**
4229
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4230
-     * Event_Meta.meta_value = 'foo'))"
4231
-     *
4232
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4233
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4234
-     * @throws EE_Error
4235
-     * @return string of SQL
4236
-     */
4237
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4238
-    {
4239
-        $where_clauses = array();
4240
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4242
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4243
-                switch ($query_param) {
4244
-                    case 'not':
4245
-                    case 'NOT':
4246
-                        $where_clauses[] = "! ("
4247
-                                           . $this->_construct_condition_clause_recursive(
4248
-                                               $op_and_value_or_sub_condition,
4249
-                                               $glue
4250
-                                           )
4251
-                                           . ")";
4252
-                        break;
4253
-                    case 'and':
4254
-                    case 'AND':
4255
-                        $where_clauses[] = " ("
4256
-                                           . $this->_construct_condition_clause_recursive(
4257
-                                               $op_and_value_or_sub_condition,
4258
-                                               ' AND '
4259
-                                           )
4260
-                                           . ")";
4261
-                        break;
4262
-                    case 'or':
4263
-                    case 'OR':
4264
-                        $where_clauses[] = " ("
4265
-                                           . $this->_construct_condition_clause_recursive(
4266
-                                               $op_and_value_or_sub_condition,
4267
-                                               ' OR '
4268
-                                           )
4269
-                                           . ")";
4270
-                        break;
4271
-                }
4272
-            } else {
4273
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4274
-                // if it's not a normal field, maybe it's a custom selection?
4275
-                if (! $field_obj) {
4276
-                    if ($this->_custom_selections instanceof CustomSelects) {
4277
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278
-                    } else {
4279
-                        throw new EE_Error(sprintf(esc_html__(
4280
-                            "%s is neither a valid model field name, nor a custom selection",
4281
-                            "event_espresso"
4282
-                        ), $query_param));
4283
-                    }
4284
-                }
4285
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4287
-            }
4288
-        }
4289
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4290
-    }
4291
-
4292
-
4293
-
4294
-    /**
4295
-     * Takes the input parameter and extract the table name (alias) and column name
4296
-     *
4297
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4298
-     * @throws EE_Error
4299
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4300
-     */
4301
-    private function _deduce_column_name_from_query_param($query_param)
4302
-    {
4303
-        $field = $this->_deduce_field_from_query_param($query_param);
4304
-        if ($field) {
4305
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4306
-                $field->get_model_name(),
4307
-                $query_param
4308
-            );
4309
-            return $table_alias_prefix . $field->get_qualified_column();
4310
-        }
4311
-        if (
4312
-            $this->_custom_selections instanceof CustomSelects
4313
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4314
-        ) {
4315
-            // maybe it's custom selection item?
4316
-            // if so, just use it as the "column name"
4317
-            return $query_param;
4318
-        }
4319
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4320
-            ? implode(',', $this->_custom_selections->columnAliases())
4321
-            : '';
4322
-        throw new EE_Error(
4323
-            sprintf(
4324
-                esc_html__(
4325
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4326
-                    "event_espresso"
4327
-                ),
4328
-                $query_param,
4329
-                $custom_select_aliases
4330
-            )
4331
-        );
4332
-    }
4333
-
4334
-
4335
-
4336
-    /**
4337
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4338
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4339
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4340
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4341
-     *
4342
-     * @param string $condition_query_param_key
4343
-     * @return string
4344
-     */
4345
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4346
-    {
4347
-        $pos_of_star = strpos($condition_query_param_key, '*');
4348
-        if ($pos_of_star === false) {
4349
-            return $condition_query_param_key;
4350
-        }
4351
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4352
-        return $condition_query_param_sans_star;
4353
-    }
4354
-
4355
-
4356
-
4357
-    /**
4358
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4359
-     *
4360
-     * @param                            mixed      array | string    $op_and_value
4361
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4362
-     * @throws EE_Error
4363
-     * @return string
4364
-     */
4365
-    private function _construct_op_and_value($op_and_value, $field_obj)
4366
-    {
4367
-        if (is_array($op_and_value)) {
4368
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
-            if (! $operator) {
4370
-                $php_array_like_string = array();
4371
-                foreach ($op_and_value as $key => $value) {
4372
-                    $php_array_like_string[] = "$key=>$value";
4373
-                }
4374
-                throw new EE_Error(
4375
-                    sprintf(
4376
-                        esc_html__(
4377
-                            "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))",
4378
-                            "event_espresso"
4379
-                        ),
4380
-                        implode(",", $php_array_like_string)
4381
-                    )
4382
-                );
4383
-            }
4384
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4385
-        } else {
4386
-            $operator = '=';
4387
-            $value = $op_and_value;
4388
-        }
4389
-        // check to see if the value is actually another field
4390
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4392
-        }
4393
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394
-            // in this case, the value should be an array, or at least a comma-separated list
4395
-            // it will need to handle a little differently
4396
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4397
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4398
-            return $operator . SP . $cleaned_value;
4399
-        }
4400
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401
-            // the value should be an array with count of two.
4402
-            if (count($value) !== 2) {
4403
-                throw new EE_Error(
4404
-                    sprintf(
4405
-                        esc_html__(
4406
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4407
-                            'event_espresso'
4408
-                        ),
4409
-                        "BETWEEN"
4410
-                    )
4411
-                );
4412
-            }
4413
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
-            return $operator . SP . $cleaned_value;
4415
-        }
4416
-        if (in_array($operator, $this->valid_null_style_operators())) {
4417
-            if ($value !== null) {
4418
-                throw new EE_Error(
4419
-                    sprintf(
4420
-                        esc_html__(
4421
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4422
-                            "event_espresso"
4423
-                        ),
4424
-                        $value,
4425
-                        $operator
4426
-                    )
4427
-                );
4428
-            }
4429
-            return $operator;
4430
-        }
4431
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4433
-            // remove other junk. So just treat it as a string.
4434
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4435
-        }
4436
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
-        }
4439
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440
-            throw new EE_Error(
4441
-                sprintf(
4442
-                    esc_html__(
4443
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4444
-                        'event_espresso'
4445
-                    ),
4446
-                    $operator,
4447
-                    $operator
4448
-                )
4449
-            );
4450
-        }
4451
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
-            throw new EE_Error(
4453
-                sprintf(
4454
-                    esc_html__(
4455
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4456
-                        'event_espresso'
4457
-                    ),
4458
-                    $operator,
4459
-                    $operator
4460
-                )
4461
-            );
4462
-        }
4463
-        throw new EE_Error(
4464
-            sprintf(
4465
-                esc_html__(
4466
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4467
-                    "event_espresso"
4468
-                ),
4469
-                http_build_query($op_and_value)
4470
-            )
4471
-        );
4472
-    }
4473
-
4474
-
4475
-
4476
-    /**
4477
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4478
-     *
4479
-     * @param array                      $values
4480
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4481
-     *                                              '%s'
4482
-     * @return string
4483
-     * @throws EE_Error
4484
-     */
4485
-    public function _construct_between_value($values, $field_obj)
4486
-    {
4487
-        $cleaned_values = array();
4488
-        foreach ($values as $value) {
4489
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490
-        }
4491
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4492
-    }
4493
-
4494
-
4495
-    /**
4496
-     * Takes an array or a comma-separated list of $values and cleans them
4497
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4498
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
-     *
4502
-     * @param mixed                      $values    array or comma-separated string
4503
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
-     * @throws EE_Error
4506
-     */
4507
-    public function _construct_in_value($values, $field_obj)
4508
-    {
4509
-        $prepped = [];
4510
-        // check if the value is a CSV list
4511
-        if (is_string($values)) {
4512
-            // in which case, turn it into an array
4513
-            $values = explode(',', $values);
4514
-        }
4515
-        // make sure we only have one of each value in the list
4516
-        $values = array_unique($values);
4517
-        foreach ($values as $value) {
4518
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4519
-        }
4520
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4521
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4522
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523
-        if (empty($prepped)) {
4524
-            $all_fields = $this->field_settings();
4525
-            $first_field    = reset($all_fields);
4526
-            $main_table = $this->_get_main_table();
4527
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528
-        }
4529
-        return '(' . implode(',', $prepped) . ')';
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * @param mixed                      $value
4536
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4537
-     * @throws EE_Error
4538
-     * @return false|null|string
4539
-     */
4540
-    private function _wpdb_prepare_using_field($value, $field_obj)
4541
-    {
4542
-        /** @type WPDB $wpdb */
4543
-        global $wpdb;
4544
-        if ($field_obj instanceof EE_Model_Field_Base) {
4545
-            return $wpdb->prepare(
4546
-                $field_obj->get_wpdb_data_type(),
4547
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4548
-            );
4549
-        } //$field_obj should really just be a data type
4550
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551
-            throw new EE_Error(
4552
-                sprintf(
4553
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4554
-                    $field_obj,
4555
-                    implode(",", $this->_valid_wpdb_data_types)
4556
-                )
4557
-            );
4558
-        }
4559
-        return $wpdb->prepare($field_obj, $value);
4560
-    }
4561
-
4562
-
4563
-
4564
-    /**
4565
-     * Takes the input parameter and finds the model field that it indicates.
4566
-     *
4567
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4568
-     * @throws EE_Error
4569
-     * @return EE_Model_Field_Base
4570
-     */
4571
-    protected function _deduce_field_from_query_param($query_param_name)
4572
-    {
4573
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4574
-        // which will help us find the database table and column
4575
-        $query_param_parts = explode(".", $query_param_name);
4576
-        if (empty($query_param_parts)) {
4577
-            throw new EE_Error(sprintf(esc_html__(
4578
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4579
-                'event_espresso'
4580
-            ), $query_param_name));
4581
-        }
4582
-        $number_of_parts = count($query_param_parts);
4583
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4584
-        if ($number_of_parts === 1) {
4585
-            $field_name = $last_query_param_part;
4586
-            $model_obj = $this;
4587
-        } else {// $number_of_parts >= 2
4588
-            // the last part is the column name, and there are only 2parts. therefore...
4589
-            $field_name = $last_query_param_part;
4590
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4591
-        }
4592
-        try {
4593
-            return $model_obj->field_settings_for($field_name);
4594
-        } catch (EE_Error $e) {
4595
-            return null;
4596
-        }
4597
-    }
4598
-
4599
-
4600
-
4601
-    /**
4602
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4603
-     * alias and column which corresponds to it
4604
-     *
4605
-     * @param string $field_name
4606
-     * @throws EE_Error
4607
-     * @return string
4608
-     */
4609
-    public function _get_qualified_column_for_field($field_name)
4610
-    {
4611
-        $all_fields = $this->field_settings();
4612
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4613
-        if ($field) {
4614
-            return $field->get_qualified_column();
4615
-        }
4616
-        throw new EE_Error(
4617
-            sprintf(
4618
-                esc_html__(
4619
-                    "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.",
4620
-                    'event_espresso'
4621
-                ),
4622
-                $field_name,
4623
-                get_class($this)
4624
-            )
4625
-        );
4626
-    }
4627
-
4628
-
4629
-
4630
-    /**
4631
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4632
-     * Example usage:
4633
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4634
-     *      array(),
4635
-     *      ARRAY_A,
4636
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4637
-     *  );
4638
-     * is equivalent to
4639
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4640
-     * and
4641
-     *  EEM_Event::instance()->get_all_wpdb_results(
4642
-     *      array(
4643
-     *          array(
4644
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4645
-     *          ),
4646
-     *          ARRAY_A,
4647
-     *          implode(
4648
-     *              ', ',
4649
-     *              array_merge(
4650
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4651
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4652
-     *              )
4653
-     *          )
4654
-     *      )
4655
-     *  );
4656
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4657
-     *
4658
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4659
-     *                                            and the one whose fields you are selecting for example: when querying
4660
-     *                                            tickets model and selecting fields from the tickets model you would
4661
-     *                                            leave this parameter empty, because no models are needed to join
4662
-     *                                            between the queried model and the selected one. Likewise when
4663
-     *                                            querying the datetime model and selecting fields from the tickets
4664
-     *                                            model, it would also be left empty, because there is a direct
4665
-     *                                            relation from datetimes to tickets, so no model is needed to join
4666
-     *                                            them together. However, when querying from the event model and
4667
-     *                                            selecting fields from the ticket model, you should provide the string
4668
-     *                                            'Datetime', indicating that the event model must first join to the
4669
-     *                                            datetime model in order to find its relation to ticket model.
4670
-     *                                            Also, when querying from the venue model and selecting fields from
4671
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4672
-     *                                            indicating you need to join the venue model to the event model,
4673
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4674
-     *                                            This string is used to deduce the prefix that gets added onto the
4675
-     *                                            models' tables qualified columns
4676
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4677
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4678
-     *                                            qualified column names
4679
-     * @return array|string
4680
-     */
4681
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682
-    {
4683
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4684
-        $qualified_columns = array();
4685
-        foreach ($this->field_settings() as $field_name => $field) {
4686
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4687
-        }
4688
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689
-    }
4690
-
4691
-
4692
-
4693
-    /**
4694
-     * constructs the select use on special limit joins
4695
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4696
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4697
-     * (as that is typically where the limits would be set).
4698
-     *
4699
-     * @param  string       $table_alias The table the select is being built for
4700
-     * @param  mixed|string $limit       The limit for this select
4701
-     * @return string                The final select join element for the query.
4702
-     */
4703
-    public function _construct_limit_join_select($table_alias, $limit)
4704
-    {
4705
-        $SQL = '';
4706
-        foreach ($this->_tables as $table_obj) {
4707
-            if ($table_obj instanceof EE_Primary_Table) {
4708
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4709
-                    ? $table_obj->get_select_join_limit($limit)
4710
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4711
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4712
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4713
-                    ? $table_obj->get_select_join_limit_join($limit)
4714
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4715
-            }
4716
-        }
4717
-        return $SQL;
4718
-    }
4719
-
4720
-
4721
-
4722
-    /**
4723
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4724
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4725
-     *
4726
-     * @return string SQL
4727
-     * @throws EE_Error
4728
-     */
4729
-    public function _construct_internal_join()
4730
-    {
4731
-        $SQL = $this->_get_main_table()->get_table_sql();
4732
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4733
-        return $SQL;
4734
-    }
4735
-
4736
-
4737
-
4738
-    /**
4739
-     * Constructs the SQL for joining all the tables on this model.
4740
-     * Normally $alias should be the primary table's alias, but in cases where
4741
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4742
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4743
-     * alias, this will construct SQL like:
4744
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4745
-     * With $alias being a secondary table's alias, this will construct SQL like:
4746
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
-     *
4748
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4749
-     * @return string
4750
-     */
4751
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4752
-    {
4753
-        $SQL = '';
4754
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4755
-        foreach ($this->_tables as $table_obj) {
4756
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4757
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4758
-                    // so we're joining to this table, meaning the table is already in
4759
-                    // the FROM statement, BUT the primary table isn't. So we want
4760
-                    // to add the inverse join sql
4761
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4762
-                } else {
4763
-                    // just add a regular JOIN to this table from the primary table
4764
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4765
-                }
4766
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4767
-        }
4768
-        return $SQL;
4769
-    }
4770
-
4771
-
4772
-
4773
-    /**
4774
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4775
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4776
-     * their data type (eg, '%s', '%d', etc)
4777
-     *
4778
-     * @return array
4779
-     */
4780
-    public function _get_data_types()
4781
-    {
4782
-        $data_types = array();
4783
-        foreach ($this->field_settings() as $field_obj) {
4784
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785
-            /** @var $field_obj EE_Model_Field_Base */
4786
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4787
-        }
4788
-        return $data_types;
4789
-    }
4790
-
4791
-
4792
-
4793
-    /**
4794
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4795
-     *
4796
-     * @param string $model_name
4797
-     * @throws EE_Error
4798
-     * @return EEM_Base
4799
-     */
4800
-    public function get_related_model_obj($model_name)
4801
-    {
4802
-        $model_classname = "EEM_" . $model_name;
4803
-        if (! class_exists($model_classname)) {
4804
-            throw new EE_Error(sprintf(esc_html__(
4805
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806
-                'event_espresso'
4807
-            ), $model_name, $model_classname));
4808
-        }
4809
-        return call_user_func($model_classname . "::instance");
4810
-    }
4811
-
4812
-
4813
-
4814
-    /**
4815
-     * Returns the array of EE_ModelRelations for this model.
4816
-     *
4817
-     * @return EE_Model_Relation_Base[]
4818
-     */
4819
-    public function relation_settings()
4820
-    {
4821
-        return $this->_model_relations;
4822
-    }
4823
-
4824
-
4825
-
4826
-    /**
4827
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4828
-     * because without THOSE models, this model probably doesn't have much purpose.
4829
-     * (Eg, without an event, datetimes have little purpose.)
4830
-     *
4831
-     * @return EE_Belongs_To_Relation[]
4832
-     */
4833
-    public function belongs_to_relations()
4834
-    {
4835
-        $belongs_to_relations = array();
4836
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4839
-            }
4840
-        }
4841
-        return $belongs_to_relations;
4842
-    }
4843
-
4844
-
4845
-
4846
-    /**
4847
-     * Returns the specified EE_Model_Relation, or throws an exception
4848
-     *
4849
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4850
-     * @throws EE_Error
4851
-     * @return EE_Model_Relation_Base
4852
-     */
4853
-    public function related_settings_for($relation_name)
4854
-    {
4855
-        $relatedModels = $this->relation_settings();
4856
-        if (! array_key_exists($relation_name, $relatedModels)) {
4857
-            throw new EE_Error(
4858
-                sprintf(
4859
-                    esc_html__(
4860
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4861
-                        'event_espresso'
4862
-                    ),
4863
-                    $relation_name,
4864
-                    $this->_get_class_name(),
4865
-                    implode(', ', array_keys($relatedModels))
4866
-                )
4867
-            );
4868
-        }
4869
-        return $relatedModels[ $relation_name ];
4870
-    }
4871
-
4872
-
4873
-
4874
-    /**
4875
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4876
-     * fields
4877
-     *
4878
-     * @param string $fieldName
4879
-     * @param boolean $include_db_only_fields
4880
-     * @throws EE_Error
4881
-     * @return EE_Model_Field_Base
4882
-     */
4883
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4884
-    {
4885
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4886
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4887
-            throw new EE_Error(sprintf(
4888
-                esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889
-                $fieldName,
4890
-                get_class($this)
4891
-            ));
4892
-        }
4893
-        return $fieldSettings[ $fieldName ];
4894
-    }
4895
-
4896
-
4897
-
4898
-    /**
4899
-     * Checks if this field exists on this model
4900
-     *
4901
-     * @param string $fieldName a key in the model's _field_settings array
4902
-     * @return boolean
4903
-     */
4904
-    public function has_field($fieldName)
4905
-    {
4906
-        $fieldSettings = $this->field_settings(true);
4907
-        if (isset($fieldSettings[ $fieldName ])) {
4908
-            return true;
4909
-        }
4910
-        return false;
4911
-    }
4912
-
4913
-
4914
-
4915
-    /**
4916
-     * Returns whether or not this model has a relation to the specified model
4917
-     *
4918
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4919
-     * @return boolean
4920
-     */
4921
-    public function has_relation($relation_name)
4922
-    {
4923
-        $relations = $this->relation_settings();
4924
-        if (isset($relations[ $relation_name ])) {
4925
-            return true;
4926
-        }
4927
-        return false;
4928
-    }
4929
-
4930
-
4931
-
4932
-    /**
4933
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
-     * Eg, on EE_Answer that would be ANS_ID field object
4935
-     *
4936
-     * @param $field_obj
4937
-     * @return boolean
4938
-     */
4939
-    public function is_primary_key_field($field_obj)
4940
-    {
4941
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4942
-    }
4943
-
4944
-
4945
-
4946
-    /**
4947
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4948
-     * Eg, on EE_Answer that would be ANS_ID field object
4949
-     *
4950
-     * @return EE_Model_Field_Base
4951
-     * @throws EE_Error
4952
-     */
4953
-    public function get_primary_key_field()
4954
-    {
4955
-        if ($this->_primary_key_field === null) {
4956
-            foreach ($this->field_settings(true) as $field_obj) {
4957
-                if ($this->is_primary_key_field($field_obj)) {
4958
-                    $this->_primary_key_field = $field_obj;
4959
-                    break;
4960
-                }
4961
-            }
4962
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963
-                throw new EE_Error(sprintf(
4964
-                    esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965
-                    get_class($this)
4966
-                ));
4967
-            }
4968
-        }
4969
-        return $this->_primary_key_field;
4970
-    }
4971
-
4972
-
4973
-
4974
-    /**
4975
-     * Returns whether or not not there is a primary key on this model.
4976
-     * Internally does some caching.
4977
-     *
4978
-     * @return boolean
4979
-     */
4980
-    public function has_primary_key_field()
4981
-    {
4982
-        if ($this->_has_primary_key_field === null) {
4983
-            try {
4984
-                $this->get_primary_key_field();
4985
-                $this->_has_primary_key_field = true;
4986
-            } catch (EE_Error $e) {
4987
-                $this->_has_primary_key_field = false;
4988
-            }
4989
-        }
4990
-        return $this->_has_primary_key_field;
4991
-    }
4992
-
4993
-
4994
-
4995
-    /**
4996
-     * Finds the first field of type $field_class_name.
4997
-     *
4998
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4999
-     *                                 EE_Foreign_Key_Field, etc
5000
-     * @return EE_Model_Field_Base or null if none is found
5001
-     */
5002
-    public function get_a_field_of_type($field_class_name)
5003
-    {
5004
-        foreach ($this->field_settings() as $field) {
5005
-            if ($field instanceof $field_class_name) {
5006
-                return $field;
5007
-            }
5008
-        }
5009
-        return null;
5010
-    }
5011
-
5012
-
5013
-
5014
-    /**
5015
-     * Gets a foreign key field pointing to model.
5016
-     *
5017
-     * @param string $model_name eg Event, Registration, not EEM_Event
5018
-     * @return EE_Foreign_Key_Field_Base
5019
-     * @throws EE_Error
5020
-     */
5021
-    public function get_foreign_key_to($model_name)
5022
-    {
5023
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5024
-            foreach ($this->field_settings() as $field) {
5025
-                if (
5026
-                    $field instanceof EE_Foreign_Key_Field_Base
5027
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5028
-                ) {
5029
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5030
-                    break;
5031
-                }
5032
-            }
5033
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5034
-                throw new EE_Error(sprintf(esc_html__(
5035
-                    "There is no foreign key field pointing to model %s on model %s",
5036
-                    'event_espresso'
5037
-                ), $model_name, get_class($this)));
5038
-            }
5039
-        }
5040
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5041
-    }
5042
-
5043
-
5044
-
5045
-    /**
5046
-     * Gets the table name (including $wpdb->prefix) for the table alias
5047
-     *
5048
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5049
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5050
-     *                            Either one works
5051
-     * @return string
5052
-     */
5053
-    public function get_table_for_alias($table_alias)
5054
-    {
5055
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5057
-    }
5058
-
5059
-
5060
-
5061
-    /**
5062
-     * Returns a flat array of all field son this model, instead of organizing them
5063
-     * by table_alias as they are in the constructor.
5064
-     *
5065
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5066
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5067
-     */
5068
-    public function field_settings($include_db_only_fields = false)
5069
-    {
5070
-        if ($include_db_only_fields) {
5071
-            if ($this->_cached_fields === null) {
5072
-                $this->_cached_fields = array();
5073
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5074
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5076
-                    }
5077
-                }
5078
-            }
5079
-            return $this->_cached_fields;
5080
-        }
5081
-        if ($this->_cached_fields_non_db_only === null) {
5082
-            $this->_cached_fields_non_db_only = array();
5083
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5084
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085
-                    /** @var $field_obj EE_Model_Field_Base */
5086
-                    if (! $field_obj->is_db_only_field()) {
5087
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
-                    }
5089
-                }
5090
-            }
5091
-        }
5092
-        return $this->_cached_fields_non_db_only;
5093
-    }
5094
-
5095
-
5096
-
5097
-    /**
5098
-     *        cycle though array of attendees and create objects out of each item
5099
-     *
5100
-     * @access        private
5101
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5102
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5103
-     *                           numerically indexed)
5104
-     * @throws EE_Error
5105
-     */
5106
-    protected function _create_objects($rows = array())
5107
-    {
5108
-        $array_of_objects = array();
5109
-        if (empty($rows)) {
5110
-            return array();
5111
-        }
5112
-        $count_if_model_has_no_primary_key = 0;
5113
-        $has_primary_key = $this->has_primary_key_field();
5114
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5115
-        foreach ((array) $rows as $row) {
5116
-            if (empty($row)) {
5117
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5118
-                return array();
5119
-            }
5120
-            // check if we've already set this object in the results array,
5121
-            // in which case there's no need to process it further (again)
5122
-            if ($has_primary_key) {
5123
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5124
-                    $row,
5125
-                    $primary_key_field->get_qualified_column(),
5126
-                    $primary_key_field->get_table_column()
5127
-                );
5128
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5129
-                    continue;
5130
-                }
5131
-            }
5132
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5133
-            if (! $classInstance) {
5134
-                throw new EE_Error(
5135
-                    sprintf(
5136
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5137
-                        $this->get_this_model_name(),
5138
-                        http_build_query($row)
5139
-                    )
5140
-                );
5141
-            }
5142
-            // set the timezone on the instantiated objects
5143
-            $classInstance->set_timezone($this->_timezone);
5144
-            // make sure if there is any timezone setting present that we set the timezone for the object
5145
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
-            $array_of_objects[ $key ] = $classInstance;
5147
-            // also, for all the relations of type BelongsTo, see if we can cache
5148
-            // those related models
5149
-            // (we could do this for other relations too, but if there are conditions
5150
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5151
-            // so it requires a little more thought than just caching them immediately...)
5152
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5153
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5154
-                    // check if this model's INFO is present. If so, cache it on the model
5155
-                    $other_model = $relation_obj->get_other_model();
5156
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5157
-                    // if we managed to make a model object from the results, cache it on the main model object
5158
-                    if ($other_model_obj_maybe) {
5159
-                        // set timezone on these other model objects if they are present
5160
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5161
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5162
-                    }
5163
-                }
5164
-            }
5165
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5166
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5167
-            // the field in the CustomSelects object
5168
-            if ($this->_custom_selections instanceof CustomSelects) {
5169
-                $classInstance->setCustomSelectsValues(
5170
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5171
-                );
5172
-            }
5173
-        }
5174
-        return $array_of_objects;
5175
-    }
5176
-
5177
-
5178
-    /**
5179
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5180
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5181
-     *
5182
-     * @param array $db_results_row
5183
-     * @return array
5184
-     */
5185
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5186
-    {
5187
-        $results = array();
5188
-        if ($this->_custom_selections instanceof CustomSelects) {
5189
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
-                if (isset($db_results_row[ $alias ])) {
5191
-                    $results[ $alias ] = $this->convertValueToDataType(
5192
-                        $db_results_row[ $alias ],
5193
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5194
-                    );
5195
-                }
5196
-            }
5197
-        }
5198
-        return $results;
5199
-    }
5200
-
5201
-
5202
-    /**
5203
-     * This will set the value for the given alias
5204
-     * @param string $value
5205
-     * @param string $datatype (one of %d, %s, %f)
5206
-     * @return int|string|float (int for %d, string for %s, float for %f)
5207
-     */
5208
-    protected function convertValueToDataType($value, $datatype)
5209
-    {
5210
-        switch ($datatype) {
5211
-            case '%f':
5212
-                return (float) $value;
5213
-            case '%d':
5214
-                return (int) $value;
5215
-            default:
5216
-                return (string) $value;
5217
-        }
5218
-    }
5219
-
5220
-
5221
-    /**
5222
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5223
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5224
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5225
-     * object (as set in the model_field!).
5226
-     *
5227
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5228
-     */
5229
-    public function create_default_object()
5230
-    {
5231
-        $this_model_fields_and_values = array();
5232
-        // setup the row using default values;
5233
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5234
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5235
-        }
5236
-        $className = $this->_get_class_name();
5237
-        $classInstance = EE_Registry::instance()
5238
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5239
-        return $classInstance;
5240
-    }
5241
-
5242
-
5243
-
5244
-    /**
5245
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5246
-     *                             or an stdClass where each property is the name of a column,
5247
-     * @return EE_Base_Class
5248
-     * @throws EE_Error
5249
-     */
5250
-    public function instantiate_class_from_array_or_object($cols_n_values)
5251
-    {
5252
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5253
-            $cols_n_values = get_object_vars($cols_n_values);
5254
-        }
5255
-        $primary_key = null;
5256
-        // make sure the array only has keys that are fields/columns on this model
5257
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
-        }
5261
-        $className = $this->_get_class_name();
5262
-        // check we actually found results that we can use to build our model object
5263
-        // if not, return null
5264
-        if ($this->has_primary_key_field()) {
5265
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5266
-                return null;
5267
-            }
5268
-        } elseif ($this->unique_indexes()) {
5269
-            $first_column = reset($this_model_fields_n_values);
5270
-            if (empty($first_column)) {
5271
-                return null;
5272
-            }
5273
-        }
5274
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275
-        if ($primary_key) {
5276
-            $classInstance = $this->get_from_entity_map($primary_key);
5277
-            if (! $classInstance) {
5278
-                $classInstance = EE_Registry::instance()
5279
-                                            ->load_class(
5280
-                                                $className,
5281
-                                                array($this_model_fields_n_values, $this->_timezone),
5282
-                                                true,
5283
-                                                false
5284
-                                            );
5285
-                // add this new object to the entity map
5286
-                $classInstance = $this->add_to_entity_map($classInstance);
5287
-            }
5288
-        } else {
5289
-            $classInstance = EE_Registry::instance()
5290
-                                        ->load_class(
5291
-                                            $className,
5292
-                                            array($this_model_fields_n_values, $this->_timezone),
5293
-                                            true,
5294
-                                            false
5295
-                                        );
5296
-        }
5297
-        return $classInstance;
5298
-    }
5299
-
5300
-
5301
-
5302
-    /**
5303
-     * Gets the model object from the  entity map if it exists
5304
-     *
5305
-     * @param int|string $id the ID of the model object
5306
-     * @return EE_Base_Class
5307
-     */
5308
-    public function get_from_entity_map($id)
5309
-    {
5310
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
-    }
5313
-
5314
-
5315
-
5316
-    /**
5317
-     * add_to_entity_map
5318
-     * Adds the object to the model's entity mappings
5319
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5320
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5321
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5322
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5323
-     *        then this method should be called immediately after the update query
5324
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5325
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5326
-     *
5327
-     * @param    EE_Base_Class $object
5328
-     * @throws EE_Error
5329
-     * @return \EE_Base_Class
5330
-     */
5331
-    public function add_to_entity_map(EE_Base_Class $object)
5332
-    {
5333
-        $className = $this->_get_class_name();
5334
-        if (! $object instanceof $className) {
5335
-            throw new EE_Error(sprintf(
5336
-                esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337
-                is_object($object) ? get_class($object) : $object,
5338
-                $className
5339
-            ));
5340
-        }
5341
-        /** @var $object EE_Base_Class */
5342
-        if (! $object->ID()) {
5343
-            throw new EE_Error(sprintf(esc_html__(
5344
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5345
-                "event_espresso"
5346
-            ), get_class($this)));
5347
-        }
5348
-        // double check it's not already there
5349
-        $classInstance = $this->get_from_entity_map($object->ID());
5350
-        if ($classInstance) {
5351
-            return $classInstance;
5352
-        }
5353
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5354
-        return $object;
5355
-    }
5356
-
5357
-
5358
-
5359
-    /**
5360
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5361
-     * if no identifier is provided, then the entire entity map is emptied
5362
-     *
5363
-     * @param int|string $id the ID of the model object
5364
-     * @return boolean
5365
-     */
5366
-    public function clear_entity_map($id = null)
5367
-    {
5368
-        if (empty($id)) {
5369
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5370
-            return true;
5371
-        }
5372
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
-            return true;
5375
-        }
5376
-        return false;
5377
-    }
5378
-
5379
-
5380
-
5381
-    /**
5382
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5383
-     * Given an array where keys are column (or column alias) names and values,
5384
-     * returns an array of their corresponding field names and database values
5385
-     *
5386
-     * @param array $cols_n_values
5387
-     * @return array
5388
-     */
5389
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
-    {
5391
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5392
-    }
5393
-
5394
-
5395
-
5396
-    /**
5397
-     * _deduce_fields_n_values_from_cols_n_values
5398
-     * Given an array where keys are column (or column alias) names and values,
5399
-     * returns an array of their corresponding field names and database values
5400
-     *
5401
-     * @param string $cols_n_values
5402
-     * @return array
5403
-     */
5404
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5405
-    {
5406
-        $this_model_fields_n_values = array();
5407
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5408
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5409
-                $cols_n_values,
5410
-                $table_obj->get_fully_qualified_pk_column(),
5411
-                $table_obj->get_pk_column()
5412
-            );
5413
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5414
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
-                    if (! $field_obj->is_db_only_field()) {
5417
-                        // prepare field as if its coming from db
5418
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5420
-                    }
5421
-                }
5422
-            } else {
5423
-                // the table's rows existed. Use their values
5424
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
-                    if (! $field_obj->is_db_only_field()) {
5426
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
-                            $cols_n_values,
5428
-                            $field_obj->get_qualified_column(),
5429
-                            $field_obj->get_table_column()
5430
-                        );
5431
-                    }
5432
-                }
5433
-            }
5434
-        }
5435
-        return $this_model_fields_n_values;
5436
-    }
5437
-
5438
-
5439
-    /**
5440
-     * @param $cols_n_values
5441
-     * @param $qualified_column
5442
-     * @param $regular_column
5443
-     * @return null
5444
-     * @throws EE_Error
5445
-     * @throws ReflectionException
5446
-     */
5447
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5448
-    {
5449
-        $value = null;
5450
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451
-        // does the field on the model relate to this column retrieved from the db?
5452
-        // or is it a db-only field? (not relating to the model)
5453
-        if (isset($cols_n_values[ $qualified_column ])) {
5454
-            $value = $cols_n_values[ $qualified_column ];
5455
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5456
-            $value = $cols_n_values[ $regular_column ];
5457
-        } elseif (! empty($this->foreign_key_aliases)) {
5458
-            // no PK?  ok check if there is a foreign key alias set for this table
5459
-            // then check if that alias exists in the incoming data
5460
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
-                    $value = $cols_n_values[ $FK_alias ];
5464
-                    list($pk_class) = explode('.', $PK_column);
5465
-                    $pk_model_name = "EEM_{$pk_class}";
5466
-                    /** @var EEM_Base $pk_model */
5467
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5468
-                    if ($pk_model instanceof EEM_Base) {
5469
-                        // make sure object is pulled from db and added to entity map
5470
-                        $pk_model->get_one_by_ID($value);
5471
-                    }
5472
-                    break;
5473
-                }
5474
-            }
5475
-        }
5476
-        return $value;
5477
-    }
5478
-
5479
-
5480
-
5481
-    /**
5482
-     * refresh_entity_map_from_db
5483
-     * Makes sure the model object in the entity map at $id assumes the values
5484
-     * of the database (opposite of EE_base_Class::save())
5485
-     *
5486
-     * @param int|string $id
5487
-     * @return EE_Base_Class
5488
-     * @throws EE_Error
5489
-     */
5490
-    public function refresh_entity_map_from_db($id)
5491
-    {
5492
-        $obj_in_map = $this->get_from_entity_map($id);
5493
-        if ($obj_in_map) {
5494
-            $wpdb_results = $this->_get_all_wpdb_results(
5495
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5496
-            );
5497
-            if ($wpdb_results && is_array($wpdb_results)) {
5498
-                $one_row = reset($wpdb_results);
5499
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5500
-                    $obj_in_map->set_from_db($field_name, $db_value);
5501
-                }
5502
-                // clear the cache of related model objects
5503
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5504
-                    $obj_in_map->clear_cache($relation_name, null, true);
5505
-                }
5506
-            }
5507
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5508
-            return $obj_in_map;
5509
-        }
5510
-        return $this->get_one_by_ID($id);
5511
-    }
5512
-
5513
-
5514
-
5515
-    /**
5516
-     * refresh_entity_map_with
5517
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5518
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5519
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5520
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5521
-     *
5522
-     * @param int|string    $id
5523
-     * @param EE_Base_Class $replacing_model_obj
5524
-     * @return \EE_Base_Class
5525
-     * @throws EE_Error
5526
-     */
5527
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5528
-    {
5529
-        $obj_in_map = $this->get_from_entity_map($id);
5530
-        if ($obj_in_map) {
5531
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5532
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5533
-                    $obj_in_map->set($field_name, $value);
5534
-                }
5535
-                // make the model object in the entity map's cache match the $replacing_model_obj
5536
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5537
-                    $obj_in_map->clear_cache($relation_name, null, true);
5538
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5539
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5540
-                    }
5541
-                }
5542
-            }
5543
-            return $obj_in_map;
5544
-        }
5545
-        $this->add_to_entity_map($replacing_model_obj);
5546
-        return $replacing_model_obj;
5547
-    }
5548
-
5549
-
5550
-
5551
-    /**
5552
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5553
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5554
-     * require_once($this->_getClassName().".class.php");
5555
-     *
5556
-     * @return string
5557
-     */
5558
-    private function _get_class_name()
5559
-    {
5560
-        return "EE_" . $this->get_this_model_name();
5561
-    }
5562
-
5563
-
5564
-
5565
-    /**
5566
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5567
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5568
-     * it would be 'Events'.
5569
-     *
5570
-     * @param int $quantity
5571
-     * @return string
5572
-     */
5573
-    public function item_name($quantity = 1)
5574
-    {
5575
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5576
-    }
5577
-
5578
-
5579
-
5580
-    /**
5581
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5582
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5583
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5584
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5585
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5586
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5587
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5588
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5589
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5590
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5591
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5592
-     *        return $previousReturnValue.$returnString;
5593
-     * }
5594
-     * require('EEM_Answer.model.php');
5595
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5596
-     * // will output "you called my_callback! and passed args:monkeys,100"
5597
-     *
5598
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5599
-     * @param array  $args       array of original arguments passed to the function
5600
-     * @throws EE_Error
5601
-     * @return mixed whatever the plugin which calls add_filter decides
5602
-     */
5603
-    public function __call($methodName, $args)
5604
-    {
5605
-        $className = get_class($this);
5606
-        $tagName = "FHEE__{$className}__{$methodName}";
5607
-        if (! has_filter($tagName)) {
5608
-            throw new EE_Error(
5609
-                sprintf(
5610
-                    esc_html__(
5611
-                        '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 );',
5612
-                        'event_espresso'
5613
-                    ),
5614
-                    $methodName,
5615
-                    $className,
5616
-                    $tagName,
5617
-                    '<br />'
5618
-                )
5619
-            );
5620
-        }
5621
-        return apply_filters($tagName, null, $this, $args);
5622
-    }
5623
-
5624
-
5625
-
5626
-    /**
5627
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5628
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5629
-     *
5630
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5631
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5632
-     *                                                       the object's class name
5633
-     *                                                       or object's ID
5634
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5635
-     *                                                       exists in the database. If it does not, we add it
5636
-     * @throws EE_Error
5637
-     * @return EE_Base_Class
5638
-     */
5639
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5640
-    {
5641
-        $className = $this->_get_class_name();
5642
-        if ($base_class_obj_or_id instanceof $className) {
5643
-            $model_object = $base_class_obj_or_id;
5644
-        } else {
5645
-            $primary_key_field = $this->get_primary_key_field();
5646
-            if (
5647
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5648
-                && (
5649
-                    is_int($base_class_obj_or_id)
5650
-                    || is_string($base_class_obj_or_id)
5651
-                )
5652
-            ) {
5653
-                // assume it's an ID.
5654
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5655
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5656
-            } elseif (
5657
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5658
-                && is_string($base_class_obj_or_id)
5659
-            ) {
5660
-                // assume its a string representation of the object
5661
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5662
-            } else {
5663
-                throw new EE_Error(
5664
-                    sprintf(
5665
-                        esc_html__(
5666
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5667
-                            'event_espresso'
5668
-                        ),
5669
-                        $base_class_obj_or_id,
5670
-                        $this->_get_class_name(),
5671
-                        print_r($base_class_obj_or_id, true)
5672
-                    )
5673
-                );
5674
-            }
5675
-        }
5676
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5677
-            $model_object->save();
5678
-        }
5679
-        return $model_object;
5680
-    }
5681
-
5682
-
5683
-
5684
-    /**
5685
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5686
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5687
-     * returns it ID.
5688
-     *
5689
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5690
-     * @return int|string depending on the type of this model object's ID
5691
-     * @throws EE_Error
5692
-     */
5693
-    public function ensure_is_ID($base_class_obj_or_id)
5694
-    {
5695
-        $className = $this->_get_class_name();
5696
-        if ($base_class_obj_or_id instanceof $className) {
5697
-            /** @var $base_class_obj_or_id EE_Base_Class */
5698
-            $id = $base_class_obj_or_id->ID();
5699
-        } elseif (is_int($base_class_obj_or_id)) {
5700
-            // assume it's an ID
5701
-            $id = $base_class_obj_or_id;
5702
-        } elseif (is_string($base_class_obj_or_id)) {
5703
-            // assume its a string representation of the object
5704
-            $id = $base_class_obj_or_id;
5705
-        } else {
5706
-            throw new EE_Error(sprintf(
5707
-                esc_html__(
5708
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5709
-                    'event_espresso'
5710
-                ),
5711
-                $base_class_obj_or_id,
5712
-                $this->_get_class_name(),
5713
-                print_r($base_class_obj_or_id, true)
5714
-            ));
5715
-        }
5716
-        return $id;
5717
-    }
5718
-
5719
-
5720
-
5721
-    /**
5722
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5723
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5724
-     * been sanitized and converted into the appropriate domain.
5725
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5726
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5727
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5728
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5729
-     * $EVT = EEM_Event::instance(); $old_setting =
5730
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5731
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5732
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5733
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5734
-     *
5735
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5736
-     * @return void
5737
-     */
5738
-    public function assume_values_already_prepared_by_model_object(
5739
-        $values_already_prepared = self::not_prepared_by_model_object
5740
-    ) {
5741
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5742
-    }
5743
-
5744
-
5745
-
5746
-    /**
5747
-     * Read comments for assume_values_already_prepared_by_model_object()
5748
-     *
5749
-     * @return int
5750
-     */
5751
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5752
-    {
5753
-        return $this->_values_already_prepared_by_model_object;
5754
-    }
5755
-
5756
-
5757
-
5758
-    /**
5759
-     * Gets all the indexes on this model
5760
-     *
5761
-     * @return EE_Index[]
5762
-     */
5763
-    public function indexes()
5764
-    {
5765
-        return $this->_indexes;
5766
-    }
5767
-
5768
-
5769
-
5770
-    /**
5771
-     * Gets all the Unique Indexes on this model
5772
-     *
5773
-     * @return EE_Unique_Index[]
5774
-     */
5775
-    public function unique_indexes()
5776
-    {
5777
-        $unique_indexes = array();
5778
-        foreach ($this->_indexes as $name => $index) {
5779
-            if ($index instanceof EE_Unique_Index) {
5780
-                $unique_indexes [ $name ] = $index;
5781
-            }
5782
-        }
5783
-        return $unique_indexes;
5784
-    }
5785
-
5786
-
5787
-
5788
-    /**
5789
-     * Gets all the fields which, when combined, make the primary key.
5790
-     * This is usually just an array with 1 element (the primary key), but in cases
5791
-     * where there is no primary key, it's a combination of fields as defined
5792
-     * on a primary index
5793
-     *
5794
-     * @return EE_Model_Field_Base[] indexed by the field's name
5795
-     * @throws EE_Error
5796
-     */
5797
-    public function get_combined_primary_key_fields()
5798
-    {
5799
-        foreach ($this->indexes() as $index) {
5800
-            if ($index instanceof EE_Primary_Key_Index) {
5801
-                return $index->fields();
5802
-            }
5803
-        }
5804
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5805
-    }
5806
-
5807
-
5808
-
5809
-    /**
5810
-     * Used to build a primary key string (when the model has no primary key),
5811
-     * which can be used a unique string to identify this model object.
5812
-     *
5813
-     * @param array $fields_n_values keys are field names, values are their values.
5814
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5815
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5816
-     *                               before passing it to this function (that will convert it from columns-n-values
5817
-     *                               to field-names-n-values).
5818
-     * @return string
5819
-     * @throws EE_Error
5820
-     */
5821
-    public function get_index_primary_key_string($fields_n_values)
5822
-    {
5823
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5824
-            $fields_n_values,
5825
-            $this->get_combined_primary_key_fields()
5826
-        );
5827
-        return http_build_query($cols_n_values_for_primary_key_index);
5828
-    }
5829
-
5830
-
5831
-
5832
-    /**
5833
-     * Gets the field values from the primary key string
5834
-     *
5835
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5836
-     * @param string $index_primary_key_string
5837
-     * @return null|array
5838
-     * @throws EE_Error
5839
-     */
5840
-    public function parse_index_primary_key_string($index_primary_key_string)
5841
-    {
5842
-        $key_fields = $this->get_combined_primary_key_fields();
5843
-        // check all of them are in the $id
5844
-        $key_vals_in_combined_pk = array();
5845
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5846
-        foreach ($key_fields as $key_field_name => $field_obj) {
5847
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5848
-                return null;
5849
-            }
5850
-        }
5851
-        return $key_vals_in_combined_pk;
5852
-    }
5853
-
5854
-
5855
-
5856
-    /**
5857
-     * verifies that an array of key-value pairs for model fields has a key
5858
-     * for each field comprising the primary key index
5859
-     *
5860
-     * @param array $key_vals
5861
-     * @return boolean
5862
-     * @throws EE_Error
5863
-     */
5864
-    public function has_all_combined_primary_key_fields($key_vals)
5865
-    {
5866
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5867
-        foreach ($keys_it_should_have as $key) {
5868
-            if (! isset($key_vals[ $key ])) {
5869
-                return false;
5870
-            }
5871
-        }
5872
-        return true;
5873
-    }
5874
-
5875
-
5876
-
5877
-    /**
5878
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5879
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5880
-     *
5881
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5882
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5883
-     * @throws EE_Error
5884
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5885
-     *                                                              indexed)
5886
-     */
5887
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5888
-    {
5889
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5890
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5891
-        } elseif (is_array($model_object_or_attributes_array)) {
5892
-            $attributes_array = $model_object_or_attributes_array;
5893
-        } else {
5894
-            throw new EE_Error(sprintf(esc_html__(
5895
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5896
-                "event_espresso"
5897
-            ), $model_object_or_attributes_array));
5898
-        }
5899
-        // even copies obviously won't have the same ID, so remove the primary key
5900
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5901
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5902
-            unset($attributes_array[ $this->primary_key_name() ]);
5903
-        }
5904
-        if (isset($query_params[0])) {
5905
-            $query_params[0] = array_merge($attributes_array, $query_params);
5906
-        } else {
5907
-            $query_params[0] = $attributes_array;
5908
-        }
5909
-        return $this->get_all($query_params);
5910
-    }
5911
-
5912
-
5913
-
5914
-    /**
5915
-     * Gets the first copy we find. See get_all_copies for more details
5916
-     *
5917
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5918
-     * @param array $query_params
5919
-     * @return EE_Base_Class
5920
-     * @throws EE_Error
5921
-     */
5922
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5923
-    {
5924
-        if (! is_array($query_params)) {
5925
-            EE_Error::doing_it_wrong(
5926
-                'EEM_Base::get_one_copy',
5927
-                sprintf(
5928
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5929
-                    gettype($query_params)
5930
-                ),
5931
-                '4.6.0'
5932
-            );
5933
-            $query_params = array();
5934
-        }
5935
-        $query_params['limit'] = 1;
5936
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5937
-        if (is_array($copies)) {
5938
-            return array_shift($copies);
5939
-        }
5940
-        return null;
5941
-    }
5942
-
5943
-
5944
-
5945
-    /**
5946
-     * Updates the item with the specified id. Ignores default query parameters because
5947
-     * we have specified the ID, and its assumed we KNOW what we're doing
5948
-     *
5949
-     * @param array      $fields_n_values keys are field names, values are their new values
5950
-     * @param int|string $id              the value of the primary key to update
5951
-     * @return int number of rows updated
5952
-     * @throws EE_Error
5953
-     */
5954
-    public function update_by_ID($fields_n_values, $id)
5955
-    {
5956
-        $query_params = array(
5957
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5958
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5959
-        );
5960
-        return $this->update($fields_n_values, $query_params);
5961
-    }
5962
-
5963
-
5964
-
5965
-    /**
5966
-     * Changes an operator which was supplied to the models into one usable in SQL
5967
-     *
5968
-     * @param string $operator_supplied
5969
-     * @return string an operator which can be used in SQL
5970
-     * @throws EE_Error
5971
-     */
5972
-    private function _prepare_operator_for_sql($operator_supplied)
5973
-    {
5974
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5975
-            : null;
5976
-        if ($sql_operator) {
5977
-            return $sql_operator;
5978
-        }
5979
-        throw new EE_Error(
5980
-            sprintf(
5981
-                esc_html__(
5982
-                    "The operator '%s' is not in the list of valid operators: %s",
5983
-                    "event_espresso"
5984
-                ),
5985
-                $operator_supplied,
5986
-                implode(",", array_keys($this->_valid_operators))
5987
-            )
5988
-        );
5989
-    }
5990
-
5991
-
5992
-
5993
-    /**
5994
-     * Gets the valid operators
5995
-     * @return array keys are accepted strings, values are the SQL they are converted to
5996
-     */
5997
-    public function valid_operators()
5998
-    {
5999
-        return $this->_valid_operators;
6000
-    }
6001
-
6002
-
6003
-
6004
-    /**
6005
-     * Gets the between-style operators (take 2 arguments).
6006
-     * @return array keys are accepted strings, values are the SQL they are converted to
6007
-     */
6008
-    public function valid_between_style_operators()
6009
-    {
6010
-        return array_intersect(
6011
-            $this->valid_operators(),
6012
-            $this->_between_style_operators
6013
-        );
6014
-    }
6015
-
6016
-    /**
6017
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6018
-     * @return array keys are accepted strings, values are the SQL they are converted to
6019
-     */
6020
-    public function valid_like_style_operators()
6021
-    {
6022
-        return array_intersect(
6023
-            $this->valid_operators(),
6024
-            $this->_like_style_operators
6025
-        );
6026
-    }
6027
-
6028
-    /**
6029
-     * Gets the "in"-style operators
6030
-     * @return array keys are accepted strings, values are the SQL they are converted to
6031
-     */
6032
-    public function valid_in_style_operators()
6033
-    {
6034
-        return array_intersect(
6035
-            $this->valid_operators(),
6036
-            $this->_in_style_operators
6037
-        );
6038
-    }
6039
-
6040
-    /**
6041
-     * Gets the "null"-style operators (accept no arguments)
6042
-     * @return array keys are accepted strings, values are the SQL they are converted to
6043
-     */
6044
-    public function valid_null_style_operators()
6045
-    {
6046
-        return array_intersect(
6047
-            $this->valid_operators(),
6048
-            $this->_null_style_operators
6049
-        );
6050
-    }
6051
-
6052
-    /**
6053
-     * Gets an array where keys are the primary keys and values are their 'names'
6054
-     * (as determined by the model object's name() function, which is often overridden)
6055
-     *
6056
-     * @param array $query_params like get_all's
6057
-     * @return string[]
6058
-     * @throws EE_Error
6059
-     */
6060
-    public function get_all_names($query_params = array())
6061
-    {
6062
-        $objs = $this->get_all($query_params);
6063
-        $names = array();
6064
-        foreach ($objs as $obj) {
6065
-            $names[ $obj->ID() ] = $obj->name();
6066
-        }
6067
-        return $names;
6068
-    }
6069
-
6070
-
6071
-
6072
-    /**
6073
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6074
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6075
-     * this is duplicated effort and reduces efficiency) you would be better to use
6076
-     * array_keys() on $model_objects.
6077
-     *
6078
-     * @param \EE_Base_Class[] $model_objects
6079
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6080
-     *                                               in the returned array
6081
-     * @return array
6082
-     * @throws EE_Error
6083
-     */
6084
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6085
-    {
6086
-        if (! $this->has_primary_key_field()) {
6087
-            if (WP_DEBUG) {
6088
-                EE_Error::add_error(
6089
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6090
-                    __FILE__,
6091
-                    __FUNCTION__,
6092
-                    __LINE__
6093
-                );
6094
-            }
6095
-        }
6096
-        $IDs = array();
6097
-        foreach ($model_objects as $model_object) {
6098
-            $id = $model_object->ID();
6099
-            if (! $id) {
6100
-                if ($filter_out_empty_ids) {
6101
-                    continue;
6102
-                }
6103
-                if (WP_DEBUG) {
6104
-                    EE_Error::add_error(
6105
-                        esc_html__(
6106
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6107
-                            'event_espresso'
6108
-                        ),
6109
-                        __FILE__,
6110
-                        __FUNCTION__,
6111
-                        __LINE__
6112
-                    );
6113
-                }
6114
-            }
6115
-            $IDs[] = $id;
6116
-        }
6117
-        return $IDs;
6118
-    }
6119
-
6120
-
6121
-
6122
-    /**
6123
-     * Returns the string used in capabilities relating to this model. If there
6124
-     * are no capabilities that relate to this model returns false
6125
-     *
6126
-     * @return string|false
6127
-     */
6128
-    public function cap_slug()
6129
-    {
6130
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6131
-    }
6132
-
6133
-
6134
-
6135
-    /**
6136
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6137
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6138
-     * only returns the cap restrictions array in that context (ie, the array
6139
-     * at that key)
6140
-     *
6141
-     * @param string $context
6142
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6143
-     * @throws EE_Error
6144
-     */
6145
-    public function cap_restrictions($context = EEM_Base::caps_read)
6146
-    {
6147
-        EEM_Base::verify_is_valid_cap_context($context);
6148
-        // check if we ought to run the restriction generator first
6149
-        if (
6150
-            isset($this->_cap_restriction_generators[ $context ])
6151
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6152
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6153
-        ) {
6154
-            $this->_cap_restrictions[ $context ] = array_merge(
6155
-                $this->_cap_restrictions[ $context ],
6156
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6157
-            );
6158
-        }
6159
-        // and make sure we've finalized the construction of each restriction
6160
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6161
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6162
-                $where_conditions_obj->_finalize_construct($this);
6163
-            }
6164
-        }
6165
-        return $this->_cap_restrictions[ $context ];
6166
-    }
6167
-
6168
-
6169
-
6170
-    /**
6171
-     * Indicating whether or not this model thinks its a wp core model
6172
-     *
6173
-     * @return boolean
6174
-     */
6175
-    public function is_wp_core_model()
6176
-    {
6177
-        return $this->_wp_core_model;
6178
-    }
6179
-
6180
-
6181
-
6182
-    /**
6183
-     * Gets all the caps that are missing which impose a restriction on
6184
-     * queries made in this context
6185
-     *
6186
-     * @param string $context one of EEM_Base::caps_ constants
6187
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6188
-     * @throws EE_Error
6189
-     */
6190
-    public function caps_missing($context = EEM_Base::caps_read)
6191
-    {
6192
-        $missing_caps = array();
6193
-        $cap_restrictions = $this->cap_restrictions($context);
6194
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6195
-            if (
6196
-                ! EE_Capabilities::instance()
6197
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6198
-            ) {
6199
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6200
-            }
6201
-        }
6202
-        return $missing_caps;
6203
-    }
6204
-
6205
-
6206
-
6207
-    /**
6208
-     * Gets the mapping from capability contexts to action strings used in capability names
6209
-     *
6210
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6211
-     * one of 'read', 'edit', or 'delete'
6212
-     */
6213
-    public function cap_contexts_to_cap_action_map()
6214
-    {
6215
-        return apply_filters(
6216
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6217
-            $this->_cap_contexts_to_cap_action_map,
6218
-            $this
6219
-        );
6220
-    }
6221
-
6222
-
6223
-
6224
-    /**
6225
-     * Gets the action string for the specified capability context
6226
-     *
6227
-     * @param string $context
6228
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6229
-     * @throws EE_Error
6230
-     */
6231
-    public function cap_action_for_context($context)
6232
-    {
6233
-        $mapping = $this->cap_contexts_to_cap_action_map();
6234
-        if (isset($mapping[ $context ])) {
6235
-            return $mapping[ $context ];
6236
-        }
6237
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6238
-            return $action;
6239
-        }
6240
-        throw new EE_Error(
6241
-            sprintf(
6242
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6243
-                $context,
6244
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6245
-            )
6246
-        );
6247
-    }
6248
-
6249
-
6250
-
6251
-    /**
6252
-     * Returns all the capability contexts which are valid when querying models
6253
-     *
6254
-     * @return array
6255
-     */
6256
-    public static function valid_cap_contexts()
6257
-    {
6258
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6259
-            self::caps_read,
6260
-            self::caps_read_admin,
6261
-            self::caps_edit,
6262
-            self::caps_delete,
6263
-        ));
6264
-    }
6265
-
6266
-
6267
-
6268
-    /**
6269
-     * Returns all valid options for 'default_where_conditions'
6270
-     *
6271
-     * @return array
6272
-     */
6273
-    public static function valid_default_where_conditions()
6274
-    {
6275
-        return array(
6276
-            EEM_Base::default_where_conditions_all,
6277
-            EEM_Base::default_where_conditions_this_only,
6278
-            EEM_Base::default_where_conditions_others_only,
6279
-            EEM_Base::default_where_conditions_minimum_all,
6280
-            EEM_Base::default_where_conditions_minimum_others,
6281
-            EEM_Base::default_where_conditions_none
6282
-        );
6283
-    }
6284
-
6285
-    // public static function default_where_conditions_full
6286
-    /**
6287
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6288
-     *
6289
-     * @param string $context
6290
-     * @return bool
6291
-     * @throws EE_Error
6292
-     */
6293
-    public static function verify_is_valid_cap_context($context)
6294
-    {
6295
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6296
-        if (in_array($context, $valid_cap_contexts)) {
6297
-            return true;
6298
-        }
6299
-        throw new EE_Error(
6300
-            sprintf(
6301
-                esc_html__(
6302
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6303
-                    'event_espresso'
6304
-                ),
6305
-                $context,
6306
-                'EEM_Base',
6307
-                implode(',', $valid_cap_contexts)
6308
-            )
6309
-        );
6310
-    }
6311
-
6312
-
6313
-
6314
-    /**
6315
-     * Clears all the models field caches. This is only useful when a sub-class
6316
-     * might have added a field or something and these caches might be invalidated
6317
-     */
6318
-    protected function _invalidate_field_caches()
6319
-    {
6320
-        $this->_cache_foreign_key_to_fields = array();
6321
-        $this->_cached_fields = null;
6322
-        $this->_cached_fields_non_db_only = null;
6323
-    }
6324
-
6325
-
6326
-
6327
-    /**
6328
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6329
-     * (eg "and", "or", "not").
6330
-     *
6331
-     * @return array
6332
-     */
6333
-    public function logic_query_param_keys()
6334
-    {
6335
-        return $this->_logic_query_param_keys;
6336
-    }
6337
-
6338
-
6339
-
6340
-    /**
6341
-     * Determines whether or not the where query param array key is for a logic query param.
6342
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6343
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6344
-     *
6345
-     * @param $query_param_key
6346
-     * @return bool
6347
-     */
6348
-    public function is_logic_query_param_key($query_param_key)
6349
-    {
6350
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6351
-            if (
6352
-                $query_param_key === $logic_query_param_key
6353
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6354
-            ) {
6355
-                return true;
6356
-            }
6357
-        }
6358
-        return false;
6359
-    }
6360
-
6361
-    /**
6362
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6363
-     * @since 4.9.74.p
6364
-     * @return boolean
6365
-     */
6366
-    public function hasPassword()
6367
-    {
6368
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6369
-        if ($this->has_password_field === null) {
6370
-            $password_field = $this->getPasswordField();
6371
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6372
-        }
6373
-        return $this->has_password_field;
6374
-    }
6375
-
6376
-    /**
6377
-     * Returns the password field on this model, if there is one
6378
-     * @since 4.9.74.p
6379
-     * @return EE_Password_Field|null
6380
-     */
6381
-    public function getPasswordField()
6382
-    {
6383
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6384
-        // there's no need to search for it. If we don't know yet, then find out
6385
-        if ($this->has_password_field === null && $this->password_field === null) {
6386
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6387
-        }
6388
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6389
-        return $this->password_field;
6390
-    }
6391
-
6392
-
6393
-    /**
6394
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6395
-     * @since 4.9.74.p
6396
-     * @return EE_Model_Field_Base[]
6397
-     * @throws EE_Error
6398
-     */
6399
-    public function getPasswordProtectedFields()
6400
-    {
6401
-        $password_field = $this->getPasswordField();
6402
-        $fields = array();
6403
-        if ($password_field instanceof EE_Password_Field) {
6404
-            $field_names = $password_field->protectedFields();
6405
-            foreach ($field_names as $field_name) {
6406
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6407
-            }
6408
-        }
6409
-        return $fields;
6410
-    }
6411
-
6412
-
6413
-    /**
6414
-     * Checks if the current user can perform the requested action on this model
6415
-     * @since 4.9.74.p
6416
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6417
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6418
-     * @return bool
6419
-     * @throws EE_Error
6420
-     * @throws InvalidArgumentException
6421
-     * @throws InvalidDataTypeException
6422
-     * @throws InvalidInterfaceException
6423
-     * @throws ReflectionException
6424
-     * @throws UnexpectedEntityException
6425
-     */
6426
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6427
-    {
6428
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6429
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6430
-        }
6431
-        if (!is_array($model_obj_or_fields_n_values)) {
6432
-            throw new UnexpectedEntityException(
6433
-                $model_obj_or_fields_n_values,
6434
-                'EE_Base_Class',
6435
-                sprintf(
6436
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6437
-                    __FUNCTION__
6438
-                )
6439
-            );
6440
-        }
6441
-        return $this->exists(
6442
-            $this->alter_query_params_to_restrict_by_ID(
6443
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6444
-                array(
6445
-                    'default_where_conditions' => 'none',
6446
-                    'caps'                     => $cap_to_check,
6447
-                )
6448
-            )
6449
-        );
6450
-    }
6451
-
6452
-    /**
6453
-     * Returns the query param where conditions key to the password affecting this model.
6454
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6455
-     * @since 4.9.74.p
6456
-     * @return null|string
6457
-     * @throws EE_Error
6458
-     * @throws InvalidArgumentException
6459
-     * @throws InvalidDataTypeException
6460
-     * @throws InvalidInterfaceException
6461
-     * @throws ModelConfigurationException
6462
-     * @throws ReflectionException
6463
-     */
6464
-    public function modelChainAndPassword()
6465
-    {
6466
-        if ($this->model_chain_to_password === null) {
6467
-            throw new ModelConfigurationException(
6468
-                $this,
6469
-                esc_html_x(
6470
-                // @codingStandardsIgnoreStart
6471
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6472
-                    // @codingStandardsIgnoreEnd
6473
-                    '1: model name',
6474
-                    'event_espresso'
6475
-                )
6476
-            );
6477
-        }
6478
-        if ($this->model_chain_to_password === '') {
6479
-            $model_with_password = $this;
6480
-        } else {
6481
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6482
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6483
-            } else {
6484
-                $last_model_in_chain = $this->model_chain_to_password;
6485
-            }
6486
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6487
-        }
6488
-
6489
-        $password_field = $model_with_password->getPasswordField();
6490
-        if ($password_field instanceof EE_Password_Field) {
6491
-            $password_field_name = $password_field->get_name();
6492
-        } else {
6493
-            throw new ModelConfigurationException(
6494
-                $this,
6495
-                sprintf(
6496
-                    esc_html_x(
6497
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6498
-                        '1: model name, 2: special string',
6499
-                        'event_espresso'
6500
-                    ),
6501
-                    $model_with_password->get_this_model_name(),
6502
-                    $this->model_chain_to_password
6503
-                )
6504
-            );
6505
-        }
6506
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6507
-    }
6508
-
6509
-    /**
6510
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6511
-     * or if this model itself has a password affecting access to some of its other fields.
6512
-     * @since 4.9.74.p
6513
-     * @return boolean
6514
-     */
6515
-    public function restrictedByRelatedModelPassword()
6516
-    {
6517
-        return $this->model_chain_to_password !== null;
6518
-    }
3815
+		}
3816
+		return $null_friendly_where_conditions;
3817
+	}
3818
+
3819
+
3820
+
3821
+	/**
3822
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3823
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3824
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3825
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3826
+	 *
3827
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3828
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3829
+	 */
3830
+	private function _get_default_where_conditions($model_relation_path = null)
3831
+	{
3832
+		if ($this->_ignore_where_strategy) {
3833
+			return array();
3834
+		}
3835
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3836
+	}
3837
+
3838
+
3839
+
3840
+	/**
3841
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3842
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3843
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3844
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3845
+	 * Similar to _get_default_where_conditions
3846
+	 *
3847
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3848
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3849
+	 */
3850
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3851
+	{
3852
+		if ($this->_ignore_where_strategy) {
3853
+			return array();
3854
+		}
3855
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3856
+	}
3857
+
3858
+
3859
+
3860
+	/**
3861
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3862
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3863
+	 *
3864
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3865
+	 * @return string
3866
+	 * @throws EE_Error
3867
+	 */
3868
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3869
+	{
3870
+		$selects = $this->_get_columns_to_select_for_this_model();
3871
+		foreach (
3872
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3873
+		) {
3874
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3875
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3876
+			foreach ($other_model_selects as $key => $value) {
3877
+				$selects[] = $value;
3878
+			}
3879
+		}
3880
+		return implode(", ", $selects);
3881
+	}
3882
+
3883
+
3884
+
3885
+	/**
3886
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3887
+	 * So that's going to be the columns for all the fields on the model
3888
+	 *
3889
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3890
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3891
+	 */
3892
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3893
+	{
3894
+		$fields = $this->field_settings();
3895
+		$selects = array();
3896
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3897
+			$model_relation_chain,
3898
+			$this->get_this_model_name()
3899
+		);
3900
+		foreach ($fields as $field_obj) {
3901
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3902
+						 . $field_obj->get_table_alias()
3903
+						 . "."
3904
+						 . $field_obj->get_table_column()
3905
+						 . " AS '"
3906
+						 . $table_alias_with_model_relation_chain_prefix
3907
+						 . $field_obj->get_table_alias()
3908
+						 . "."
3909
+						 . $field_obj->get_table_column()
3910
+						 . "'";
3911
+		}
3912
+		// make sure we are also getting the PKs of each table
3913
+		$tables = $this->get_tables();
3914
+		if (count($tables) > 1) {
3915
+			foreach ($tables as $table_obj) {
3916
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917
+									   . $table_obj->get_fully_qualified_pk_column();
3918
+				if (! in_array($qualified_pk_column, $selects)) {
3919
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920
+				}
3921
+			}
3922
+		}
3923
+		return $selects;
3924
+	}
3925
+
3926
+
3927
+
3928
+	/**
3929
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3930
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3931
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3932
+	 * SQL for joining, and the data types
3933
+	 *
3934
+	 * @param null|string                 $original_query_param
3935
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3936
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3937
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3938
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3939
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3940
+	 *                                                          or 'Registration's
3941
+	 * @param string                      $original_query_param what it originally was (eg
3942
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3943
+	 *                                                          matches $query_param
3944
+	 * @throws EE_Error
3945
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3946
+	 */
3947
+	private function _extract_related_model_info_from_query_param(
3948
+		$query_param,
3949
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3950
+		$query_param_type,
3951
+		$original_query_param = null
3952
+	) {
3953
+		if ($original_query_param === null) {
3954
+			$original_query_param = $query_param;
3955
+		}
3956
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3957
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3958
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3959
+		$allow_fields = in_array(
3960
+			$query_param_type,
3961
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3962
+			true
3963
+		);
3964
+		// check to see if we have a field on this model
3965
+		$this_model_fields = $this->field_settings(true);
3966
+		if (array_key_exists($query_param, $this_model_fields)) {
3967
+			if ($allow_fields) {
3968
+				return;
3969
+			}
3970
+			throw new EE_Error(
3971
+				sprintf(
3972
+					esc_html__(
3973
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3974
+						"event_espresso"
3975
+					),
3976
+					$query_param,
3977
+					get_class($this),
3978
+					$query_param_type,
3979
+					$original_query_param
3980
+				)
3981
+			);
3982
+		}
3983
+		// check if this is a special logic query param
3984
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3985
+			if ($allow_logic_query_params) {
3986
+				return;
3987
+			}
3988
+			throw new EE_Error(
3989
+				sprintf(
3990
+					esc_html__(
3991
+						'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',
3992
+						'event_espresso'
3993
+					),
3994
+					implode('", "', $this->_logic_query_param_keys),
3995
+					$query_param,
3996
+					get_class($this),
3997
+					'<br />',
3998
+					"\t"
3999
+					. ' $passed_in_query_info = <pre>'
4000
+					. print_r($passed_in_query_info, true)
4001
+					. '</pre>'
4002
+					. "\n\t"
4003
+					. ' $query_param_type = '
4004
+					. $query_param_type
4005
+					. "\n\t"
4006
+					. ' $original_query_param = '
4007
+					. $original_query_param
4008
+				)
4009
+			);
4010
+		}
4011
+		// check if it's a custom selection
4012
+		if (
4013
+			$this->_custom_selections instanceof CustomSelects
4014
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4015
+		) {
4016
+			return;
4017
+		}
4018
+		// check if has a model name at the beginning
4019
+		// and
4020
+		// check if it's a field on a related model
4021
+		if (
4022
+			$this->extractJoinModelFromQueryParams(
4023
+				$passed_in_query_info,
4024
+				$query_param,
4025
+				$original_query_param,
4026
+				$query_param_type
4027
+			)
4028
+		) {
4029
+			return;
4030
+		}
4031
+
4032
+		// ok so $query_param didn't start with a model name
4033
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4034
+		// it's wack, that's what it is
4035
+		throw new EE_Error(
4036
+			sprintf(
4037
+				esc_html__(
4038
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4039
+					"event_espresso"
4040
+				),
4041
+				$query_param,
4042
+				get_class($this),
4043
+				$query_param_type,
4044
+				$original_query_param
4045
+			)
4046
+		);
4047
+	}
4048
+
4049
+
4050
+	/**
4051
+	 * Extracts any possible join model information from the provided possible_join_string.
4052
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4053
+	 * parts that should be added to the query.
4054
+	 *
4055
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4056
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4057
+	 * @param null|string                 $original_query_param
4058
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4059
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4060
+	 * @return bool  returns true if a join was added and false if not.
4061
+	 * @throws EE_Error
4062
+	 */
4063
+	private function extractJoinModelFromQueryParams(
4064
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4065
+		$possible_join_string,
4066
+		$original_query_param,
4067
+		$query_parameter_type
4068
+	) {
4069
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4071
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4073
+				if ($possible_join_string === '') {
4074
+					// nothing left to $query_param
4075
+					// we should actually end in a field name, not a model like this!
4076
+					throw new EE_Error(
4077
+						sprintf(
4078
+							esc_html__(
4079
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4080
+								"event_espresso"
4081
+							),
4082
+							$possible_join_string,
4083
+							$query_parameter_type,
4084
+							get_class($this),
4085
+							$valid_related_model_name
4086
+						)
4087
+					);
4088
+				}
4089
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4090
+				$related_model_obj->_extract_related_model_info_from_query_param(
4091
+					$possible_join_string,
4092
+					$query_info_carrier,
4093
+					$query_parameter_type,
4094
+					$original_query_param
4095
+				);
4096
+				return true;
4097
+			}
4098
+			if ($possible_join_string === $valid_related_model_name) {
4099
+				$this->_add_join_to_model(
4100
+					$valid_related_model_name,
4101
+					$query_info_carrier,
4102
+					$original_query_param
4103
+				);
4104
+				return true;
4105
+			}
4106
+		}
4107
+		return false;
4108
+	}
4109
+
4110
+
4111
+	/**
4112
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4113
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
+	 * @throws EE_Error
4115
+	 */
4116
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4117
+	{
4118
+		if (
4119
+			$this->_custom_selections instanceof CustomSelects
4120
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4121
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4122
+			)
4123
+		) {
4124
+			$original_selects = $this->_custom_selections->originalSelects();
4125
+			foreach ($original_selects as $alias => $select_configuration) {
4126
+				$this->extractJoinModelFromQueryParams(
4127
+					$query_info_carrier,
4128
+					$select_configuration[0],
4129
+					$select_configuration[0],
4130
+					'custom_selects'
4131
+				);
4132
+			}
4133
+		}
4134
+	}
4135
+
4136
+
4137
+
4138
+	/**
4139
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4140
+	 * and store it on $passed_in_query_info
4141
+	 *
4142
+	 * @param string                      $model_name
4143
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4144
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4145
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4146
+	 *                                                          and are adding a join to 'Payment' with the original
4147
+	 *                                                          query param key
4148
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4149
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4150
+	 *                                                          Payment wants to add default query params so that it
4151
+	 *                                                          will know what models to prepend onto its default query
4152
+	 *                                                          params or in case it wants to rename tables (in case
4153
+	 *                                                          there are multiple joins to the same table)
4154
+	 * @return void
4155
+	 * @throws EE_Error
4156
+	 */
4157
+	private function _add_join_to_model(
4158
+		$model_name,
4159
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4160
+		$original_query_param
4161
+	) {
4162
+		$relation_obj = $this->related_settings_for($model_name);
4163
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4164
+		// check if the relation is HABTM, because then we're essentially doing two joins
4165
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4166
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4167
+			$join_model_obj = $relation_obj->get_join_model();
4168
+			// replace the model specified with the join model for this relation chain, whi
4169
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4170
+				$model_name,
4171
+				$join_model_obj->get_this_model_name(),
4172
+				$model_relation_chain
4173
+			);
4174
+			$passed_in_query_info->merge(
4175
+				new EE_Model_Query_Info_Carrier(
4176
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4177
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4178
+				)
4179
+			);
4180
+		}
4181
+		// now just join to the other table pointed to by the relation object, and add its data types
4182
+		$passed_in_query_info->merge(
4183
+			new EE_Model_Query_Info_Carrier(
4184
+				array($model_relation_chain => $model_name),
4185
+				$relation_obj->get_join_statement($model_relation_chain)
4186
+			)
4187
+		);
4188
+	}
4189
+
4190
+
4191
+
4192
+	/**
4193
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4194
+	 *
4195
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4196
+	 * @return string of SQL
4197
+	 * @throws EE_Error
4198
+	 */
4199
+	private function _construct_where_clause($where_params)
4200
+	{
4201
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202
+		if ($SQL) {
4203
+			return " WHERE " . $SQL;
4204
+		}
4205
+		return '';
4206
+	}
4207
+
4208
+
4209
+
4210
+	/**
4211
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4212
+	 * and should be passed HAVING parameters, not WHERE parameters
4213
+	 *
4214
+	 * @param array $having_params
4215
+	 * @return string
4216
+	 * @throws EE_Error
4217
+	 */
4218
+	private function _construct_having_clause($having_params)
4219
+	{
4220
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221
+		if ($SQL) {
4222
+			return " HAVING " . $SQL;
4223
+		}
4224
+		return '';
4225
+	}
4226
+
4227
+
4228
+	/**
4229
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4230
+	 * Event_Meta.meta_value = 'foo'))"
4231
+	 *
4232
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4233
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4234
+	 * @throws EE_Error
4235
+	 * @return string of SQL
4236
+	 */
4237
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4238
+	{
4239
+		$where_clauses = array();
4240
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4242
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4243
+				switch ($query_param) {
4244
+					case 'not':
4245
+					case 'NOT':
4246
+						$where_clauses[] = "! ("
4247
+										   . $this->_construct_condition_clause_recursive(
4248
+											   $op_and_value_or_sub_condition,
4249
+											   $glue
4250
+										   )
4251
+										   . ")";
4252
+						break;
4253
+					case 'and':
4254
+					case 'AND':
4255
+						$where_clauses[] = " ("
4256
+										   . $this->_construct_condition_clause_recursive(
4257
+											   $op_and_value_or_sub_condition,
4258
+											   ' AND '
4259
+										   )
4260
+										   . ")";
4261
+						break;
4262
+					case 'or':
4263
+					case 'OR':
4264
+						$where_clauses[] = " ("
4265
+										   . $this->_construct_condition_clause_recursive(
4266
+											   $op_and_value_or_sub_condition,
4267
+											   ' OR '
4268
+										   )
4269
+										   . ")";
4270
+						break;
4271
+				}
4272
+			} else {
4273
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4274
+				// if it's not a normal field, maybe it's a custom selection?
4275
+				if (! $field_obj) {
4276
+					if ($this->_custom_selections instanceof CustomSelects) {
4277
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278
+					} else {
4279
+						throw new EE_Error(sprintf(esc_html__(
4280
+							"%s is neither a valid model field name, nor a custom selection",
4281
+							"event_espresso"
4282
+						), $query_param));
4283
+					}
4284
+				}
4285
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4287
+			}
4288
+		}
4289
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4290
+	}
4291
+
4292
+
4293
+
4294
+	/**
4295
+	 * Takes the input parameter and extract the table name (alias) and column name
4296
+	 *
4297
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4298
+	 * @throws EE_Error
4299
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4300
+	 */
4301
+	private function _deduce_column_name_from_query_param($query_param)
4302
+	{
4303
+		$field = $this->_deduce_field_from_query_param($query_param);
4304
+		if ($field) {
4305
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4306
+				$field->get_model_name(),
4307
+				$query_param
4308
+			);
4309
+			return $table_alias_prefix . $field->get_qualified_column();
4310
+		}
4311
+		if (
4312
+			$this->_custom_selections instanceof CustomSelects
4313
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4314
+		) {
4315
+			// maybe it's custom selection item?
4316
+			// if so, just use it as the "column name"
4317
+			return $query_param;
4318
+		}
4319
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4320
+			? implode(',', $this->_custom_selections->columnAliases())
4321
+			: '';
4322
+		throw new EE_Error(
4323
+			sprintf(
4324
+				esc_html__(
4325
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4326
+					"event_espresso"
4327
+				),
4328
+				$query_param,
4329
+				$custom_select_aliases
4330
+			)
4331
+		);
4332
+	}
4333
+
4334
+
4335
+
4336
+	/**
4337
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4338
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4339
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4340
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4341
+	 *
4342
+	 * @param string $condition_query_param_key
4343
+	 * @return string
4344
+	 */
4345
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4346
+	{
4347
+		$pos_of_star = strpos($condition_query_param_key, '*');
4348
+		if ($pos_of_star === false) {
4349
+			return $condition_query_param_key;
4350
+		}
4351
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4352
+		return $condition_query_param_sans_star;
4353
+	}
4354
+
4355
+
4356
+
4357
+	/**
4358
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4359
+	 *
4360
+	 * @param                            mixed      array | string    $op_and_value
4361
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4362
+	 * @throws EE_Error
4363
+	 * @return string
4364
+	 */
4365
+	private function _construct_op_and_value($op_and_value, $field_obj)
4366
+	{
4367
+		if (is_array($op_and_value)) {
4368
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
+			if (! $operator) {
4370
+				$php_array_like_string = array();
4371
+				foreach ($op_and_value as $key => $value) {
4372
+					$php_array_like_string[] = "$key=>$value";
4373
+				}
4374
+				throw new EE_Error(
4375
+					sprintf(
4376
+						esc_html__(
4377
+							"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))",
4378
+							"event_espresso"
4379
+						),
4380
+						implode(",", $php_array_like_string)
4381
+					)
4382
+				);
4383
+			}
4384
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4385
+		} else {
4386
+			$operator = '=';
4387
+			$value = $op_and_value;
4388
+		}
4389
+		// check to see if the value is actually another field
4390
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4392
+		}
4393
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394
+			// in this case, the value should be an array, or at least a comma-separated list
4395
+			// it will need to handle a little differently
4396
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4397
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4398
+			return $operator . SP . $cleaned_value;
4399
+		}
4400
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401
+			// the value should be an array with count of two.
4402
+			if (count($value) !== 2) {
4403
+				throw new EE_Error(
4404
+					sprintf(
4405
+						esc_html__(
4406
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4407
+							'event_espresso'
4408
+						),
4409
+						"BETWEEN"
4410
+					)
4411
+				);
4412
+			}
4413
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
+			return $operator . SP . $cleaned_value;
4415
+		}
4416
+		if (in_array($operator, $this->valid_null_style_operators())) {
4417
+			if ($value !== null) {
4418
+				throw new EE_Error(
4419
+					sprintf(
4420
+						esc_html__(
4421
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4422
+							"event_espresso"
4423
+						),
4424
+						$value,
4425
+						$operator
4426
+					)
4427
+				);
4428
+			}
4429
+			return $operator;
4430
+		}
4431
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4433
+			// remove other junk. So just treat it as a string.
4434
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4435
+		}
4436
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
+		}
4439
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440
+			throw new EE_Error(
4441
+				sprintf(
4442
+					esc_html__(
4443
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4444
+						'event_espresso'
4445
+					),
4446
+					$operator,
4447
+					$operator
4448
+				)
4449
+			);
4450
+		}
4451
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
+			throw new EE_Error(
4453
+				sprintf(
4454
+					esc_html__(
4455
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4456
+						'event_espresso'
4457
+					),
4458
+					$operator,
4459
+					$operator
4460
+				)
4461
+			);
4462
+		}
4463
+		throw new EE_Error(
4464
+			sprintf(
4465
+				esc_html__(
4466
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4467
+					"event_espresso"
4468
+				),
4469
+				http_build_query($op_and_value)
4470
+			)
4471
+		);
4472
+	}
4473
+
4474
+
4475
+
4476
+	/**
4477
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4478
+	 *
4479
+	 * @param array                      $values
4480
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4481
+	 *                                              '%s'
4482
+	 * @return string
4483
+	 * @throws EE_Error
4484
+	 */
4485
+	public function _construct_between_value($values, $field_obj)
4486
+	{
4487
+		$cleaned_values = array();
4488
+		foreach ($values as $value) {
4489
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490
+		}
4491
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4492
+	}
4493
+
4494
+
4495
+	/**
4496
+	 * Takes an array or a comma-separated list of $values and cleans them
4497
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4498
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
+	 *
4502
+	 * @param mixed                      $values    array or comma-separated string
4503
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
+	 * @throws EE_Error
4506
+	 */
4507
+	public function _construct_in_value($values, $field_obj)
4508
+	{
4509
+		$prepped = [];
4510
+		// check if the value is a CSV list
4511
+		if (is_string($values)) {
4512
+			// in which case, turn it into an array
4513
+			$values = explode(',', $values);
4514
+		}
4515
+		// make sure we only have one of each value in the list
4516
+		$values = array_unique($values);
4517
+		foreach ($values as $value) {
4518
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4519
+		}
4520
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4521
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4522
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523
+		if (empty($prepped)) {
4524
+			$all_fields = $this->field_settings();
4525
+			$first_field    = reset($all_fields);
4526
+			$main_table = $this->_get_main_table();
4527
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528
+		}
4529
+		return '(' . implode(',', $prepped) . ')';
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * @param mixed                      $value
4536
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4537
+	 * @throws EE_Error
4538
+	 * @return false|null|string
4539
+	 */
4540
+	private function _wpdb_prepare_using_field($value, $field_obj)
4541
+	{
4542
+		/** @type WPDB $wpdb */
4543
+		global $wpdb;
4544
+		if ($field_obj instanceof EE_Model_Field_Base) {
4545
+			return $wpdb->prepare(
4546
+				$field_obj->get_wpdb_data_type(),
4547
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4548
+			);
4549
+		} //$field_obj should really just be a data type
4550
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551
+			throw new EE_Error(
4552
+				sprintf(
4553
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4554
+					$field_obj,
4555
+					implode(",", $this->_valid_wpdb_data_types)
4556
+				)
4557
+			);
4558
+		}
4559
+		return $wpdb->prepare($field_obj, $value);
4560
+	}
4561
+
4562
+
4563
+
4564
+	/**
4565
+	 * Takes the input parameter and finds the model field that it indicates.
4566
+	 *
4567
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4568
+	 * @throws EE_Error
4569
+	 * @return EE_Model_Field_Base
4570
+	 */
4571
+	protected function _deduce_field_from_query_param($query_param_name)
4572
+	{
4573
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4574
+		// which will help us find the database table and column
4575
+		$query_param_parts = explode(".", $query_param_name);
4576
+		if (empty($query_param_parts)) {
4577
+			throw new EE_Error(sprintf(esc_html__(
4578
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4579
+				'event_espresso'
4580
+			), $query_param_name));
4581
+		}
4582
+		$number_of_parts = count($query_param_parts);
4583
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4584
+		if ($number_of_parts === 1) {
4585
+			$field_name = $last_query_param_part;
4586
+			$model_obj = $this;
4587
+		} else {// $number_of_parts >= 2
4588
+			// the last part is the column name, and there are only 2parts. therefore...
4589
+			$field_name = $last_query_param_part;
4590
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4591
+		}
4592
+		try {
4593
+			return $model_obj->field_settings_for($field_name);
4594
+		} catch (EE_Error $e) {
4595
+			return null;
4596
+		}
4597
+	}
4598
+
4599
+
4600
+
4601
+	/**
4602
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4603
+	 * alias and column which corresponds to it
4604
+	 *
4605
+	 * @param string $field_name
4606
+	 * @throws EE_Error
4607
+	 * @return string
4608
+	 */
4609
+	public function _get_qualified_column_for_field($field_name)
4610
+	{
4611
+		$all_fields = $this->field_settings();
4612
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4613
+		if ($field) {
4614
+			return $field->get_qualified_column();
4615
+		}
4616
+		throw new EE_Error(
4617
+			sprintf(
4618
+				esc_html__(
4619
+					"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.",
4620
+					'event_espresso'
4621
+				),
4622
+				$field_name,
4623
+				get_class($this)
4624
+			)
4625
+		);
4626
+	}
4627
+
4628
+
4629
+
4630
+	/**
4631
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4632
+	 * Example usage:
4633
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4634
+	 *      array(),
4635
+	 *      ARRAY_A,
4636
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4637
+	 *  );
4638
+	 * is equivalent to
4639
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4640
+	 * and
4641
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4642
+	 *      array(
4643
+	 *          array(
4644
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4645
+	 *          ),
4646
+	 *          ARRAY_A,
4647
+	 *          implode(
4648
+	 *              ', ',
4649
+	 *              array_merge(
4650
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4651
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4652
+	 *              )
4653
+	 *          )
4654
+	 *      )
4655
+	 *  );
4656
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4657
+	 *
4658
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4659
+	 *                                            and the one whose fields you are selecting for example: when querying
4660
+	 *                                            tickets model and selecting fields from the tickets model you would
4661
+	 *                                            leave this parameter empty, because no models are needed to join
4662
+	 *                                            between the queried model and the selected one. Likewise when
4663
+	 *                                            querying the datetime model and selecting fields from the tickets
4664
+	 *                                            model, it would also be left empty, because there is a direct
4665
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4666
+	 *                                            them together. However, when querying from the event model and
4667
+	 *                                            selecting fields from the ticket model, you should provide the string
4668
+	 *                                            'Datetime', indicating that the event model must first join to the
4669
+	 *                                            datetime model in order to find its relation to ticket model.
4670
+	 *                                            Also, when querying from the venue model and selecting fields from
4671
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4672
+	 *                                            indicating you need to join the venue model to the event model,
4673
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4674
+	 *                                            This string is used to deduce the prefix that gets added onto the
4675
+	 *                                            models' tables qualified columns
4676
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4677
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4678
+	 *                                            qualified column names
4679
+	 * @return array|string
4680
+	 */
4681
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682
+	{
4683
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4684
+		$qualified_columns = array();
4685
+		foreach ($this->field_settings() as $field_name => $field) {
4686
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4687
+		}
4688
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689
+	}
4690
+
4691
+
4692
+
4693
+	/**
4694
+	 * constructs the select use on special limit joins
4695
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4696
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4697
+	 * (as that is typically where the limits would be set).
4698
+	 *
4699
+	 * @param  string       $table_alias The table the select is being built for
4700
+	 * @param  mixed|string $limit       The limit for this select
4701
+	 * @return string                The final select join element for the query.
4702
+	 */
4703
+	public function _construct_limit_join_select($table_alias, $limit)
4704
+	{
4705
+		$SQL = '';
4706
+		foreach ($this->_tables as $table_obj) {
4707
+			if ($table_obj instanceof EE_Primary_Table) {
4708
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4709
+					? $table_obj->get_select_join_limit($limit)
4710
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4711
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4712
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4713
+					? $table_obj->get_select_join_limit_join($limit)
4714
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4715
+			}
4716
+		}
4717
+		return $SQL;
4718
+	}
4719
+
4720
+
4721
+
4722
+	/**
4723
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4724
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4725
+	 *
4726
+	 * @return string SQL
4727
+	 * @throws EE_Error
4728
+	 */
4729
+	public function _construct_internal_join()
4730
+	{
4731
+		$SQL = $this->_get_main_table()->get_table_sql();
4732
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4733
+		return $SQL;
4734
+	}
4735
+
4736
+
4737
+
4738
+	/**
4739
+	 * Constructs the SQL for joining all the tables on this model.
4740
+	 * Normally $alias should be the primary table's alias, but in cases where
4741
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4742
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4743
+	 * alias, this will construct SQL like:
4744
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4745
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4746
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
+	 *
4748
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4749
+	 * @return string
4750
+	 */
4751
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4752
+	{
4753
+		$SQL = '';
4754
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4755
+		foreach ($this->_tables as $table_obj) {
4756
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4757
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4758
+					// so we're joining to this table, meaning the table is already in
4759
+					// the FROM statement, BUT the primary table isn't. So we want
4760
+					// to add the inverse join sql
4761
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4762
+				} else {
4763
+					// just add a regular JOIN to this table from the primary table
4764
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4765
+				}
4766
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4767
+		}
4768
+		return $SQL;
4769
+	}
4770
+
4771
+
4772
+
4773
+	/**
4774
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4775
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4776
+	 * their data type (eg, '%s', '%d', etc)
4777
+	 *
4778
+	 * @return array
4779
+	 */
4780
+	public function _get_data_types()
4781
+	{
4782
+		$data_types = array();
4783
+		foreach ($this->field_settings() as $field_obj) {
4784
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785
+			/** @var $field_obj EE_Model_Field_Base */
4786
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4787
+		}
4788
+		return $data_types;
4789
+	}
4790
+
4791
+
4792
+
4793
+	/**
4794
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4795
+	 *
4796
+	 * @param string $model_name
4797
+	 * @throws EE_Error
4798
+	 * @return EEM_Base
4799
+	 */
4800
+	public function get_related_model_obj($model_name)
4801
+	{
4802
+		$model_classname = "EEM_" . $model_name;
4803
+		if (! class_exists($model_classname)) {
4804
+			throw new EE_Error(sprintf(esc_html__(
4805
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806
+				'event_espresso'
4807
+			), $model_name, $model_classname));
4808
+		}
4809
+		return call_user_func($model_classname . "::instance");
4810
+	}
4811
+
4812
+
4813
+
4814
+	/**
4815
+	 * Returns the array of EE_ModelRelations for this model.
4816
+	 *
4817
+	 * @return EE_Model_Relation_Base[]
4818
+	 */
4819
+	public function relation_settings()
4820
+	{
4821
+		return $this->_model_relations;
4822
+	}
4823
+
4824
+
4825
+
4826
+	/**
4827
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4828
+	 * because without THOSE models, this model probably doesn't have much purpose.
4829
+	 * (Eg, without an event, datetimes have little purpose.)
4830
+	 *
4831
+	 * @return EE_Belongs_To_Relation[]
4832
+	 */
4833
+	public function belongs_to_relations()
4834
+	{
4835
+		$belongs_to_relations = array();
4836
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4839
+			}
4840
+		}
4841
+		return $belongs_to_relations;
4842
+	}
4843
+
4844
+
4845
+
4846
+	/**
4847
+	 * Returns the specified EE_Model_Relation, or throws an exception
4848
+	 *
4849
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4850
+	 * @throws EE_Error
4851
+	 * @return EE_Model_Relation_Base
4852
+	 */
4853
+	public function related_settings_for($relation_name)
4854
+	{
4855
+		$relatedModels = $this->relation_settings();
4856
+		if (! array_key_exists($relation_name, $relatedModels)) {
4857
+			throw new EE_Error(
4858
+				sprintf(
4859
+					esc_html__(
4860
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4861
+						'event_espresso'
4862
+					),
4863
+					$relation_name,
4864
+					$this->_get_class_name(),
4865
+					implode(', ', array_keys($relatedModels))
4866
+				)
4867
+			);
4868
+		}
4869
+		return $relatedModels[ $relation_name ];
4870
+	}
4871
+
4872
+
4873
+
4874
+	/**
4875
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4876
+	 * fields
4877
+	 *
4878
+	 * @param string $fieldName
4879
+	 * @param boolean $include_db_only_fields
4880
+	 * @throws EE_Error
4881
+	 * @return EE_Model_Field_Base
4882
+	 */
4883
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4884
+	{
4885
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4886
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4887
+			throw new EE_Error(sprintf(
4888
+				esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889
+				$fieldName,
4890
+				get_class($this)
4891
+			));
4892
+		}
4893
+		return $fieldSettings[ $fieldName ];
4894
+	}
4895
+
4896
+
4897
+
4898
+	/**
4899
+	 * Checks if this field exists on this model
4900
+	 *
4901
+	 * @param string $fieldName a key in the model's _field_settings array
4902
+	 * @return boolean
4903
+	 */
4904
+	public function has_field($fieldName)
4905
+	{
4906
+		$fieldSettings = $this->field_settings(true);
4907
+		if (isset($fieldSettings[ $fieldName ])) {
4908
+			return true;
4909
+		}
4910
+		return false;
4911
+	}
4912
+
4913
+
4914
+
4915
+	/**
4916
+	 * Returns whether or not this model has a relation to the specified model
4917
+	 *
4918
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4919
+	 * @return boolean
4920
+	 */
4921
+	public function has_relation($relation_name)
4922
+	{
4923
+		$relations = $this->relation_settings();
4924
+		if (isset($relations[ $relation_name ])) {
4925
+			return true;
4926
+		}
4927
+		return false;
4928
+	}
4929
+
4930
+
4931
+
4932
+	/**
4933
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
+	 * Eg, on EE_Answer that would be ANS_ID field object
4935
+	 *
4936
+	 * @param $field_obj
4937
+	 * @return boolean
4938
+	 */
4939
+	public function is_primary_key_field($field_obj)
4940
+	{
4941
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4942
+	}
4943
+
4944
+
4945
+
4946
+	/**
4947
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4948
+	 * Eg, on EE_Answer that would be ANS_ID field object
4949
+	 *
4950
+	 * @return EE_Model_Field_Base
4951
+	 * @throws EE_Error
4952
+	 */
4953
+	public function get_primary_key_field()
4954
+	{
4955
+		if ($this->_primary_key_field === null) {
4956
+			foreach ($this->field_settings(true) as $field_obj) {
4957
+				if ($this->is_primary_key_field($field_obj)) {
4958
+					$this->_primary_key_field = $field_obj;
4959
+					break;
4960
+				}
4961
+			}
4962
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963
+				throw new EE_Error(sprintf(
4964
+					esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965
+					get_class($this)
4966
+				));
4967
+			}
4968
+		}
4969
+		return $this->_primary_key_field;
4970
+	}
4971
+
4972
+
4973
+
4974
+	/**
4975
+	 * Returns whether or not not there is a primary key on this model.
4976
+	 * Internally does some caching.
4977
+	 *
4978
+	 * @return boolean
4979
+	 */
4980
+	public function has_primary_key_field()
4981
+	{
4982
+		if ($this->_has_primary_key_field === null) {
4983
+			try {
4984
+				$this->get_primary_key_field();
4985
+				$this->_has_primary_key_field = true;
4986
+			} catch (EE_Error $e) {
4987
+				$this->_has_primary_key_field = false;
4988
+			}
4989
+		}
4990
+		return $this->_has_primary_key_field;
4991
+	}
4992
+
4993
+
4994
+
4995
+	/**
4996
+	 * Finds the first field of type $field_class_name.
4997
+	 *
4998
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4999
+	 *                                 EE_Foreign_Key_Field, etc
5000
+	 * @return EE_Model_Field_Base or null if none is found
5001
+	 */
5002
+	public function get_a_field_of_type($field_class_name)
5003
+	{
5004
+		foreach ($this->field_settings() as $field) {
5005
+			if ($field instanceof $field_class_name) {
5006
+				return $field;
5007
+			}
5008
+		}
5009
+		return null;
5010
+	}
5011
+
5012
+
5013
+
5014
+	/**
5015
+	 * Gets a foreign key field pointing to model.
5016
+	 *
5017
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5018
+	 * @return EE_Foreign_Key_Field_Base
5019
+	 * @throws EE_Error
5020
+	 */
5021
+	public function get_foreign_key_to($model_name)
5022
+	{
5023
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5024
+			foreach ($this->field_settings() as $field) {
5025
+				if (
5026
+					$field instanceof EE_Foreign_Key_Field_Base
5027
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5028
+				) {
5029
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5030
+					break;
5031
+				}
5032
+			}
5033
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5034
+				throw new EE_Error(sprintf(esc_html__(
5035
+					"There is no foreign key field pointing to model %s on model %s",
5036
+					'event_espresso'
5037
+				), $model_name, get_class($this)));
5038
+			}
5039
+		}
5040
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5041
+	}
5042
+
5043
+
5044
+
5045
+	/**
5046
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5047
+	 *
5048
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5049
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5050
+	 *                            Either one works
5051
+	 * @return string
5052
+	 */
5053
+	public function get_table_for_alias($table_alias)
5054
+	{
5055
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5057
+	}
5058
+
5059
+
5060
+
5061
+	/**
5062
+	 * Returns a flat array of all field son this model, instead of organizing them
5063
+	 * by table_alias as they are in the constructor.
5064
+	 *
5065
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5066
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5067
+	 */
5068
+	public function field_settings($include_db_only_fields = false)
5069
+	{
5070
+		if ($include_db_only_fields) {
5071
+			if ($this->_cached_fields === null) {
5072
+				$this->_cached_fields = array();
5073
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5074
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
+						$this->_cached_fields[ $field_name ] = $field_obj;
5076
+					}
5077
+				}
5078
+			}
5079
+			return $this->_cached_fields;
5080
+		}
5081
+		if ($this->_cached_fields_non_db_only === null) {
5082
+			$this->_cached_fields_non_db_only = array();
5083
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5084
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085
+					/** @var $field_obj EE_Model_Field_Base */
5086
+					if (! $field_obj->is_db_only_field()) {
5087
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
+					}
5089
+				}
5090
+			}
5091
+		}
5092
+		return $this->_cached_fields_non_db_only;
5093
+	}
5094
+
5095
+
5096
+
5097
+	/**
5098
+	 *        cycle though array of attendees and create objects out of each item
5099
+	 *
5100
+	 * @access        private
5101
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5102
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5103
+	 *                           numerically indexed)
5104
+	 * @throws EE_Error
5105
+	 */
5106
+	protected function _create_objects($rows = array())
5107
+	{
5108
+		$array_of_objects = array();
5109
+		if (empty($rows)) {
5110
+			return array();
5111
+		}
5112
+		$count_if_model_has_no_primary_key = 0;
5113
+		$has_primary_key = $this->has_primary_key_field();
5114
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5115
+		foreach ((array) $rows as $row) {
5116
+			if (empty($row)) {
5117
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5118
+				return array();
5119
+			}
5120
+			// check if we've already set this object in the results array,
5121
+			// in which case there's no need to process it further (again)
5122
+			if ($has_primary_key) {
5123
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5124
+					$row,
5125
+					$primary_key_field->get_qualified_column(),
5126
+					$primary_key_field->get_table_column()
5127
+				);
5128
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5129
+					continue;
5130
+				}
5131
+			}
5132
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5133
+			if (! $classInstance) {
5134
+				throw new EE_Error(
5135
+					sprintf(
5136
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5137
+						$this->get_this_model_name(),
5138
+						http_build_query($row)
5139
+					)
5140
+				);
5141
+			}
5142
+			// set the timezone on the instantiated objects
5143
+			$classInstance->set_timezone($this->_timezone);
5144
+			// make sure if there is any timezone setting present that we set the timezone for the object
5145
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
+			$array_of_objects[ $key ] = $classInstance;
5147
+			// also, for all the relations of type BelongsTo, see if we can cache
5148
+			// those related models
5149
+			// (we could do this for other relations too, but if there are conditions
5150
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5151
+			// so it requires a little more thought than just caching them immediately...)
5152
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5153
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5154
+					// check if this model's INFO is present. If so, cache it on the model
5155
+					$other_model = $relation_obj->get_other_model();
5156
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5157
+					// if we managed to make a model object from the results, cache it on the main model object
5158
+					if ($other_model_obj_maybe) {
5159
+						// set timezone on these other model objects if they are present
5160
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5161
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5162
+					}
5163
+				}
5164
+			}
5165
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5166
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5167
+			// the field in the CustomSelects object
5168
+			if ($this->_custom_selections instanceof CustomSelects) {
5169
+				$classInstance->setCustomSelectsValues(
5170
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5171
+				);
5172
+			}
5173
+		}
5174
+		return $array_of_objects;
5175
+	}
5176
+
5177
+
5178
+	/**
5179
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5180
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5181
+	 *
5182
+	 * @param array $db_results_row
5183
+	 * @return array
5184
+	 */
5185
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5186
+	{
5187
+		$results = array();
5188
+		if ($this->_custom_selections instanceof CustomSelects) {
5189
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
+				if (isset($db_results_row[ $alias ])) {
5191
+					$results[ $alias ] = $this->convertValueToDataType(
5192
+						$db_results_row[ $alias ],
5193
+						$this->_custom_selections->getDataTypeForAlias($alias)
5194
+					);
5195
+				}
5196
+			}
5197
+		}
5198
+		return $results;
5199
+	}
5200
+
5201
+
5202
+	/**
5203
+	 * This will set the value for the given alias
5204
+	 * @param string $value
5205
+	 * @param string $datatype (one of %d, %s, %f)
5206
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5207
+	 */
5208
+	protected function convertValueToDataType($value, $datatype)
5209
+	{
5210
+		switch ($datatype) {
5211
+			case '%f':
5212
+				return (float) $value;
5213
+			case '%d':
5214
+				return (int) $value;
5215
+			default:
5216
+				return (string) $value;
5217
+		}
5218
+	}
5219
+
5220
+
5221
+	/**
5222
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5223
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5224
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5225
+	 * object (as set in the model_field!).
5226
+	 *
5227
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5228
+	 */
5229
+	public function create_default_object()
5230
+	{
5231
+		$this_model_fields_and_values = array();
5232
+		// setup the row using default values;
5233
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5234
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5235
+		}
5236
+		$className = $this->_get_class_name();
5237
+		$classInstance = EE_Registry::instance()
5238
+									->load_class($className, array($this_model_fields_and_values), false, false);
5239
+		return $classInstance;
5240
+	}
5241
+
5242
+
5243
+
5244
+	/**
5245
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5246
+	 *                             or an stdClass where each property is the name of a column,
5247
+	 * @return EE_Base_Class
5248
+	 * @throws EE_Error
5249
+	 */
5250
+	public function instantiate_class_from_array_or_object($cols_n_values)
5251
+	{
5252
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5253
+			$cols_n_values = get_object_vars($cols_n_values);
5254
+		}
5255
+		$primary_key = null;
5256
+		// make sure the array only has keys that are fields/columns on this model
5257
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
+		}
5261
+		$className = $this->_get_class_name();
5262
+		// check we actually found results that we can use to build our model object
5263
+		// if not, return null
5264
+		if ($this->has_primary_key_field()) {
5265
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5266
+				return null;
5267
+			}
5268
+		} elseif ($this->unique_indexes()) {
5269
+			$first_column = reset($this_model_fields_n_values);
5270
+			if (empty($first_column)) {
5271
+				return null;
5272
+			}
5273
+		}
5274
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275
+		if ($primary_key) {
5276
+			$classInstance = $this->get_from_entity_map($primary_key);
5277
+			if (! $classInstance) {
5278
+				$classInstance = EE_Registry::instance()
5279
+											->load_class(
5280
+												$className,
5281
+												array($this_model_fields_n_values, $this->_timezone),
5282
+												true,
5283
+												false
5284
+											);
5285
+				// add this new object to the entity map
5286
+				$classInstance = $this->add_to_entity_map($classInstance);
5287
+			}
5288
+		} else {
5289
+			$classInstance = EE_Registry::instance()
5290
+										->load_class(
5291
+											$className,
5292
+											array($this_model_fields_n_values, $this->_timezone),
5293
+											true,
5294
+											false
5295
+										);
5296
+		}
5297
+		return $classInstance;
5298
+	}
5299
+
5300
+
5301
+
5302
+	/**
5303
+	 * Gets the model object from the  entity map if it exists
5304
+	 *
5305
+	 * @param int|string $id the ID of the model object
5306
+	 * @return EE_Base_Class
5307
+	 */
5308
+	public function get_from_entity_map($id)
5309
+	{
5310
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
+	}
5313
+
5314
+
5315
+
5316
+	/**
5317
+	 * add_to_entity_map
5318
+	 * Adds the object to the model's entity mappings
5319
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5320
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5321
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5322
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5323
+	 *        then this method should be called immediately after the update query
5324
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5325
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5326
+	 *
5327
+	 * @param    EE_Base_Class $object
5328
+	 * @throws EE_Error
5329
+	 * @return \EE_Base_Class
5330
+	 */
5331
+	public function add_to_entity_map(EE_Base_Class $object)
5332
+	{
5333
+		$className = $this->_get_class_name();
5334
+		if (! $object instanceof $className) {
5335
+			throw new EE_Error(sprintf(
5336
+				esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337
+				is_object($object) ? get_class($object) : $object,
5338
+				$className
5339
+			));
5340
+		}
5341
+		/** @var $object EE_Base_Class */
5342
+		if (! $object->ID()) {
5343
+			throw new EE_Error(sprintf(esc_html__(
5344
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5345
+				"event_espresso"
5346
+			), get_class($this)));
5347
+		}
5348
+		// double check it's not already there
5349
+		$classInstance = $this->get_from_entity_map($object->ID());
5350
+		if ($classInstance) {
5351
+			return $classInstance;
5352
+		}
5353
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5354
+		return $object;
5355
+	}
5356
+
5357
+
5358
+
5359
+	/**
5360
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5361
+	 * if no identifier is provided, then the entire entity map is emptied
5362
+	 *
5363
+	 * @param int|string $id the ID of the model object
5364
+	 * @return boolean
5365
+	 */
5366
+	public function clear_entity_map($id = null)
5367
+	{
5368
+		if (empty($id)) {
5369
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5370
+			return true;
5371
+		}
5372
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
+			return true;
5375
+		}
5376
+		return false;
5377
+	}
5378
+
5379
+
5380
+
5381
+	/**
5382
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5383
+	 * Given an array where keys are column (or column alias) names and values,
5384
+	 * returns an array of their corresponding field names and database values
5385
+	 *
5386
+	 * @param array $cols_n_values
5387
+	 * @return array
5388
+	 */
5389
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
+	{
5391
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5392
+	}
5393
+
5394
+
5395
+
5396
+	/**
5397
+	 * _deduce_fields_n_values_from_cols_n_values
5398
+	 * Given an array where keys are column (or column alias) names and values,
5399
+	 * returns an array of their corresponding field names and database values
5400
+	 *
5401
+	 * @param string $cols_n_values
5402
+	 * @return array
5403
+	 */
5404
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5405
+	{
5406
+		$this_model_fields_n_values = array();
5407
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5408
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5409
+				$cols_n_values,
5410
+				$table_obj->get_fully_qualified_pk_column(),
5411
+				$table_obj->get_pk_column()
5412
+			);
5413
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5414
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
+					if (! $field_obj->is_db_only_field()) {
5417
+						// prepare field as if its coming from db
5418
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5420
+					}
5421
+				}
5422
+			} else {
5423
+				// the table's rows existed. Use their values
5424
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
+					if (! $field_obj->is_db_only_field()) {
5426
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
+							$cols_n_values,
5428
+							$field_obj->get_qualified_column(),
5429
+							$field_obj->get_table_column()
5430
+						);
5431
+					}
5432
+				}
5433
+			}
5434
+		}
5435
+		return $this_model_fields_n_values;
5436
+	}
5437
+
5438
+
5439
+	/**
5440
+	 * @param $cols_n_values
5441
+	 * @param $qualified_column
5442
+	 * @param $regular_column
5443
+	 * @return null
5444
+	 * @throws EE_Error
5445
+	 * @throws ReflectionException
5446
+	 */
5447
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5448
+	{
5449
+		$value = null;
5450
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451
+		// does the field on the model relate to this column retrieved from the db?
5452
+		// or is it a db-only field? (not relating to the model)
5453
+		if (isset($cols_n_values[ $qualified_column ])) {
5454
+			$value = $cols_n_values[ $qualified_column ];
5455
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5456
+			$value = $cols_n_values[ $regular_column ];
5457
+		} elseif (! empty($this->foreign_key_aliases)) {
5458
+			// no PK?  ok check if there is a foreign key alias set for this table
5459
+			// then check if that alias exists in the incoming data
5460
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
+					$value = $cols_n_values[ $FK_alias ];
5464
+					list($pk_class) = explode('.', $PK_column);
5465
+					$pk_model_name = "EEM_{$pk_class}";
5466
+					/** @var EEM_Base $pk_model */
5467
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5468
+					if ($pk_model instanceof EEM_Base) {
5469
+						// make sure object is pulled from db and added to entity map
5470
+						$pk_model->get_one_by_ID($value);
5471
+					}
5472
+					break;
5473
+				}
5474
+			}
5475
+		}
5476
+		return $value;
5477
+	}
5478
+
5479
+
5480
+
5481
+	/**
5482
+	 * refresh_entity_map_from_db
5483
+	 * Makes sure the model object in the entity map at $id assumes the values
5484
+	 * of the database (opposite of EE_base_Class::save())
5485
+	 *
5486
+	 * @param int|string $id
5487
+	 * @return EE_Base_Class
5488
+	 * @throws EE_Error
5489
+	 */
5490
+	public function refresh_entity_map_from_db($id)
5491
+	{
5492
+		$obj_in_map = $this->get_from_entity_map($id);
5493
+		if ($obj_in_map) {
5494
+			$wpdb_results = $this->_get_all_wpdb_results(
5495
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5496
+			);
5497
+			if ($wpdb_results && is_array($wpdb_results)) {
5498
+				$one_row = reset($wpdb_results);
5499
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5500
+					$obj_in_map->set_from_db($field_name, $db_value);
5501
+				}
5502
+				// clear the cache of related model objects
5503
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5504
+					$obj_in_map->clear_cache($relation_name, null, true);
5505
+				}
5506
+			}
5507
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5508
+			return $obj_in_map;
5509
+		}
5510
+		return $this->get_one_by_ID($id);
5511
+	}
5512
+
5513
+
5514
+
5515
+	/**
5516
+	 * refresh_entity_map_with
5517
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5518
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5519
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5520
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5521
+	 *
5522
+	 * @param int|string    $id
5523
+	 * @param EE_Base_Class $replacing_model_obj
5524
+	 * @return \EE_Base_Class
5525
+	 * @throws EE_Error
5526
+	 */
5527
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5528
+	{
5529
+		$obj_in_map = $this->get_from_entity_map($id);
5530
+		if ($obj_in_map) {
5531
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5532
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5533
+					$obj_in_map->set($field_name, $value);
5534
+				}
5535
+				// make the model object in the entity map's cache match the $replacing_model_obj
5536
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5537
+					$obj_in_map->clear_cache($relation_name, null, true);
5538
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5539
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5540
+					}
5541
+				}
5542
+			}
5543
+			return $obj_in_map;
5544
+		}
5545
+		$this->add_to_entity_map($replacing_model_obj);
5546
+		return $replacing_model_obj;
5547
+	}
5548
+
5549
+
5550
+
5551
+	/**
5552
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5553
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5554
+	 * require_once($this->_getClassName().".class.php");
5555
+	 *
5556
+	 * @return string
5557
+	 */
5558
+	private function _get_class_name()
5559
+	{
5560
+		return "EE_" . $this->get_this_model_name();
5561
+	}
5562
+
5563
+
5564
+
5565
+	/**
5566
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5567
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5568
+	 * it would be 'Events'.
5569
+	 *
5570
+	 * @param int $quantity
5571
+	 * @return string
5572
+	 */
5573
+	public function item_name($quantity = 1)
5574
+	{
5575
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5576
+	}
5577
+
5578
+
5579
+
5580
+	/**
5581
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5582
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5583
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5584
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5585
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5586
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5587
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5588
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5589
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5590
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5591
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5592
+	 *        return $previousReturnValue.$returnString;
5593
+	 * }
5594
+	 * require('EEM_Answer.model.php');
5595
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5596
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5597
+	 *
5598
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5599
+	 * @param array  $args       array of original arguments passed to the function
5600
+	 * @throws EE_Error
5601
+	 * @return mixed whatever the plugin which calls add_filter decides
5602
+	 */
5603
+	public function __call($methodName, $args)
5604
+	{
5605
+		$className = get_class($this);
5606
+		$tagName = "FHEE__{$className}__{$methodName}";
5607
+		if (! has_filter($tagName)) {
5608
+			throw new EE_Error(
5609
+				sprintf(
5610
+					esc_html__(
5611
+						'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 );',
5612
+						'event_espresso'
5613
+					),
5614
+					$methodName,
5615
+					$className,
5616
+					$tagName,
5617
+					'<br />'
5618
+				)
5619
+			);
5620
+		}
5621
+		return apply_filters($tagName, null, $this, $args);
5622
+	}
5623
+
5624
+
5625
+
5626
+	/**
5627
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5628
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5629
+	 *
5630
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5631
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5632
+	 *                                                       the object's class name
5633
+	 *                                                       or object's ID
5634
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5635
+	 *                                                       exists in the database. If it does not, we add it
5636
+	 * @throws EE_Error
5637
+	 * @return EE_Base_Class
5638
+	 */
5639
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5640
+	{
5641
+		$className = $this->_get_class_name();
5642
+		if ($base_class_obj_or_id instanceof $className) {
5643
+			$model_object = $base_class_obj_or_id;
5644
+		} else {
5645
+			$primary_key_field = $this->get_primary_key_field();
5646
+			if (
5647
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5648
+				&& (
5649
+					is_int($base_class_obj_or_id)
5650
+					|| is_string($base_class_obj_or_id)
5651
+				)
5652
+			) {
5653
+				// assume it's an ID.
5654
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5655
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5656
+			} elseif (
5657
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5658
+				&& is_string($base_class_obj_or_id)
5659
+			) {
5660
+				// assume its a string representation of the object
5661
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5662
+			} else {
5663
+				throw new EE_Error(
5664
+					sprintf(
5665
+						esc_html__(
5666
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5667
+							'event_espresso'
5668
+						),
5669
+						$base_class_obj_or_id,
5670
+						$this->_get_class_name(),
5671
+						print_r($base_class_obj_or_id, true)
5672
+					)
5673
+				);
5674
+			}
5675
+		}
5676
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5677
+			$model_object->save();
5678
+		}
5679
+		return $model_object;
5680
+	}
5681
+
5682
+
5683
+
5684
+	/**
5685
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5686
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5687
+	 * returns it ID.
5688
+	 *
5689
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5690
+	 * @return int|string depending on the type of this model object's ID
5691
+	 * @throws EE_Error
5692
+	 */
5693
+	public function ensure_is_ID($base_class_obj_or_id)
5694
+	{
5695
+		$className = $this->_get_class_name();
5696
+		if ($base_class_obj_or_id instanceof $className) {
5697
+			/** @var $base_class_obj_or_id EE_Base_Class */
5698
+			$id = $base_class_obj_or_id->ID();
5699
+		} elseif (is_int($base_class_obj_or_id)) {
5700
+			// assume it's an ID
5701
+			$id = $base_class_obj_or_id;
5702
+		} elseif (is_string($base_class_obj_or_id)) {
5703
+			// assume its a string representation of the object
5704
+			$id = $base_class_obj_or_id;
5705
+		} else {
5706
+			throw new EE_Error(sprintf(
5707
+				esc_html__(
5708
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5709
+					'event_espresso'
5710
+				),
5711
+				$base_class_obj_or_id,
5712
+				$this->_get_class_name(),
5713
+				print_r($base_class_obj_or_id, true)
5714
+			));
5715
+		}
5716
+		return $id;
5717
+	}
5718
+
5719
+
5720
+
5721
+	/**
5722
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5723
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5724
+	 * been sanitized and converted into the appropriate domain.
5725
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5726
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5727
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5728
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5729
+	 * $EVT = EEM_Event::instance(); $old_setting =
5730
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5731
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5732
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5733
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5734
+	 *
5735
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5736
+	 * @return void
5737
+	 */
5738
+	public function assume_values_already_prepared_by_model_object(
5739
+		$values_already_prepared = self::not_prepared_by_model_object
5740
+	) {
5741
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5742
+	}
5743
+
5744
+
5745
+
5746
+	/**
5747
+	 * Read comments for assume_values_already_prepared_by_model_object()
5748
+	 *
5749
+	 * @return int
5750
+	 */
5751
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5752
+	{
5753
+		return $this->_values_already_prepared_by_model_object;
5754
+	}
5755
+
5756
+
5757
+
5758
+	/**
5759
+	 * Gets all the indexes on this model
5760
+	 *
5761
+	 * @return EE_Index[]
5762
+	 */
5763
+	public function indexes()
5764
+	{
5765
+		return $this->_indexes;
5766
+	}
5767
+
5768
+
5769
+
5770
+	/**
5771
+	 * Gets all the Unique Indexes on this model
5772
+	 *
5773
+	 * @return EE_Unique_Index[]
5774
+	 */
5775
+	public function unique_indexes()
5776
+	{
5777
+		$unique_indexes = array();
5778
+		foreach ($this->_indexes as $name => $index) {
5779
+			if ($index instanceof EE_Unique_Index) {
5780
+				$unique_indexes [ $name ] = $index;
5781
+			}
5782
+		}
5783
+		return $unique_indexes;
5784
+	}
5785
+
5786
+
5787
+
5788
+	/**
5789
+	 * Gets all the fields which, when combined, make the primary key.
5790
+	 * This is usually just an array with 1 element (the primary key), but in cases
5791
+	 * where there is no primary key, it's a combination of fields as defined
5792
+	 * on a primary index
5793
+	 *
5794
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5795
+	 * @throws EE_Error
5796
+	 */
5797
+	public function get_combined_primary_key_fields()
5798
+	{
5799
+		foreach ($this->indexes() as $index) {
5800
+			if ($index instanceof EE_Primary_Key_Index) {
5801
+				return $index->fields();
5802
+			}
5803
+		}
5804
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5805
+	}
5806
+
5807
+
5808
+
5809
+	/**
5810
+	 * Used to build a primary key string (when the model has no primary key),
5811
+	 * which can be used a unique string to identify this model object.
5812
+	 *
5813
+	 * @param array $fields_n_values keys are field names, values are their values.
5814
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5815
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5816
+	 *                               before passing it to this function (that will convert it from columns-n-values
5817
+	 *                               to field-names-n-values).
5818
+	 * @return string
5819
+	 * @throws EE_Error
5820
+	 */
5821
+	public function get_index_primary_key_string($fields_n_values)
5822
+	{
5823
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5824
+			$fields_n_values,
5825
+			$this->get_combined_primary_key_fields()
5826
+		);
5827
+		return http_build_query($cols_n_values_for_primary_key_index);
5828
+	}
5829
+
5830
+
5831
+
5832
+	/**
5833
+	 * Gets the field values from the primary key string
5834
+	 *
5835
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5836
+	 * @param string $index_primary_key_string
5837
+	 * @return null|array
5838
+	 * @throws EE_Error
5839
+	 */
5840
+	public function parse_index_primary_key_string($index_primary_key_string)
5841
+	{
5842
+		$key_fields = $this->get_combined_primary_key_fields();
5843
+		// check all of them are in the $id
5844
+		$key_vals_in_combined_pk = array();
5845
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5846
+		foreach ($key_fields as $key_field_name => $field_obj) {
5847
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5848
+				return null;
5849
+			}
5850
+		}
5851
+		return $key_vals_in_combined_pk;
5852
+	}
5853
+
5854
+
5855
+
5856
+	/**
5857
+	 * verifies that an array of key-value pairs for model fields has a key
5858
+	 * for each field comprising the primary key index
5859
+	 *
5860
+	 * @param array $key_vals
5861
+	 * @return boolean
5862
+	 * @throws EE_Error
5863
+	 */
5864
+	public function has_all_combined_primary_key_fields($key_vals)
5865
+	{
5866
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5867
+		foreach ($keys_it_should_have as $key) {
5868
+			if (! isset($key_vals[ $key ])) {
5869
+				return false;
5870
+			}
5871
+		}
5872
+		return true;
5873
+	}
5874
+
5875
+
5876
+
5877
+	/**
5878
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5879
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5880
+	 *
5881
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5882
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5883
+	 * @throws EE_Error
5884
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5885
+	 *                                                              indexed)
5886
+	 */
5887
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5888
+	{
5889
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5890
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5891
+		} elseif (is_array($model_object_or_attributes_array)) {
5892
+			$attributes_array = $model_object_or_attributes_array;
5893
+		} else {
5894
+			throw new EE_Error(sprintf(esc_html__(
5895
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5896
+				"event_espresso"
5897
+			), $model_object_or_attributes_array));
5898
+		}
5899
+		// even copies obviously won't have the same ID, so remove the primary key
5900
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5901
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5902
+			unset($attributes_array[ $this->primary_key_name() ]);
5903
+		}
5904
+		if (isset($query_params[0])) {
5905
+			$query_params[0] = array_merge($attributes_array, $query_params);
5906
+		} else {
5907
+			$query_params[0] = $attributes_array;
5908
+		}
5909
+		return $this->get_all($query_params);
5910
+	}
5911
+
5912
+
5913
+
5914
+	/**
5915
+	 * Gets the first copy we find. See get_all_copies for more details
5916
+	 *
5917
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5918
+	 * @param array $query_params
5919
+	 * @return EE_Base_Class
5920
+	 * @throws EE_Error
5921
+	 */
5922
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5923
+	{
5924
+		if (! is_array($query_params)) {
5925
+			EE_Error::doing_it_wrong(
5926
+				'EEM_Base::get_one_copy',
5927
+				sprintf(
5928
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5929
+					gettype($query_params)
5930
+				),
5931
+				'4.6.0'
5932
+			);
5933
+			$query_params = array();
5934
+		}
5935
+		$query_params['limit'] = 1;
5936
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5937
+		if (is_array($copies)) {
5938
+			return array_shift($copies);
5939
+		}
5940
+		return null;
5941
+	}
5942
+
5943
+
5944
+
5945
+	/**
5946
+	 * Updates the item with the specified id. Ignores default query parameters because
5947
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5948
+	 *
5949
+	 * @param array      $fields_n_values keys are field names, values are their new values
5950
+	 * @param int|string $id              the value of the primary key to update
5951
+	 * @return int number of rows updated
5952
+	 * @throws EE_Error
5953
+	 */
5954
+	public function update_by_ID($fields_n_values, $id)
5955
+	{
5956
+		$query_params = array(
5957
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5958
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5959
+		);
5960
+		return $this->update($fields_n_values, $query_params);
5961
+	}
5962
+
5963
+
5964
+
5965
+	/**
5966
+	 * Changes an operator which was supplied to the models into one usable in SQL
5967
+	 *
5968
+	 * @param string $operator_supplied
5969
+	 * @return string an operator which can be used in SQL
5970
+	 * @throws EE_Error
5971
+	 */
5972
+	private function _prepare_operator_for_sql($operator_supplied)
5973
+	{
5974
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5975
+			: null;
5976
+		if ($sql_operator) {
5977
+			return $sql_operator;
5978
+		}
5979
+		throw new EE_Error(
5980
+			sprintf(
5981
+				esc_html__(
5982
+					"The operator '%s' is not in the list of valid operators: %s",
5983
+					"event_espresso"
5984
+				),
5985
+				$operator_supplied,
5986
+				implode(",", array_keys($this->_valid_operators))
5987
+			)
5988
+		);
5989
+	}
5990
+
5991
+
5992
+
5993
+	/**
5994
+	 * Gets the valid operators
5995
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5996
+	 */
5997
+	public function valid_operators()
5998
+	{
5999
+		return $this->_valid_operators;
6000
+	}
6001
+
6002
+
6003
+
6004
+	/**
6005
+	 * Gets the between-style operators (take 2 arguments).
6006
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6007
+	 */
6008
+	public function valid_between_style_operators()
6009
+	{
6010
+		return array_intersect(
6011
+			$this->valid_operators(),
6012
+			$this->_between_style_operators
6013
+		);
6014
+	}
6015
+
6016
+	/**
6017
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6018
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6019
+	 */
6020
+	public function valid_like_style_operators()
6021
+	{
6022
+		return array_intersect(
6023
+			$this->valid_operators(),
6024
+			$this->_like_style_operators
6025
+		);
6026
+	}
6027
+
6028
+	/**
6029
+	 * Gets the "in"-style operators
6030
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6031
+	 */
6032
+	public function valid_in_style_operators()
6033
+	{
6034
+		return array_intersect(
6035
+			$this->valid_operators(),
6036
+			$this->_in_style_operators
6037
+		);
6038
+	}
6039
+
6040
+	/**
6041
+	 * Gets the "null"-style operators (accept no arguments)
6042
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6043
+	 */
6044
+	public function valid_null_style_operators()
6045
+	{
6046
+		return array_intersect(
6047
+			$this->valid_operators(),
6048
+			$this->_null_style_operators
6049
+		);
6050
+	}
6051
+
6052
+	/**
6053
+	 * Gets an array where keys are the primary keys and values are their 'names'
6054
+	 * (as determined by the model object's name() function, which is often overridden)
6055
+	 *
6056
+	 * @param array $query_params like get_all's
6057
+	 * @return string[]
6058
+	 * @throws EE_Error
6059
+	 */
6060
+	public function get_all_names($query_params = array())
6061
+	{
6062
+		$objs = $this->get_all($query_params);
6063
+		$names = array();
6064
+		foreach ($objs as $obj) {
6065
+			$names[ $obj->ID() ] = $obj->name();
6066
+		}
6067
+		return $names;
6068
+	}
6069
+
6070
+
6071
+
6072
+	/**
6073
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6074
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6075
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6076
+	 * array_keys() on $model_objects.
6077
+	 *
6078
+	 * @param \EE_Base_Class[] $model_objects
6079
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6080
+	 *                                               in the returned array
6081
+	 * @return array
6082
+	 * @throws EE_Error
6083
+	 */
6084
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6085
+	{
6086
+		if (! $this->has_primary_key_field()) {
6087
+			if (WP_DEBUG) {
6088
+				EE_Error::add_error(
6089
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6090
+					__FILE__,
6091
+					__FUNCTION__,
6092
+					__LINE__
6093
+				);
6094
+			}
6095
+		}
6096
+		$IDs = array();
6097
+		foreach ($model_objects as $model_object) {
6098
+			$id = $model_object->ID();
6099
+			if (! $id) {
6100
+				if ($filter_out_empty_ids) {
6101
+					continue;
6102
+				}
6103
+				if (WP_DEBUG) {
6104
+					EE_Error::add_error(
6105
+						esc_html__(
6106
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6107
+							'event_espresso'
6108
+						),
6109
+						__FILE__,
6110
+						__FUNCTION__,
6111
+						__LINE__
6112
+					);
6113
+				}
6114
+			}
6115
+			$IDs[] = $id;
6116
+		}
6117
+		return $IDs;
6118
+	}
6119
+
6120
+
6121
+
6122
+	/**
6123
+	 * Returns the string used in capabilities relating to this model. If there
6124
+	 * are no capabilities that relate to this model returns false
6125
+	 *
6126
+	 * @return string|false
6127
+	 */
6128
+	public function cap_slug()
6129
+	{
6130
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6131
+	}
6132
+
6133
+
6134
+
6135
+	/**
6136
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6137
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6138
+	 * only returns the cap restrictions array in that context (ie, the array
6139
+	 * at that key)
6140
+	 *
6141
+	 * @param string $context
6142
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6143
+	 * @throws EE_Error
6144
+	 */
6145
+	public function cap_restrictions($context = EEM_Base::caps_read)
6146
+	{
6147
+		EEM_Base::verify_is_valid_cap_context($context);
6148
+		// check if we ought to run the restriction generator first
6149
+		if (
6150
+			isset($this->_cap_restriction_generators[ $context ])
6151
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6152
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6153
+		) {
6154
+			$this->_cap_restrictions[ $context ] = array_merge(
6155
+				$this->_cap_restrictions[ $context ],
6156
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6157
+			);
6158
+		}
6159
+		// and make sure we've finalized the construction of each restriction
6160
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6161
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6162
+				$where_conditions_obj->_finalize_construct($this);
6163
+			}
6164
+		}
6165
+		return $this->_cap_restrictions[ $context ];
6166
+	}
6167
+
6168
+
6169
+
6170
+	/**
6171
+	 * Indicating whether or not this model thinks its a wp core model
6172
+	 *
6173
+	 * @return boolean
6174
+	 */
6175
+	public function is_wp_core_model()
6176
+	{
6177
+		return $this->_wp_core_model;
6178
+	}
6179
+
6180
+
6181
+
6182
+	/**
6183
+	 * Gets all the caps that are missing which impose a restriction on
6184
+	 * queries made in this context
6185
+	 *
6186
+	 * @param string $context one of EEM_Base::caps_ constants
6187
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6188
+	 * @throws EE_Error
6189
+	 */
6190
+	public function caps_missing($context = EEM_Base::caps_read)
6191
+	{
6192
+		$missing_caps = array();
6193
+		$cap_restrictions = $this->cap_restrictions($context);
6194
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6195
+			if (
6196
+				! EE_Capabilities::instance()
6197
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6198
+			) {
6199
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6200
+			}
6201
+		}
6202
+		return $missing_caps;
6203
+	}
6204
+
6205
+
6206
+
6207
+	/**
6208
+	 * Gets the mapping from capability contexts to action strings used in capability names
6209
+	 *
6210
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6211
+	 * one of 'read', 'edit', or 'delete'
6212
+	 */
6213
+	public function cap_contexts_to_cap_action_map()
6214
+	{
6215
+		return apply_filters(
6216
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6217
+			$this->_cap_contexts_to_cap_action_map,
6218
+			$this
6219
+		);
6220
+	}
6221
+
6222
+
6223
+
6224
+	/**
6225
+	 * Gets the action string for the specified capability context
6226
+	 *
6227
+	 * @param string $context
6228
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6229
+	 * @throws EE_Error
6230
+	 */
6231
+	public function cap_action_for_context($context)
6232
+	{
6233
+		$mapping = $this->cap_contexts_to_cap_action_map();
6234
+		if (isset($mapping[ $context ])) {
6235
+			return $mapping[ $context ];
6236
+		}
6237
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6238
+			return $action;
6239
+		}
6240
+		throw new EE_Error(
6241
+			sprintf(
6242
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6243
+				$context,
6244
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6245
+			)
6246
+		);
6247
+	}
6248
+
6249
+
6250
+
6251
+	/**
6252
+	 * Returns all the capability contexts which are valid when querying models
6253
+	 *
6254
+	 * @return array
6255
+	 */
6256
+	public static function valid_cap_contexts()
6257
+	{
6258
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6259
+			self::caps_read,
6260
+			self::caps_read_admin,
6261
+			self::caps_edit,
6262
+			self::caps_delete,
6263
+		));
6264
+	}
6265
+
6266
+
6267
+
6268
+	/**
6269
+	 * Returns all valid options for 'default_where_conditions'
6270
+	 *
6271
+	 * @return array
6272
+	 */
6273
+	public static function valid_default_where_conditions()
6274
+	{
6275
+		return array(
6276
+			EEM_Base::default_where_conditions_all,
6277
+			EEM_Base::default_where_conditions_this_only,
6278
+			EEM_Base::default_where_conditions_others_only,
6279
+			EEM_Base::default_where_conditions_minimum_all,
6280
+			EEM_Base::default_where_conditions_minimum_others,
6281
+			EEM_Base::default_where_conditions_none
6282
+		);
6283
+	}
6284
+
6285
+	// public static function default_where_conditions_full
6286
+	/**
6287
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6288
+	 *
6289
+	 * @param string $context
6290
+	 * @return bool
6291
+	 * @throws EE_Error
6292
+	 */
6293
+	public static function verify_is_valid_cap_context($context)
6294
+	{
6295
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6296
+		if (in_array($context, $valid_cap_contexts)) {
6297
+			return true;
6298
+		}
6299
+		throw new EE_Error(
6300
+			sprintf(
6301
+				esc_html__(
6302
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6303
+					'event_espresso'
6304
+				),
6305
+				$context,
6306
+				'EEM_Base',
6307
+				implode(',', $valid_cap_contexts)
6308
+			)
6309
+		);
6310
+	}
6311
+
6312
+
6313
+
6314
+	/**
6315
+	 * Clears all the models field caches. This is only useful when a sub-class
6316
+	 * might have added a field or something and these caches might be invalidated
6317
+	 */
6318
+	protected function _invalidate_field_caches()
6319
+	{
6320
+		$this->_cache_foreign_key_to_fields = array();
6321
+		$this->_cached_fields = null;
6322
+		$this->_cached_fields_non_db_only = null;
6323
+	}
6324
+
6325
+
6326
+
6327
+	/**
6328
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6329
+	 * (eg "and", "or", "not").
6330
+	 *
6331
+	 * @return array
6332
+	 */
6333
+	public function logic_query_param_keys()
6334
+	{
6335
+		return $this->_logic_query_param_keys;
6336
+	}
6337
+
6338
+
6339
+
6340
+	/**
6341
+	 * Determines whether or not the where query param array key is for a logic query param.
6342
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6343
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6344
+	 *
6345
+	 * @param $query_param_key
6346
+	 * @return bool
6347
+	 */
6348
+	public function is_logic_query_param_key($query_param_key)
6349
+	{
6350
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6351
+			if (
6352
+				$query_param_key === $logic_query_param_key
6353
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6354
+			) {
6355
+				return true;
6356
+			}
6357
+		}
6358
+		return false;
6359
+	}
6360
+
6361
+	/**
6362
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6363
+	 * @since 4.9.74.p
6364
+	 * @return boolean
6365
+	 */
6366
+	public function hasPassword()
6367
+	{
6368
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6369
+		if ($this->has_password_field === null) {
6370
+			$password_field = $this->getPasswordField();
6371
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6372
+		}
6373
+		return $this->has_password_field;
6374
+	}
6375
+
6376
+	/**
6377
+	 * Returns the password field on this model, if there is one
6378
+	 * @since 4.9.74.p
6379
+	 * @return EE_Password_Field|null
6380
+	 */
6381
+	public function getPasswordField()
6382
+	{
6383
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6384
+		// there's no need to search for it. If we don't know yet, then find out
6385
+		if ($this->has_password_field === null && $this->password_field === null) {
6386
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6387
+		}
6388
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6389
+		return $this->password_field;
6390
+	}
6391
+
6392
+
6393
+	/**
6394
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6395
+	 * @since 4.9.74.p
6396
+	 * @return EE_Model_Field_Base[]
6397
+	 * @throws EE_Error
6398
+	 */
6399
+	public function getPasswordProtectedFields()
6400
+	{
6401
+		$password_field = $this->getPasswordField();
6402
+		$fields = array();
6403
+		if ($password_field instanceof EE_Password_Field) {
6404
+			$field_names = $password_field->protectedFields();
6405
+			foreach ($field_names as $field_name) {
6406
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6407
+			}
6408
+		}
6409
+		return $fields;
6410
+	}
6411
+
6412
+
6413
+	/**
6414
+	 * Checks if the current user can perform the requested action on this model
6415
+	 * @since 4.9.74.p
6416
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6417
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6418
+	 * @return bool
6419
+	 * @throws EE_Error
6420
+	 * @throws InvalidArgumentException
6421
+	 * @throws InvalidDataTypeException
6422
+	 * @throws InvalidInterfaceException
6423
+	 * @throws ReflectionException
6424
+	 * @throws UnexpectedEntityException
6425
+	 */
6426
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6427
+	{
6428
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6429
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6430
+		}
6431
+		if (!is_array($model_obj_or_fields_n_values)) {
6432
+			throw new UnexpectedEntityException(
6433
+				$model_obj_or_fields_n_values,
6434
+				'EE_Base_Class',
6435
+				sprintf(
6436
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6437
+					__FUNCTION__
6438
+				)
6439
+			);
6440
+		}
6441
+		return $this->exists(
6442
+			$this->alter_query_params_to_restrict_by_ID(
6443
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6444
+				array(
6445
+					'default_where_conditions' => 'none',
6446
+					'caps'                     => $cap_to_check,
6447
+				)
6448
+			)
6449
+		);
6450
+	}
6451
+
6452
+	/**
6453
+	 * Returns the query param where conditions key to the password affecting this model.
6454
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6455
+	 * @since 4.9.74.p
6456
+	 * @return null|string
6457
+	 * @throws EE_Error
6458
+	 * @throws InvalidArgumentException
6459
+	 * @throws InvalidDataTypeException
6460
+	 * @throws InvalidInterfaceException
6461
+	 * @throws ModelConfigurationException
6462
+	 * @throws ReflectionException
6463
+	 */
6464
+	public function modelChainAndPassword()
6465
+	{
6466
+		if ($this->model_chain_to_password === null) {
6467
+			throw new ModelConfigurationException(
6468
+				$this,
6469
+				esc_html_x(
6470
+				// @codingStandardsIgnoreStart
6471
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6472
+					// @codingStandardsIgnoreEnd
6473
+					'1: model name',
6474
+					'event_espresso'
6475
+				)
6476
+			);
6477
+		}
6478
+		if ($this->model_chain_to_password === '') {
6479
+			$model_with_password = $this;
6480
+		} else {
6481
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6482
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6483
+			} else {
6484
+				$last_model_in_chain = $this->model_chain_to_password;
6485
+			}
6486
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6487
+		}
6488
+
6489
+		$password_field = $model_with_password->getPasswordField();
6490
+		if ($password_field instanceof EE_Password_Field) {
6491
+			$password_field_name = $password_field->get_name();
6492
+		} else {
6493
+			throw new ModelConfigurationException(
6494
+				$this,
6495
+				sprintf(
6496
+					esc_html_x(
6497
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6498
+						'1: model name, 2: special string',
6499
+						'event_espresso'
6500
+					),
6501
+					$model_with_password->get_this_model_name(),
6502
+					$this->model_chain_to_password
6503
+				)
6504
+			);
6505
+		}
6506
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6507
+	}
6508
+
6509
+	/**
6510
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6511
+	 * or if this model itself has a password affecting access to some of its other fields.
6512
+	 * @since 4.9.74.p
6513
+	 * @return boolean
6514
+	 */
6515
+	public function restrictedByRelatedModelPassword()
6516
+	{
6517
+		return $this->model_chain_to_password !== null;
6518
+	}
6519 6519
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +3347 added lines, -3347 removed lines patch added patch discarded remove patch
@@ -14,3363 +14,3363 @@
 block discarded – undo
14 14
 abstract class EE_Base_Class
15 15
 {
16 16
 
17
-    /**
18
-     * This is an array of the original properties and values provided during construction
19
-     * of this model object. (keys are model field names, values are their values).
20
-     * This list is important to remember so that when we are merging data from the db, we know
21
-     * which values to override and which to not override.
22
-     *
23
-     * @var array
24
-     */
25
-    protected $_props_n_values_provided_in_constructor;
26
-
27
-    /**
28
-     * Timezone
29
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
30
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
31
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
32
-     * access to it.
33
-     *
34
-     * @var string
35
-     */
36
-    protected $_timezone;
37
-
38
-    /**
39
-     * date format
40
-     * pattern or format for displaying dates
41
-     *
42
-     * @var string $_dt_frmt
43
-     */
44
-    protected $_dt_frmt;
45
-
46
-    /**
47
-     * time format
48
-     * pattern or format for displaying time
49
-     *
50
-     * @var string $_tm_frmt
51
-     */
52
-    protected $_tm_frmt;
53
-
54
-    /**
55
-     * This property is for holding a cached array of object properties indexed by property name as the key.
56
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
57
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
58
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
59
-     *
60
-     * @var array
61
-     */
62
-    protected $_cached_properties = array();
63
-
64
-    /**
65
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
66
-     * single
67
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
68
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
69
-     * all others have an array)
70
-     *
71
-     * @var array
72
-     */
73
-    protected $_model_relations = array();
74
-
75
-    /**
76
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
77
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
78
-     *
79
-     * @var array
80
-     */
81
-    protected $_fields = array();
82
-
83
-    /**
84
-     * @var boolean indicating whether or not this model object is intended to ever be saved
85
-     * For example, we might create model objects intended to only be used for the duration
86
-     * of this request and to be thrown away, and if they were accidentally saved
87
-     * it would be a bug.
88
-     */
89
-    protected $_allow_persist = true;
90
-
91
-    /**
92
-     * @var boolean indicating whether or not this model object's properties have changed since construction
93
-     */
94
-    protected $_has_changes = false;
95
-
96
-    /**
97
-     * @var EEM_Base
98
-     */
99
-    protected $_model;
100
-
101
-    /**
102
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
103
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
104
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
105
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
106
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
107
-     * array as:
108
-     * array(
109
-     *  'Registration_Count' => 24
110
-     * );
111
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
112
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
113
-     * info)
114
-     *
115
-     * @var array
116
-     */
117
-    protected $custom_selection_results = array();
118
-
119
-
120
-    /**
121
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
-     * play nice
123
-     *
124
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
-     *                                                         TXN_amount, QST_name, etc) and values are their values
127
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
128
-     *                                                         corresponding db model or not.
129
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
-     *                                                         be in when instantiating a EE_Base_Class object.
131
-     * @param array   $date_formats                            An array of date formats to set on construct where first
132
-     *                                                         value is the date_format and second value is the time
133
-     *                                                         format.
134
-     * @throws InvalidArgumentException
135
-     * @throws InvalidInterfaceException
136
-     * @throws InvalidDataTypeException
137
-     * @throws EE_Error
138
-     * @throws ReflectionException
139
-     */
140
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
141
-    {
142
-        $className = get_class($this);
143
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
144
-        $model = $this->get_model();
145
-        $model_fields = $model->field_settings(false);
146
-        // ensure $fieldValues is an array
147
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
148
-        // verify client code has not passed any invalid field names
149
-        foreach ($fieldValues as $field_name => $field_value) {
150
-            if (! isset($model_fields[ $field_name ])) {
151
-                throw new EE_Error(
152
-                    sprintf(
153
-                        esc_html__(
154
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
155
-                            'event_espresso'
156
-                        ),
157
-                        $field_name,
158
-                        get_class($this),
159
-                        implode(', ', array_keys($model_fields))
160
-                    )
161
-                );
162
-            }
163
-        }
164
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
165
-        if (! empty($date_formats) && is_array($date_formats)) {
166
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
167
-        } else {
168
-            // set default formats for date and time
169
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
170
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
171
-        }
172
-        // if db model is instantiating
173
-        if ($bydb) {
174
-            // client code has indicated these field values are from the database
175
-            foreach ($model_fields as $fieldName => $field) {
176
-                $this->set_from_db(
177
-                    $fieldName,
178
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
179
-                );
180
-            }
181
-        } else {
182
-            // we're constructing a brand
183
-            // new instance of the model object. Generally, this means we'll need to do more field validation
184
-            foreach ($model_fields as $fieldName => $field) {
185
-                $this->set(
186
-                    $fieldName,
187
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
188
-                    true
189
-                );
190
-            }
191
-        }
192
-        // remember what values were passed to this constructor
193
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
194
-        // remember in entity mapper
195
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
-            $model->add_to_entity_map($this);
197
-        }
198
-        // setup all the relations
199
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
202
-            } else {
203
-                $this->_model_relations[ $relation_name ] = array();
204
-            }
205
-        }
206
-        /**
207
-         * Action done at the end of each model object construction
208
-         *
209
-         * @param EE_Base_Class $this the model object just created
210
-         */
211
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
217
-     *
218
-     * @return boolean
219
-     */
220
-    public function allow_persist()
221
-    {
222
-        return $this->_allow_persist;
223
-    }
224
-
225
-
226
-    /**
227
-     * Sets whether or not this model object should be allowed to be saved to the DB.
228
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
-     * you got new information that somehow made you change your mind.
230
-     *
231
-     * @param boolean $allow_persist
232
-     * @return boolean
233
-     */
234
-    public function set_allow_persist($allow_persist)
235
-    {
236
-        return $this->_allow_persist = $allow_persist;
237
-    }
238
-
239
-
240
-    /**
241
-     * Gets the field's original value when this object was constructed during this request.
242
-     * This can be helpful when determining if a model object has changed or not
243
-     *
244
-     * @param string $field_name
245
-     * @return mixed|null
246
-     * @throws ReflectionException
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidInterfaceException
249
-     * @throws InvalidDataTypeException
250
-     * @throws EE_Error
251
-     */
252
-    public function get_original($field_name)
253
-    {
254
-        if (
255
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
257
-        ) {
258
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
-        }
260
-        return null;
261
-    }
262
-
263
-
264
-    /**
265
-     * @param EE_Base_Class $obj
266
-     * @return string
267
-     */
268
-    public function get_class($obj)
269
-    {
270
-        return get_class($obj);
271
-    }
272
-
273
-
274
-    /**
275
-     * Overrides parent because parent expects old models.
276
-     * This also doesn't do any validation, and won't work for serialized arrays
277
-     *
278
-     * @param    string $field_name
279
-     * @param    mixed  $field_value
280
-     * @param bool      $use_default
281
-     * @throws InvalidArgumentException
282
-     * @throws InvalidInterfaceException
283
-     * @throws InvalidDataTypeException
284
-     * @throws EE_Error
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     * @throws ReflectionException
288
-     */
289
-    public function set($field_name, $field_value, $use_default = false)
290
-    {
291
-        // if not using default and nothing has changed, and object has already been setup (has ID),
292
-        // then don't do anything
293
-        if (
294
-            ! $use_default
295
-            && $this->_fields[ $field_name ] === $field_value
296
-            && $this->ID()
297
-        ) {
298
-            return;
299
-        }
300
-        $model = $this->get_model();
301
-        $this->_has_changes = true;
302
-        $field_obj = $model->field_settings_for($field_name);
303
-        if ($field_obj instanceof EE_Model_Field_Base) {
304
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
305
-            if ($field_obj instanceof EE_Datetime_Field) {
306
-                $field_obj->set_timezone($this->_timezone);
307
-                $field_obj->set_date_format($this->_dt_frmt);
308
-                $field_obj->set_time_format($this->_tm_frmt);
309
-            }
310
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
311
-            // should the value be null?
312
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
313
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
314
-                /**
315
-                 * To save having to refactor all the models, if a default value is used for a
316
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
317
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
318
-                 * object.
319
-                 *
320
-                 * @since 4.6.10+
321
-                 */
322
-                if (
323
-                    $field_obj instanceof EE_Datetime_Field
324
-                    && $this->_fields[ $field_name ] !== null
325
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
326
-                ) {
327
-                    empty($this->_fields[ $field_name ])
328
-                        ? $this->set($field_name, time())
329
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
330
-                }
331
-            } else {
332
-                $this->_fields[ $field_name ] = $holder_of_value;
333
-            }
334
-            // if we're not in the constructor...
335
-            // now check if what we set was a primary key
336
-            if (
17
+	/**
18
+	 * This is an array of the original properties and values provided during construction
19
+	 * of this model object. (keys are model field names, values are their values).
20
+	 * This list is important to remember so that when we are merging data from the db, we know
21
+	 * which values to override and which to not override.
22
+	 *
23
+	 * @var array
24
+	 */
25
+	protected $_props_n_values_provided_in_constructor;
26
+
27
+	/**
28
+	 * Timezone
29
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
30
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
31
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
32
+	 * access to it.
33
+	 *
34
+	 * @var string
35
+	 */
36
+	protected $_timezone;
37
+
38
+	/**
39
+	 * date format
40
+	 * pattern or format for displaying dates
41
+	 *
42
+	 * @var string $_dt_frmt
43
+	 */
44
+	protected $_dt_frmt;
45
+
46
+	/**
47
+	 * time format
48
+	 * pattern or format for displaying time
49
+	 *
50
+	 * @var string $_tm_frmt
51
+	 */
52
+	protected $_tm_frmt;
53
+
54
+	/**
55
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
56
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
57
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
58
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
59
+	 *
60
+	 * @var array
61
+	 */
62
+	protected $_cached_properties = array();
63
+
64
+	/**
65
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
66
+	 * single
67
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
68
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
69
+	 * all others have an array)
70
+	 *
71
+	 * @var array
72
+	 */
73
+	protected $_model_relations = array();
74
+
75
+	/**
76
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
77
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
78
+	 *
79
+	 * @var array
80
+	 */
81
+	protected $_fields = array();
82
+
83
+	/**
84
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
85
+	 * For example, we might create model objects intended to only be used for the duration
86
+	 * of this request and to be thrown away, and if they were accidentally saved
87
+	 * it would be a bug.
88
+	 */
89
+	protected $_allow_persist = true;
90
+
91
+	/**
92
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
93
+	 */
94
+	protected $_has_changes = false;
95
+
96
+	/**
97
+	 * @var EEM_Base
98
+	 */
99
+	protected $_model;
100
+
101
+	/**
102
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
103
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
104
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
105
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
106
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
107
+	 * array as:
108
+	 * array(
109
+	 *  'Registration_Count' => 24
110
+	 * );
111
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
112
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
113
+	 * info)
114
+	 *
115
+	 * @var array
116
+	 */
117
+	protected $custom_selection_results = array();
118
+
119
+
120
+	/**
121
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
+	 * play nice
123
+	 *
124
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
127
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
128
+	 *                                                         corresponding db model or not.
129
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
+	 *                                                         be in when instantiating a EE_Base_Class object.
131
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
132
+	 *                                                         value is the date_format and second value is the time
133
+	 *                                                         format.
134
+	 * @throws InvalidArgumentException
135
+	 * @throws InvalidInterfaceException
136
+	 * @throws InvalidDataTypeException
137
+	 * @throws EE_Error
138
+	 * @throws ReflectionException
139
+	 */
140
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
141
+	{
142
+		$className = get_class($this);
143
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
144
+		$model = $this->get_model();
145
+		$model_fields = $model->field_settings(false);
146
+		// ensure $fieldValues is an array
147
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
148
+		// verify client code has not passed any invalid field names
149
+		foreach ($fieldValues as $field_name => $field_value) {
150
+			if (! isset($model_fields[ $field_name ])) {
151
+				throw new EE_Error(
152
+					sprintf(
153
+						esc_html__(
154
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
155
+							'event_espresso'
156
+						),
157
+						$field_name,
158
+						get_class($this),
159
+						implode(', ', array_keys($model_fields))
160
+					)
161
+				);
162
+			}
163
+		}
164
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
165
+		if (! empty($date_formats) && is_array($date_formats)) {
166
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
167
+		} else {
168
+			// set default formats for date and time
169
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
170
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
171
+		}
172
+		// if db model is instantiating
173
+		if ($bydb) {
174
+			// client code has indicated these field values are from the database
175
+			foreach ($model_fields as $fieldName => $field) {
176
+				$this->set_from_db(
177
+					$fieldName,
178
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
179
+				);
180
+			}
181
+		} else {
182
+			// we're constructing a brand
183
+			// new instance of the model object. Generally, this means we'll need to do more field validation
184
+			foreach ($model_fields as $fieldName => $field) {
185
+				$this->set(
186
+					$fieldName,
187
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
188
+					true
189
+				);
190
+			}
191
+		}
192
+		// remember what values were passed to this constructor
193
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
194
+		// remember in entity mapper
195
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
+			$model->add_to_entity_map($this);
197
+		}
198
+		// setup all the relations
199
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
+				$this->_model_relations[ $relation_name ] = null;
202
+			} else {
203
+				$this->_model_relations[ $relation_name ] = array();
204
+			}
205
+		}
206
+		/**
207
+		 * Action done at the end of each model object construction
208
+		 *
209
+		 * @param EE_Base_Class $this the model object just created
210
+		 */
211
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
217
+	 *
218
+	 * @return boolean
219
+	 */
220
+	public function allow_persist()
221
+	{
222
+		return $this->_allow_persist;
223
+	}
224
+
225
+
226
+	/**
227
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
228
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
+	 * you got new information that somehow made you change your mind.
230
+	 *
231
+	 * @param boolean $allow_persist
232
+	 * @return boolean
233
+	 */
234
+	public function set_allow_persist($allow_persist)
235
+	{
236
+		return $this->_allow_persist = $allow_persist;
237
+	}
238
+
239
+
240
+	/**
241
+	 * Gets the field's original value when this object was constructed during this request.
242
+	 * This can be helpful when determining if a model object has changed or not
243
+	 *
244
+	 * @param string $field_name
245
+	 * @return mixed|null
246
+	 * @throws ReflectionException
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws EE_Error
251
+	 */
252
+	public function get_original($field_name)
253
+	{
254
+		if (
255
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
257
+		) {
258
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
+		}
260
+		return null;
261
+	}
262
+
263
+
264
+	/**
265
+	 * @param EE_Base_Class $obj
266
+	 * @return string
267
+	 */
268
+	public function get_class($obj)
269
+	{
270
+		return get_class($obj);
271
+	}
272
+
273
+
274
+	/**
275
+	 * Overrides parent because parent expects old models.
276
+	 * This also doesn't do any validation, and won't work for serialized arrays
277
+	 *
278
+	 * @param    string $field_name
279
+	 * @param    mixed  $field_value
280
+	 * @param bool      $use_default
281
+	 * @throws InvalidArgumentException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws InvalidDataTypeException
284
+	 * @throws EE_Error
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 * @throws ReflectionException
288
+	 */
289
+	public function set($field_name, $field_value, $use_default = false)
290
+	{
291
+		// if not using default and nothing has changed, and object has already been setup (has ID),
292
+		// then don't do anything
293
+		if (
294
+			! $use_default
295
+			&& $this->_fields[ $field_name ] === $field_value
296
+			&& $this->ID()
297
+		) {
298
+			return;
299
+		}
300
+		$model = $this->get_model();
301
+		$this->_has_changes = true;
302
+		$field_obj = $model->field_settings_for($field_name);
303
+		if ($field_obj instanceof EE_Model_Field_Base) {
304
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
305
+			if ($field_obj instanceof EE_Datetime_Field) {
306
+				$field_obj->set_timezone($this->_timezone);
307
+				$field_obj->set_date_format($this->_dt_frmt);
308
+				$field_obj->set_time_format($this->_tm_frmt);
309
+			}
310
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
311
+			// should the value be null?
312
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
313
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
314
+				/**
315
+				 * To save having to refactor all the models, if a default value is used for a
316
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
317
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
318
+				 * object.
319
+				 *
320
+				 * @since 4.6.10+
321
+				 */
322
+				if (
323
+					$field_obj instanceof EE_Datetime_Field
324
+					&& $this->_fields[ $field_name ] !== null
325
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
326
+				) {
327
+					empty($this->_fields[ $field_name ])
328
+						? $this->set($field_name, time())
329
+						: $this->set($field_name, $this->_fields[ $field_name ]);
330
+				}
331
+			} else {
332
+				$this->_fields[ $field_name ] = $holder_of_value;
333
+			}
334
+			// if we're not in the constructor...
335
+			// now check if what we set was a primary key
336
+			if (
337 337
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
338
-                $this->_props_n_values_provided_in_constructor
339
-                && $field_value
340
-                && $field_name === $model->primary_key_name()
341
-            ) {
342
-                // if so, we want all this object's fields to be filled either with
343
-                // what we've explicitly set on this model
344
-                // or what we have in the db
345
-                // echo "setting primary key!";
346
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
347
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
348
-                foreach ($fields_on_model as $field_obj) {
349
-                    if (
350
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
351
-                        && $field_obj->get_name() !== $field_name
352
-                    ) {
353
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
354
-                    }
355
-                }
356
-                // oh this model object has an ID? well make sure its in the entity mapper
357
-                $model->add_to_entity_map($this);
358
-            }
359
-            // let's unset any cache for this field_name from the $_cached_properties property.
360
-            $this->_clear_cached_property($field_name);
361
-        } else {
362
-            throw new EE_Error(
363
-                sprintf(
364
-                    esc_html__(
365
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
366
-                        'event_espresso'
367
-                    ),
368
-                    $field_name
369
-                )
370
-            );
371
-        }
372
-    }
373
-
374
-
375
-    /**
376
-     * Set custom select values for model.
377
-     *
378
-     * @param array $custom_select_values
379
-     */
380
-    public function setCustomSelectsValues(array $custom_select_values)
381
-    {
382
-        $this->custom_selection_results = $custom_select_values;
383
-    }
384
-
385
-
386
-    /**
387
-     * Returns the custom select value for the provided alias if its set.
388
-     * If not set, returns null.
389
-     *
390
-     * @param string $alias
391
-     * @return string|int|float|null
392
-     */
393
-    public function getCustomSelect($alias)
394
-    {
395
-        return isset($this->custom_selection_results[ $alias ])
396
-            ? $this->custom_selection_results[ $alias ]
397
-            : null;
398
-    }
399
-
400
-
401
-    /**
402
-     * This sets the field value on the db column if it exists for the given $column_name or
403
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
404
-     *
405
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
406
-     * @param string $field_name  Must be the exact column name.
407
-     * @param mixed  $field_value The value to set.
408
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
-     * @throws InvalidArgumentException
410
-     * @throws InvalidInterfaceException
411
-     * @throws InvalidDataTypeException
412
-     * @throws EE_Error
413
-     * @throws ReflectionException
414
-     */
415
-    public function set_field_or_extra_meta($field_name, $field_value)
416
-    {
417
-        if ($this->get_model()->has_field($field_name)) {
418
-            $this->set($field_name, $field_value);
419
-            return true;
420
-        }
421
-        // ensure this object is saved first so that extra meta can be properly related.
422
-        $this->save();
423
-        return $this->update_extra_meta($field_name, $field_value);
424
-    }
425
-
426
-
427
-    /**
428
-     * This retrieves the value of the db column set on this class or if that's not present
429
-     * it will attempt to retrieve from extra_meta if found.
430
-     * Example Usage:
431
-     * Via EE_Message child class:
432
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
433
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
434
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
435
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
436
-     * value for those extra fields dynamically via the EE_message object.
437
-     *
438
-     * @param  string $field_name expecting the fully qualified field name.
439
-     * @return mixed|null  value for the field if found.  null if not found.
440
-     * @throws ReflectionException
441
-     * @throws InvalidArgumentException
442
-     * @throws InvalidInterfaceException
443
-     * @throws InvalidDataTypeException
444
-     * @throws EE_Error
445
-     */
446
-    public function get_field_or_extra_meta($field_name)
447
-    {
448
-        if ($this->get_model()->has_field($field_name)) {
449
-            $column_value = $this->get($field_name);
450
-        } else {
451
-            // This isn't a column in the main table, let's see if it is in the extra meta.
452
-            $column_value = $this->get_extra_meta($field_name, true, null);
453
-        }
454
-        return $column_value;
455
-    }
456
-
457
-
458
-    /**
459
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
460
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
461
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
462
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
463
-     *
464
-     * @access public
465
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
466
-     * @return void
467
-     * @throws InvalidArgumentException
468
-     * @throws InvalidInterfaceException
469
-     * @throws InvalidDataTypeException
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     */
473
-    public function set_timezone($timezone = '')
474
-    {
475
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
476
-        // make sure we clear all cached properties because they won't be relevant now
477
-        $this->_clear_cached_properties();
478
-        // make sure we update field settings and the date for all EE_Datetime_Fields
479
-        $model_fields = $this->get_model()->field_settings(false);
480
-        foreach ($model_fields as $field_name => $field_obj) {
481
-            if ($field_obj instanceof EE_Datetime_Field) {
482
-                $field_obj->set_timezone($this->_timezone);
483
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
484
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
485
-                }
486
-            }
487
-        }
488
-    }
489
-
490
-
491
-    /**
492
-     * This just returns whatever is set for the current timezone.
493
-     *
494
-     * @access public
495
-     * @return string timezone string
496
-     */
497
-    public function get_timezone()
498
-    {
499
-        return $this->_timezone;
500
-    }
501
-
502
-
503
-    /**
504
-     * This sets the internal date format to what is sent in to be used as the new default for the class
505
-     * internally instead of wp set date format options
506
-     *
507
-     * @since 4.6
508
-     * @param string $format should be a format recognizable by PHP date() functions.
509
-     */
510
-    public function set_date_format($format)
511
-    {
512
-        $this->_dt_frmt = $format;
513
-        // clear cached_properties because they won't be relevant now.
514
-        $this->_clear_cached_properties();
515
-    }
516
-
517
-
518
-    /**
519
-     * This sets the internal time format string to what is sent in to be used as the new default for the
520
-     * class internally instead of wp set time format options.
521
-     *
522
-     * @since 4.6
523
-     * @param string $format should be a format recognizable by PHP date() functions.
524
-     */
525
-    public function set_time_format($format)
526
-    {
527
-        $this->_tm_frmt = $format;
528
-        // clear cached_properties because they won't be relevant now.
529
-        $this->_clear_cached_properties();
530
-    }
531
-
532
-
533
-    /**
534
-     * This returns the current internal set format for the date and time formats.
535
-     *
536
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
537
-     *                             where the first value is the date format and the second value is the time format.
538
-     * @return mixed string|array
539
-     */
540
-    public function get_format($full = true)
541
-    {
542
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
543
-    }
544
-
545
-
546
-    /**
547
-     * cache
548
-     * stores the passed model object on the current model object.
549
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
550
-     *
551
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
552
-     *                                       'Registration' associated with this model object
553
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
554
-     *                                       that could be a payment or a registration)
555
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
556
-     *                                       items which will be stored in an array on this object
557
-     * @throws ReflectionException
558
-     * @throws InvalidArgumentException
559
-     * @throws InvalidInterfaceException
560
-     * @throws InvalidDataTypeException
561
-     * @throws EE_Error
562
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
563
-     *                                       related thing, no array)
564
-     */
565
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
566
-    {
567
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
568
-        if (! $object_to_cache instanceof EE_Base_Class) {
569
-            return false;
570
-        }
571
-        // also get "how" the object is related, or throw an error
572
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
573
-            throw new EE_Error(
574
-                sprintf(
575
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
576
-                    $relationName,
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        // how many things are related ?
582
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
583
-            // if it's a "belongs to" relationship, then there's only one related model object
584
-            // eg, if this is a registration, there's only 1 attendee for it
585
-            // so for these model objects just set it to be cached
586
-            $this->_model_relations[ $relationName ] = $object_to_cache;
587
-            $return = true;
588
-        } else {
589
-            // otherwise, this is the "many" side of a one to many relationship,
590
-            // so we'll add the object to the array of related objects for that type.
591
-            // eg: if this is an event, there are many registrations for that event,
592
-            // so we cache the registrations in an array
593
-            if (! is_array($this->_model_relations[ $relationName ])) {
594
-                // if for some reason, the cached item is a model object,
595
-                // then stick that in the array, otherwise start with an empty array
596
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
597
-                                                           instanceof
598
-                                                           EE_Base_Class
599
-                    ? array($this->_model_relations[ $relationName ]) : array();
600
-            }
601
-            // first check for a cache_id which is normally empty
602
-            if (! empty($cache_id)) {
603
-                // if the cache_id exists, then it means we are purposely trying to cache this
604
-                // with a known key that can then be used to retrieve the object later on
605
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
606
-                $return = $cache_id;
607
-            } elseif ($object_to_cache->ID()) {
608
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
609
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
610
-                $return = $object_to_cache->ID();
611
-            } else {
612
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
613
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
614
-                // move the internal pointer to the end of the array
615
-                end($this->_model_relations[ $relationName ]);
616
-                // and grab the key so that we can return it
617
-                $return = key($this->_model_relations[ $relationName ]);
618
-            }
619
-        }
620
-        return $return;
621
-    }
622
-
623
-
624
-    /**
625
-     * For adding an item to the cached_properties property.
626
-     *
627
-     * @access protected
628
-     * @param string      $fieldname the property item the corresponding value is for.
629
-     * @param mixed       $value     The value we are caching.
630
-     * @param string|null $cache_type
631
-     * @return void
632
-     * @throws ReflectionException
633
-     * @throws InvalidArgumentException
634
-     * @throws InvalidInterfaceException
635
-     * @throws InvalidDataTypeException
636
-     * @throws EE_Error
637
-     */
638
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
639
-    {
640
-        // first make sure this property exists
641
-        $this->get_model()->field_settings_for($fieldname);
642
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
643
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
644
-    }
645
-
646
-
647
-    /**
648
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
649
-     * This also SETS the cache if we return the actual property!
650
-     *
651
-     * @param string $fieldname        the name of the property we're trying to retrieve
652
-     * @param bool   $pretty
653
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
654
-     *                                 (in cases where the same property may be used for different outputs
655
-     *                                 - i.e. datetime, money etc.)
656
-     *                                 It can also accept certain pre-defined "schema" strings
657
-     *                                 to define how to output the property.
658
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
659
-     * @return mixed                   whatever the value for the property is we're retrieving
660
-     * @throws ReflectionException
661
-     * @throws InvalidArgumentException
662
-     * @throws InvalidInterfaceException
663
-     * @throws InvalidDataTypeException
664
-     * @throws EE_Error
665
-     */
666
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
667
-    {
668
-        // verify the field exists
669
-        $model = $this->get_model();
670
-        $model->field_settings_for($fieldname);
671
-        $cache_type = $pretty ? 'pretty' : 'standard';
672
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
673
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
674
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
675
-        }
676
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
677
-        $this->_set_cached_property($fieldname, $value, $cache_type);
678
-        return $value;
679
-    }
680
-
681
-
682
-    /**
683
-     * If the cache didn't fetch the needed item, this fetches it.
684
-     *
685
-     * @param string $fieldname
686
-     * @param bool   $pretty
687
-     * @param string $extra_cache_ref
688
-     * @return mixed
689
-     * @throws InvalidArgumentException
690
-     * @throws InvalidInterfaceException
691
-     * @throws InvalidDataTypeException
692
-     * @throws EE_Error
693
-     * @throws ReflectionException
694
-     */
695
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
696
-    {
697
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
698
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
699
-        if ($field_obj instanceof EE_Datetime_Field) {
700
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
701
-        }
702
-        if (! isset($this->_fields[ $fieldname ])) {
703
-            $this->_fields[ $fieldname ] = null;
704
-        }
705
-        $value = $pretty
706
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
707
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
708
-        return $value;
709
-    }
710
-
711
-
712
-    /**
713
-     * set timezone, formats, and output for EE_Datetime_Field objects
714
-     *
715
-     * @param \EE_Datetime_Field $datetime_field
716
-     * @param bool               $pretty
717
-     * @param null               $date_or_time
718
-     * @return void
719
-     * @throws InvalidArgumentException
720
-     * @throws InvalidInterfaceException
721
-     * @throws InvalidDataTypeException
722
-     * @throws EE_Error
723
-     */
724
-    protected function _prepare_datetime_field(
725
-        EE_Datetime_Field $datetime_field,
726
-        $pretty = false,
727
-        $date_or_time = null
728
-    ) {
729
-        $datetime_field->set_timezone($this->_timezone);
730
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
731
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
732
-        // set the output returned
733
-        switch ($date_or_time) {
734
-            case 'D':
735
-                $datetime_field->set_date_time_output('date');
736
-                break;
737
-            case 'T':
738
-                $datetime_field->set_date_time_output('time');
739
-                break;
740
-            default:
741
-                $datetime_field->set_date_time_output();
742
-        }
743
-    }
744
-
745
-
746
-    /**
747
-     * This just takes care of clearing out the cached_properties
748
-     *
749
-     * @return void
750
-     */
751
-    protected function _clear_cached_properties()
752
-    {
753
-        $this->_cached_properties = array();
754
-    }
755
-
756
-
757
-    /**
758
-     * This just clears out ONE property if it exists in the cache
759
-     *
760
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
761
-     * @return void
762
-     */
763
-    protected function _clear_cached_property($property_name)
764
-    {
765
-        if (isset($this->_cached_properties[ $property_name ])) {
766
-            unset($this->_cached_properties[ $property_name ]);
767
-        }
768
-    }
769
-
770
-
771
-    /**
772
-     * Ensures that this related thing is a model object.
773
-     *
774
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
775
-     * @param string $model_name   name of the related thing, eg 'Attendee',
776
-     * @return EE_Base_Class
777
-     * @throws ReflectionException
778
-     * @throws InvalidArgumentException
779
-     * @throws InvalidInterfaceException
780
-     * @throws InvalidDataTypeException
781
-     * @throws EE_Error
782
-     */
783
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
784
-    {
785
-        $other_model_instance = self::_get_model_instance_with_name(
786
-            self::_get_model_classname($model_name),
787
-            $this->_timezone
788
-        );
789
-        return $other_model_instance->ensure_is_obj($object_or_id);
790
-    }
791
-
792
-
793
-    /**
794
-     * Forgets the cached model of the given relation Name. So the next time we request it,
795
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
796
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
797
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
798
-     *
799
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
800
-     *                                                     Eg 'Registration'
801
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
802
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
803
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
804
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
805
-     *                                                     this is HasMany or HABTM.
806
-     * @throws ReflectionException
807
-     * @throws InvalidArgumentException
808
-     * @throws InvalidInterfaceException
809
-     * @throws InvalidDataTypeException
810
-     * @throws EE_Error
811
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
812
-     *                                                     relation from all
813
-     */
814
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
815
-    {
816
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
817
-        $index_in_cache = '';
818
-        if (! $relationship_to_model) {
819
-            throw new EE_Error(
820
-                sprintf(
821
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
822
-                    $relationName,
823
-                    get_class($this)
824
-                )
825
-            );
826
-        }
827
-        if ($clear_all) {
828
-            $obj_removed = true;
829
-            $this->_model_relations[ $relationName ] = null;
830
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
831
-            $obj_removed = $this->_model_relations[ $relationName ];
832
-            $this->_model_relations[ $relationName ] = null;
833
-        } else {
834
-            if (
835
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
836
-                && $object_to_remove_or_index_into_array->ID()
837
-            ) {
838
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
839
-                if (
840
-                    is_array($this->_model_relations[ $relationName ])
841
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
842
-                ) {
843
-                    $index_found_at = null;
844
-                    // find this object in the array even though it has a different key
845
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
846
-                        /** @noinspection TypeUnsafeComparisonInspection */
847
-                        if (
848
-                            $obj instanceof EE_Base_Class
849
-                            && (
850
-                                $obj == $object_to_remove_or_index_into_array
851
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
852
-                            )
853
-                        ) {
854
-                            $index_found_at = $index;
855
-                            break;
856
-                        }
857
-                    }
858
-                    if ($index_found_at) {
859
-                        $index_in_cache = $index_found_at;
860
-                    } else {
861
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
862
-                        // if it wasn't in it to begin with. So we're done
863
-                        return $object_to_remove_or_index_into_array;
864
-                    }
865
-                }
866
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
867
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
868
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
869
-                    /** @noinspection TypeUnsafeComparisonInspection */
870
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
871
-                        $index_in_cache = $index;
872
-                    }
873
-                }
874
-            } else {
875
-                $index_in_cache = $object_to_remove_or_index_into_array;
876
-            }
877
-            // supposedly we've found it. But it could just be that the client code
878
-            // provided a bad index/object
879
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
880
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
881
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
882
-            } else {
883
-                // that thing was never cached anyways.
884
-                $obj_removed = null;
885
-            }
886
-        }
887
-        return $obj_removed;
888
-    }
889
-
890
-
891
-    /**
892
-     * update_cache_after_object_save
893
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
894
-     * obtained after being saved to the db
895
-     *
896
-     * @param string        $relationName       - the type of object that is cached
897
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
898
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
899
-     * @return boolean TRUE on success, FALSE on fail
900
-     * @throws ReflectionException
901
-     * @throws InvalidArgumentException
902
-     * @throws InvalidInterfaceException
903
-     * @throws InvalidDataTypeException
904
-     * @throws EE_Error
905
-     */
906
-    public function update_cache_after_object_save(
907
-        $relationName,
908
-        EE_Base_Class $newly_saved_object,
909
-        $current_cache_id = ''
910
-    ) {
911
-        // verify that incoming object is of the correct type
912
-        $obj_class = 'EE_' . $relationName;
913
-        if ($newly_saved_object instanceof $obj_class) {
914
-            /* @type EE_Base_Class $newly_saved_object */
915
-            // now get the type of relation
916
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
917
-            // if this is a 1:1 relationship
918
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
919
-                // then just replace the cached object with the newly saved object
920
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
921
-                return true;
922
-                // or if it's some kind of sordid feral polyamorous relationship...
923
-            }
924
-            if (
925
-                is_array($this->_model_relations[ $relationName ])
926
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
927
-            ) {
928
-                // then remove the current cached item
929
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
930
-                // and cache the newly saved object using it's new ID
931
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
932
-                return true;
933
-            }
934
-        }
935
-        return false;
936
-    }
937
-
938
-
939
-    /**
940
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
941
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
942
-     *
943
-     * @param string $relationName
944
-     * @return EE_Base_Class
945
-     */
946
-    public function get_one_from_cache($relationName)
947
-    {
948
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
949
-            ? $this->_model_relations[ $relationName ]
950
-            : null;
951
-        if (is_array($cached_array_or_object)) {
952
-            return array_shift($cached_array_or_object);
953
-        }
954
-        return $cached_array_or_object;
955
-    }
956
-
957
-
958
-    /**
959
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
960
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
961
-     *
962
-     * @param string $relationName
963
-     * @throws ReflectionException
964
-     * @throws InvalidArgumentException
965
-     * @throws InvalidInterfaceException
966
-     * @throws InvalidDataTypeException
967
-     * @throws EE_Error
968
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
969
-     */
970
-    public function get_all_from_cache($relationName)
971
-    {
972
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
973
-        // if the result is not an array, but exists, make it an array
974
-        $objects = is_array($objects) ? $objects : array($objects);
975
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
976
-        // basically, if this model object was stored in the session, and these cached model objects
977
-        // already have IDs, let's make sure they're in their model's entity mapper
978
-        // otherwise we will have duplicates next time we call
979
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
980
-        $model = EE_Registry::instance()->load_model($relationName);
981
-        foreach ($objects as $model_object) {
982
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
983
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
984
-                if ($model_object->ID()) {
985
-                    $model->add_to_entity_map($model_object);
986
-                }
987
-            } else {
988
-                throw new EE_Error(
989
-                    sprintf(
990
-                        esc_html__(
991
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
992
-                            'event_espresso'
993
-                        ),
994
-                        $relationName,
995
-                        gettype($model_object)
996
-                    )
997
-                );
998
-            }
999
-        }
1000
-        return $objects;
1001
-    }
1002
-
1003
-
1004
-    /**
1005
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1006
-     * matching the given query conditions.
1007
-     *
1008
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1009
-     * @param int   $limit              How many objects to return.
1010
-     * @param array $query_params       Any additional conditions on the query.
1011
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1012
-     *                                  you can indicate just the columns you want returned
1013
-     * @return array|EE_Base_Class[]
1014
-     * @throws ReflectionException
1015
-     * @throws InvalidArgumentException
1016
-     * @throws InvalidInterfaceException
1017
-     * @throws InvalidDataTypeException
1018
-     * @throws EE_Error
1019
-     */
1020
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1021
-    {
1022
-        $model = $this->get_model();
1023
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1024
-            ? $model->get_primary_key_field()->get_name()
1025
-            : $field_to_order_by;
1026
-        $current_value = ! empty($field) ? $this->get($field) : null;
1027
-        if (empty($field) || empty($current_value)) {
1028
-            return array();
1029
-        }
1030
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1031
-    }
1032
-
1033
-
1034
-    /**
1035
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1036
-     * matching the given query conditions.
1037
-     *
1038
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1039
-     * @param int   $limit              How many objects to return.
1040
-     * @param array $query_params       Any additional conditions on the query.
1041
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1042
-     *                                  you can indicate just the columns you want returned
1043
-     * @return array|EE_Base_Class[]
1044
-     * @throws ReflectionException
1045
-     * @throws InvalidArgumentException
1046
-     * @throws InvalidInterfaceException
1047
-     * @throws InvalidDataTypeException
1048
-     * @throws EE_Error
1049
-     */
1050
-    public function previous_x(
1051
-        $field_to_order_by = null,
1052
-        $limit = 1,
1053
-        $query_params = array(),
1054
-        $columns_to_select = null
1055
-    ) {
1056
-        $model = $this->get_model();
1057
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1058
-            ? $model->get_primary_key_field()->get_name()
1059
-            : $field_to_order_by;
1060
-        $current_value = ! empty($field) ? $this->get($field) : null;
1061
-        if (empty($field) || empty($current_value)) {
1062
-            return array();
1063
-        }
1064
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1070
-     * matching the given query conditions.
1071
-     *
1072
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1073
-     * @param array $query_params       Any additional conditions on the query.
1074
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1075
-     *                                  you can indicate just the columns you want returned
1076
-     * @return array|EE_Base_Class
1077
-     * @throws ReflectionException
1078
-     * @throws InvalidArgumentException
1079
-     * @throws InvalidInterfaceException
1080
-     * @throws InvalidDataTypeException
1081
-     * @throws EE_Error
1082
-     */
1083
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1084
-    {
1085
-        $model = $this->get_model();
1086
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1087
-            ? $model->get_primary_key_field()->get_name()
1088
-            : $field_to_order_by;
1089
-        $current_value = ! empty($field) ? $this->get($field) : null;
1090
-        if (empty($field) || empty($current_value)) {
1091
-            return array();
1092
-        }
1093
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1094
-    }
1095
-
1096
-
1097
-    /**
1098
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1099
-     * matching the given query conditions.
1100
-     *
1101
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1102
-     * @param array $query_params       Any additional conditions on the query.
1103
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1104
-     *                                  you can indicate just the column you want returned
1105
-     * @return array|EE_Base_Class
1106
-     * @throws ReflectionException
1107
-     * @throws InvalidArgumentException
1108
-     * @throws InvalidInterfaceException
1109
-     * @throws InvalidDataTypeException
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1113
-    {
1114
-        $model = $this->get_model();
1115
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1116
-            ? $model->get_primary_key_field()->get_name()
1117
-            : $field_to_order_by;
1118
-        $current_value = ! empty($field) ? $this->get($field) : null;
1119
-        if (empty($field) || empty($current_value)) {
1120
-            return array();
1121
-        }
1122
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * Overrides parent because parent expects old models.
1128
-     * This also doesn't do any validation, and won't work for serialized arrays
1129
-     *
1130
-     * @param string $field_name
1131
-     * @param mixed  $field_value_from_db
1132
-     * @throws ReflectionException
1133
-     * @throws InvalidArgumentException
1134
-     * @throws InvalidInterfaceException
1135
-     * @throws InvalidDataTypeException
1136
-     * @throws EE_Error
1137
-     */
1138
-    public function set_from_db($field_name, $field_value_from_db)
1139
-    {
1140
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1141
-        if ($field_obj instanceof EE_Model_Field_Base) {
1142
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1143
-            // eg, a CPT model object could have an entry in the posts table, but no
1144
-            // entry in the meta table. Meaning that all its columns in the meta table
1145
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1146
-            if ($field_value_from_db === null) {
1147
-                if ($field_obj->is_nullable()) {
1148
-                    // if the field allows nulls, then let it be null
1149
-                    $field_value = null;
1150
-                } else {
1151
-                    $field_value = $field_obj->get_default_value();
1152
-                }
1153
-            } else {
1154
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1155
-            }
1156
-            $this->_fields[ $field_name ] = $field_value;
1157
-            $this->_clear_cached_property($field_name);
1158
-        }
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * verifies that the specified field is of the correct type
1164
-     *
1165
-     * @param string $field_name
1166
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
-     *                                (in cases where the same property may be used for different outputs
1168
-     *                                - i.e. datetime, money etc.)
1169
-     * @return mixed
1170
-     * @throws ReflectionException
1171
-     * @throws InvalidArgumentException
1172
-     * @throws InvalidInterfaceException
1173
-     * @throws InvalidDataTypeException
1174
-     * @throws EE_Error
1175
-     */
1176
-    public function get($field_name, $extra_cache_ref = null)
1177
-    {
1178
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1179
-    }
1180
-
1181
-
1182
-    /**
1183
-     * This method simply returns the RAW unprocessed value for the given property in this class
1184
-     *
1185
-     * @param  string $field_name A valid fieldname
1186
-     * @return mixed              Whatever the raw value stored on the property is.
1187
-     * @throws ReflectionException
1188
-     * @throws InvalidArgumentException
1189
-     * @throws InvalidInterfaceException
1190
-     * @throws InvalidDataTypeException
1191
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1192
-     */
1193
-    public function get_raw($field_name)
1194
-    {
1195
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1196
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1197
-            ? $this->_fields[ $field_name ]->format('U')
1198
-            : $this->_fields[ $field_name ];
1199
-    }
1200
-
1201
-
1202
-    /**
1203
-     * This is used to return the internal DateTime object used for a field that is a
1204
-     * EE_Datetime_Field.
1205
-     *
1206
-     * @param string $field_name               The field name retrieving the DateTime object.
1207
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1208
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1209
-     *                                         EE_Datetime_Field and but the field value is null, then
1210
-     *                                         just null is returned (because that indicates that likely
1211
-     *                                         this field is nullable).
1212
-     * @throws InvalidArgumentException
1213
-     * @throws InvalidDataTypeException
1214
-     * @throws InvalidInterfaceException
1215
-     * @throws ReflectionException
1216
-     */
1217
-    public function get_DateTime_object($field_name)
1218
-    {
1219
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1220
-        if (! $field_settings instanceof EE_Datetime_Field) {
1221
-            EE_Error::add_error(
1222
-                sprintf(
1223
-                    esc_html__(
1224
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1225
-                        'event_espresso'
1226
-                    ),
1227
-                    $field_name
1228
-                ),
1229
-                __FILE__,
1230
-                __FUNCTION__,
1231
-                __LINE__
1232
-            );
1233
-            return false;
1234
-        }
1235
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1236
-            ? clone $this->_fields[ $field_name ]
1237
-            : null;
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     * To be used in template to immediately echo out the value, and format it for output.
1243
-     * Eg, should call stripslashes and whatnot before echoing
1244
-     *
1245
-     * @param string $field_name      the name of the field as it appears in the DB
1246
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1247
-     *                                (in cases where the same property may be used for different outputs
1248
-     *                                - i.e. datetime, money etc.)
1249
-     * @return void
1250
-     * @throws ReflectionException
1251
-     * @throws InvalidArgumentException
1252
-     * @throws InvalidInterfaceException
1253
-     * @throws InvalidDataTypeException
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function e($field_name, $extra_cache_ref = null)
1257
-    {
1258
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1264
-     * can be easily used as the value of form input.
1265
-     *
1266
-     * @param string $field_name
1267
-     * @return void
1268
-     * @throws ReflectionException
1269
-     * @throws InvalidArgumentException
1270
-     * @throws InvalidInterfaceException
1271
-     * @throws InvalidDataTypeException
1272
-     * @throws EE_Error
1273
-     */
1274
-    public function f($field_name)
1275
-    {
1276
-        $this->e($field_name, 'form_input');
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * Same as `f()` but just returns the value instead of echoing it
1282
-     *
1283
-     * @param string $field_name
1284
-     * @return string
1285
-     * @throws ReflectionException
1286
-     * @throws InvalidArgumentException
1287
-     * @throws InvalidInterfaceException
1288
-     * @throws InvalidDataTypeException
1289
-     * @throws EE_Error
1290
-     */
1291
-    public function get_f($field_name)
1292
-    {
1293
-        return (string) $this->get_pretty($field_name, 'form_input');
1294
-    }
1295
-
1296
-
1297
-    /**
1298
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1299
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1300
-     * to see what options are available.
1301
-     *
1302
-     * @param string $field_name
1303
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1304
-     *                                (in cases where the same property may be used for different outputs
1305
-     *                                - i.e. datetime, money etc.)
1306
-     * @return mixed
1307
-     * @throws ReflectionException
1308
-     * @throws InvalidArgumentException
1309
-     * @throws InvalidInterfaceException
1310
-     * @throws InvalidDataTypeException
1311
-     * @throws EE_Error
1312
-     */
1313
-    public function get_pretty($field_name, $extra_cache_ref = null)
1314
-    {
1315
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1316
-    }
1317
-
1318
-
1319
-    /**
1320
-     * This simply returns the datetime for the given field name
1321
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1322
-     * (and the equivalent e_date, e_time, e_datetime).
1323
-     *
1324
-     * @access   protected
1325
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1326
-     * @param string   $dt_frmt      valid datetime format used for date
1327
-     *                               (if '' then we just use the default on the field,
1328
-     *                               if NULL we use the last-used format)
1329
-     * @param string   $tm_frmt      Same as above except this is for time format
1330
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1331
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1332
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1333
-     *                               if field is not a valid dtt field, or void if echoing
1334
-     * @throws ReflectionException
1335
-     * @throws InvalidArgumentException
1336
-     * @throws InvalidInterfaceException
1337
-     * @throws InvalidDataTypeException
1338
-     * @throws EE_Error
1339
-     */
1340
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1341
-    {
1342
-        // clear cached property
1343
-        $this->_clear_cached_property($field_name);
1344
-        // reset format properties because they are used in get()
1345
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1346
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1347
-        if ($echo) {
1348
-            $this->e($field_name, $date_or_time);
1349
-            return '';
1350
-        }
1351
-        return $this->get($field_name, $date_or_time);
1352
-    }
1353
-
1354
-
1355
-    /**
1356
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1357
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1358
-     * other echoes the pretty value for dtt)
1359
-     *
1360
-     * @param  string $field_name name of model object datetime field holding the value
1361
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1362
-     * @return string            datetime value formatted
1363
-     * @throws ReflectionException
1364
-     * @throws InvalidArgumentException
1365
-     * @throws InvalidInterfaceException
1366
-     * @throws InvalidDataTypeException
1367
-     * @throws EE_Error
1368
-     */
1369
-    public function get_date($field_name, $format = '')
1370
-    {
1371
-        return $this->_get_datetime($field_name, $format, null, 'D');
1372
-    }
1373
-
1374
-
1375
-    /**
1376
-     * @param        $field_name
1377
-     * @param string $format
1378
-     * @throws ReflectionException
1379
-     * @throws InvalidArgumentException
1380
-     * @throws InvalidInterfaceException
1381
-     * @throws InvalidDataTypeException
1382
-     * @throws EE_Error
1383
-     */
1384
-    public function e_date($field_name, $format = '')
1385
-    {
1386
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1387
-    }
1388
-
1389
-
1390
-    /**
1391
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1392
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1393
-     * other echoes the pretty value for dtt)
1394
-     *
1395
-     * @param  string $field_name name of model object datetime field holding the value
1396
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1397
-     * @return string             datetime value formatted
1398
-     * @throws ReflectionException
1399
-     * @throws InvalidArgumentException
1400
-     * @throws InvalidInterfaceException
1401
-     * @throws InvalidDataTypeException
1402
-     * @throws EE_Error
1403
-     */
1404
-    public function get_time($field_name, $format = '')
1405
-    {
1406
-        return $this->_get_datetime($field_name, null, $format, 'T');
1407
-    }
1408
-
1409
-
1410
-    /**
1411
-     * @param        $field_name
1412
-     * @param string $format
1413
-     * @throws ReflectionException
1414
-     * @throws InvalidArgumentException
1415
-     * @throws InvalidInterfaceException
1416
-     * @throws InvalidDataTypeException
1417
-     * @throws EE_Error
1418
-     */
1419
-    public function e_time($field_name, $format = '')
1420
-    {
1421
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1422
-    }
1423
-
1424
-
1425
-    /**
1426
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1427
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1428
-     * other echoes the pretty value for dtt)
1429
-     *
1430
-     * @param  string $field_name name of model object datetime field holding the value
1431
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1432
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1433
-     * @return string             datetime value formatted
1434
-     * @throws ReflectionException
1435
-     * @throws InvalidArgumentException
1436
-     * @throws InvalidInterfaceException
1437
-     * @throws InvalidDataTypeException
1438
-     * @throws EE_Error
1439
-     */
1440
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1441
-    {
1442
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1443
-    }
1444
-
1445
-
1446
-    /**
1447
-     * @param string $field_name
1448
-     * @param string $dt_frmt
1449
-     * @param string $tm_frmt
1450
-     * @throws ReflectionException
1451
-     * @throws InvalidArgumentException
1452
-     * @throws InvalidInterfaceException
1453
-     * @throws InvalidDataTypeException
1454
-     * @throws EE_Error
1455
-     */
1456
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1457
-    {
1458
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1459
-    }
1460
-
1461
-
1462
-    /**
1463
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1464
-     *
1465
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1466
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1467
-     *                           on the object will be used.
1468
-     * @return string Date and time string in set locale or false if no field exists for the given
1469
-     * @throws ReflectionException
1470
-     * @throws InvalidArgumentException
1471
-     * @throws InvalidInterfaceException
1472
-     * @throws InvalidDataTypeException
1473
-     * @throws EE_Error
1474
-     *                           field name.
1475
-     */
1476
-    public function get_i18n_datetime($field_name, $format = '')
1477
-    {
1478
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1479
-        return date_i18n(
1480
-            $format,
1481
-            EEH_DTT_Helper::get_timestamp_with_offset(
1482
-                $this->get_raw($field_name),
1483
-                $this->_timezone
1484
-            )
1485
-        );
1486
-    }
1487
-
1488
-
1489
-    /**
1490
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1491
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1492
-     * thrown.
1493
-     *
1494
-     * @param  string $field_name The field name being checked
1495
-     * @throws ReflectionException
1496
-     * @throws InvalidArgumentException
1497
-     * @throws InvalidInterfaceException
1498
-     * @throws InvalidDataTypeException
1499
-     * @throws EE_Error
1500
-     * @return EE_Datetime_Field
1501
-     */
1502
-    protected function _get_dtt_field_settings($field_name)
1503
-    {
1504
-        $field = $this->get_model()->field_settings_for($field_name);
1505
-        // check if field is dtt
1506
-        if ($field instanceof EE_Datetime_Field) {
1507
-            return $field;
1508
-        }
1509
-        throw new EE_Error(
1510
-            sprintf(
1511
-                esc_html__(
1512
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1513
-                    'event_espresso'
1514
-                ),
1515
-                $field_name,
1516
-                self::_get_model_classname(get_class($this))
1517
-            )
1518
-        );
1519
-    }
1520
-
1521
-
1522
-
1523
-
1524
-    /**
1525
-     * NOTE ABOUT BELOW:
1526
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1527
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1528
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1529
-     * method and make sure you send the entire datetime value for setting.
1530
-     */
1531
-    /**
1532
-     * sets the time on a datetime property
1533
-     *
1534
-     * @access protected
1535
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1536
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1537
-     * @throws ReflectionException
1538
-     * @throws InvalidArgumentException
1539
-     * @throws InvalidInterfaceException
1540
-     * @throws InvalidDataTypeException
1541
-     * @throws EE_Error
1542
-     */
1543
-    protected function _set_time_for($time, $fieldname)
1544
-    {
1545
-        $this->_set_date_time('T', $time, $fieldname);
1546
-    }
1547
-
1548
-
1549
-    /**
1550
-     * sets the date on a datetime property
1551
-     *
1552
-     * @access protected
1553
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1554
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1555
-     * @throws ReflectionException
1556
-     * @throws InvalidArgumentException
1557
-     * @throws InvalidInterfaceException
1558
-     * @throws InvalidDataTypeException
1559
-     * @throws EE_Error
1560
-     */
1561
-    protected function _set_date_for($date, $fieldname)
1562
-    {
1563
-        $this->_set_date_time('D', $date, $fieldname);
1564
-    }
1565
-
1566
-
1567
-    /**
1568
-     * This takes care of setting a date or time independently on a given model object property. This method also
1569
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1570
-     *
1571
-     * @access protected
1572
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1573
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1574
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1575
-     *                                        EE_Datetime_Field property)
1576
-     * @throws ReflectionException
1577
-     * @throws InvalidArgumentException
1578
-     * @throws InvalidInterfaceException
1579
-     * @throws InvalidDataTypeException
1580
-     * @throws EE_Error
1581
-     */
1582
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1583
-    {
1584
-        $field = $this->_get_dtt_field_settings($fieldname);
1585
-        $field->set_timezone($this->_timezone);
1586
-        $field->set_date_format($this->_dt_frmt);
1587
-        $field->set_time_format($this->_tm_frmt);
1588
-        switch ($what) {
1589
-            case 'T':
1590
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1591
-                    $datetime_value,
1592
-                    $this->_fields[ $fieldname ]
1593
-                );
1594
-                $this->_has_changes = true;
1595
-                break;
1596
-            case 'D':
1597
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1598
-                    $datetime_value,
1599
-                    $this->_fields[ $fieldname ]
1600
-                );
1601
-                $this->_has_changes = true;
1602
-                break;
1603
-            case 'B':
1604
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1605
-                $this->_has_changes = true;
1606
-                break;
1607
-        }
1608
-        $this->_clear_cached_property($fieldname);
1609
-    }
1610
-
1611
-
1612
-    /**
1613
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1614
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1615
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1616
-     * that could lead to some unexpected results!
1617
-     *
1618
-     * @access public
1619
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1620
-     *                                         value being returned.
1621
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1622
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1623
-     * @param string $prepend                  You can include something to prepend on the timestamp
1624
-     * @param string $append                   You can include something to append on the timestamp
1625
-     * @throws ReflectionException
1626
-     * @throws InvalidArgumentException
1627
-     * @throws InvalidInterfaceException
1628
-     * @throws InvalidDataTypeException
1629
-     * @throws EE_Error
1630
-     * @return string timestamp
1631
-     */
1632
-    public function display_in_my_timezone(
1633
-        $field_name,
1634
-        $callback = 'get_datetime',
1635
-        $args = null,
1636
-        $prepend = '',
1637
-        $append = ''
1638
-    ) {
1639
-        $timezone = EEH_DTT_Helper::get_timezone();
1640
-        if ($timezone === $this->_timezone) {
1641
-            return '';
1642
-        }
1643
-        $original_timezone = $this->_timezone;
1644
-        $this->set_timezone($timezone);
1645
-        $fn = (array) $field_name;
1646
-        $args = array_merge($fn, (array) $args);
1647
-        if (! method_exists($this, $callback)) {
1648
-            throw new EE_Error(
1649
-                sprintf(
1650
-                    esc_html__(
1651
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1652
-                        'event_espresso'
1653
-                    ),
1654
-                    $callback
1655
-                )
1656
-            );
1657
-        }
1658
-        $args = (array) $args;
1659
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
-        $this->set_timezone($original_timezone);
1661
-        return $return;
1662
-    }
1663
-
1664
-
1665
-    /**
1666
-     * Deletes this model object.
1667
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1668
-     * override
1669
-     * `EE_Base_Class::_delete` NOT this class.
1670
-     *
1671
-     * @return boolean | int
1672
-     * @throws ReflectionException
1673
-     * @throws InvalidArgumentException
1674
-     * @throws InvalidInterfaceException
1675
-     * @throws InvalidDataTypeException
1676
-     * @throws EE_Error
1677
-     */
1678
-    public function delete()
1679
-    {
1680
-        /**
1681
-         * Called just before the `EE_Base_Class::_delete` method call.
1682
-         * Note:
1683
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1684
-         * should be aware that `_delete` may not always result in a permanent delete.
1685
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1686
-         * soft deletes (trash) the object and does not permanently delete it.
1687
-         *
1688
-         * @param EE_Base_Class $model_object about to be 'deleted'
1689
-         */
1690
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1691
-        $result = $this->_delete();
1692
-        /**
1693
-         * Called just after the `EE_Base_Class::_delete` method call.
1694
-         * Note:
1695
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1696
-         * should be aware that `_delete` may not always result in a permanent delete.
1697
-         * For example `EE_Soft_Base_Class::_delete`
1698
-         * soft deletes (trash) the object and does not permanently delete it.
1699
-         *
1700
-         * @param EE_Base_Class $model_object that was just 'deleted'
1701
-         * @param boolean       $result
1702
-         */
1703
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1704
-        return $result;
1705
-    }
1706
-
1707
-
1708
-    /**
1709
-     * Calls the specific delete method for the instantiated class.
1710
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1711
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1712
-     * `EE_Base_Class::delete`
1713
-     *
1714
-     * @return bool|int
1715
-     * @throws ReflectionException
1716
-     * @throws InvalidArgumentException
1717
-     * @throws InvalidInterfaceException
1718
-     * @throws InvalidDataTypeException
1719
-     * @throws EE_Error
1720
-     */
1721
-    protected function _delete()
1722
-    {
1723
-        return $this->delete_permanently();
1724
-    }
1725
-
1726
-
1727
-    /**
1728
-     * Deletes this model object permanently from db
1729
-     * (but keep in mind related models may block the delete and return an error)
1730
-     *
1731
-     * @return bool | int
1732
-     * @throws ReflectionException
1733
-     * @throws InvalidArgumentException
1734
-     * @throws InvalidInterfaceException
1735
-     * @throws InvalidDataTypeException
1736
-     * @throws EE_Error
1737
-     */
1738
-    public function delete_permanently()
1739
-    {
1740
-        /**
1741
-         * Called just before HARD deleting a model object
1742
-         *
1743
-         * @param EE_Base_Class $model_object about to be 'deleted'
1744
-         */
1745
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1746
-        $model = $this->get_model();
1747
-        $result = $model->delete_permanently_by_ID($this->ID());
1748
-        $this->refresh_cache_of_related_objects();
1749
-        /**
1750
-         * Called just after HARD deleting a model object
1751
-         *
1752
-         * @param EE_Base_Class $model_object that was just 'deleted'
1753
-         * @param boolean       $result
1754
-         */
1755
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1756
-        return $result;
1757
-    }
1758
-
1759
-
1760
-    /**
1761
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1762
-     * related model objects
1763
-     *
1764
-     * @throws ReflectionException
1765
-     * @throws InvalidArgumentException
1766
-     * @throws InvalidInterfaceException
1767
-     * @throws InvalidDataTypeException
1768
-     * @throws EE_Error
1769
-     */
1770
-    public function refresh_cache_of_related_objects()
1771
-    {
1772
-        $model = $this->get_model();
1773
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1774
-            if (! empty($this->_model_relations[ $relation_name ])) {
1775
-                $related_objects = $this->_model_relations[ $relation_name ];
1776
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1777
-                    // this relation only stores a single model object, not an array
1778
-                    // but let's make it consistent
1779
-                    $related_objects = array($related_objects);
1780
-                }
1781
-                foreach ($related_objects as $related_object) {
1782
-                    // only refresh their cache if they're in memory
1783
-                    if ($related_object instanceof EE_Base_Class) {
1784
-                        $related_object->clear_cache(
1785
-                            $model->get_this_model_name(),
1786
-                            $this
1787
-                        );
1788
-                    }
1789
-                }
1790
-            }
1791
-        }
1792
-    }
1793
-
1794
-
1795
-    /**
1796
-     *        Saves this object to the database. An array may be supplied to set some values on this
1797
-     * object just before saving.
1798
-     *
1799
-     * @access public
1800
-     * @param array $set_cols_n_values  keys are field names, values are their new values,
1801
-     *                                  if provided during the save() method
1802
-     *                                  (often client code will change the fields' values before calling save)
1803
-     * @return false|int|string         1 on a successful update;
1804
-     *                                  the ID of the new entry on insert;
1805
-     *                                  0 on failure, or if the model object isn't allowed to persist
1806
-     *                                  (as determined by EE_Base_Class::allow_persist())
1807
-     * @throws InvalidInterfaceException
1808
-     * @throws InvalidDataTypeException
1809
-     * @throws EE_Error
1810
-     * @throws InvalidArgumentException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     * @throws ReflectionException
1814
-     */
1815
-    public function save($set_cols_n_values = array())
1816
-    {
1817
-        $model = $this->get_model();
1818
-        /**
1819
-         * Filters the fields we're about to save on the model object
1820
-         *
1821
-         * @param array         $set_cols_n_values
1822
-         * @param EE_Base_Class $model_object
1823
-         */
1824
-        $set_cols_n_values = (array) apply_filters(
1825
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1826
-            $set_cols_n_values,
1827
-            $this
1828
-        );
1829
-        // set attributes as provided in $set_cols_n_values
1830
-        foreach ($set_cols_n_values as $column => $value) {
1831
-            $this->set($column, $value);
1832
-        }
1833
-        // no changes ? then don't do anything
1834
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
-            return 0;
1836
-        }
1837
-        /**
1838
-         * Saving a model object.
1839
-         * Before we perform a save, this action is fired.
1840
-         *
1841
-         * @param EE_Base_Class $model_object the model object about to be saved.
1842
-         */
1843
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1844
-        if (! $this->allow_persist()) {
1845
-            return 0;
1846
-        }
1847
-        // now get current attribute values
1848
-        $save_cols_n_values = $this->_fields;
1849
-        // if the object already has an ID, update it. Otherwise, insert it
1850
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1851
-        // They have been
1852
-        $old_assumption_concerning_value_preparation = $model
1853
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1854
-        $model->assume_values_already_prepared_by_model_object(true);
1855
-        // does this model have an autoincrement PK?
1856
-        if ($model->has_primary_key_field()) {
1857
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1858
-                // ok check if it's set, if so: update; if not, insert
1859
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1861
-                } else {
1862
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
-                    $results = $model->insert($save_cols_n_values);
1864
-                    if ($results) {
1865
-                        // if successful, set the primary key
1866
-                        // but don't use the normal SET method, because it will check if
1867
-                        // an item with the same ID exists in the mapper & db, then
1868
-                        // will find it in the db (because we just added it) and THAT object
1869
-                        // will get added to the mapper before we can add this one!
1870
-                        // but if we just avoid using the SET method, all that headache can be avoided
1871
-                        $pk_field_name = $model->primary_key_name();
1872
-                        $this->_fields[ $pk_field_name ] = $results;
1873
-                        $this->_clear_cached_property($pk_field_name);
1874
-                        $model->add_to_entity_map($this);
1875
-                        $this->_update_cached_related_model_objs_fks();
1876
-                    }
1877
-                }
1878
-            } else {// PK is NOT auto-increment
1879
-                // so check if one like it already exists in the db
1880
-                if ($model->exists_by_ID($this->ID())) {
1881
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1882
-                        throw new EE_Error(
1883
-                            sprintf(
1884
-                                esc_html__(
1885
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1886
-                                    'event_espresso'
1887
-                                ),
1888
-                                get_class($this),
1889
-                                get_class($model) . '::instance()->add_to_entity_map()',
1890
-                                get_class($model) . '::instance()->get_one_by_ID()',
1891
-                                '<br />'
1892
-                            )
1893
-                        );
1894
-                    }
1895
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1896
-                } else {
1897
-                    $results = $model->insert($save_cols_n_values);
1898
-                    $this->_update_cached_related_model_objs_fks();
1899
-                }
1900
-            }
1901
-        } else {// there is NO primary key
1902
-            $already_in_db = false;
1903
-            foreach ($model->unique_indexes() as $index) {
1904
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1905
-                if ($model->exists(array($uniqueness_where_params))) {
1906
-                    $already_in_db = true;
1907
-                }
1908
-            }
1909
-            if ($already_in_db) {
1910
-                $combined_pk_fields_n_values = array_intersect_key(
1911
-                    $save_cols_n_values,
1912
-                    $model->get_combined_primary_key_fields()
1913
-                );
1914
-                $results = $model->update(
1915
-                    $save_cols_n_values,
1916
-                    $combined_pk_fields_n_values
1917
-                );
1918
-            } else {
1919
-                $results = $model->insert($save_cols_n_values);
1920
-            }
1921
-        }
1922
-        // restore the old assumption about values being prepared by the model object
1923
-        $model->assume_values_already_prepared_by_model_object(
1924
-            $old_assumption_concerning_value_preparation
1925
-        );
1926
-        /**
1927
-         * After saving the model object this action is called
1928
-         *
1929
-         * @param EE_Base_Class $model_object which was just saved
1930
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1931
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1932
-         */
1933
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1934
-        $this->_has_changes = false;
1935
-        return $results;
1936
-    }
1937
-
1938
-
1939
-    /**
1940
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1941
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1942
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1943
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1944
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1945
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1946
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1947
-     *
1948
-     * @return void
1949
-     * @throws ReflectionException
1950
-     * @throws InvalidArgumentException
1951
-     * @throws InvalidInterfaceException
1952
-     * @throws InvalidDataTypeException
1953
-     * @throws EE_Error
1954
-     */
1955
-    protected function _update_cached_related_model_objs_fks()
1956
-    {
1957
-        $model = $this->get_model();
1958
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1959
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1960
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1961
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1962
-                        $model->get_this_model_name()
1963
-                    );
1964
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1965
-                    if ($related_model_obj_in_cache->ID()) {
1966
-                        $related_model_obj_in_cache->save();
1967
-                    }
1968
-                }
1969
-            }
1970
-        }
1971
-    }
1972
-
1973
-
1974
-    /**
1975
-     * Saves this model object and its NEW cached relations to the database.
1976
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1977
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1978
-     * because otherwise, there's a potential for infinite looping of saving
1979
-     * Saves the cached related model objects, and ensures the relation between them
1980
-     * and this object and properly setup
1981
-     *
1982
-     * @return int ID of new model object on save; 0 on failure+
1983
-     * @throws ReflectionException
1984
-     * @throws InvalidArgumentException
1985
-     * @throws InvalidInterfaceException
1986
-     * @throws InvalidDataTypeException
1987
-     * @throws EE_Error
1988
-     */
1989
-    public function save_new_cached_related_model_objs()
1990
-    {
1991
-        // make sure this has been saved
1992
-        if (! $this->ID()) {
1993
-            $id = $this->save();
1994
-        } else {
1995
-            $id = $this->ID();
1996
-        }
1997
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1998
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1999
-            if ($this->_model_relations[ $relationName ]) {
2000
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2001
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2002
-                /* @var $related_model_obj EE_Base_Class */
2003
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2004
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2005
-                    // but ONLY if it DOES NOT exist in the DB
2006
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2007
-                    // if( ! $related_model_obj->ID()){
2008
-                    $this->_add_relation_to($related_model_obj, $relationName);
2009
-                    $related_model_obj->save_new_cached_related_model_objs();
2010
-                    // }
2011
-                } else {
2012
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2014
-                        // but ONLY if it DOES NOT exist in the DB
2015
-                        // if( ! $related_model_obj->ID()){
2016
-                        $this->_add_relation_to($related_model_obj, $relationName);
2017
-                        $related_model_obj->save_new_cached_related_model_objs();
2018
-                        // }
2019
-                    }
2020
-                }
2021
-            }
2022
-        }
2023
-        return $id;
2024
-    }
2025
-
2026
-
2027
-    /**
2028
-     * for getting a model while instantiated.
2029
-     *
2030
-     * @return EEM_Base | EEM_CPT_Base
2031
-     * @throws ReflectionException
2032
-     * @throws InvalidArgumentException
2033
-     * @throws InvalidInterfaceException
2034
-     * @throws InvalidDataTypeException
2035
-     * @throws EE_Error
2036
-     */
2037
-    public function get_model()
2038
-    {
2039
-        if (! $this->_model) {
2040
-            $modelName = self::_get_model_classname(get_class($this));
2041
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2042
-        } else {
2043
-            $this->_model->set_timezone($this->_timezone);
2044
-        }
2045
-        return $this->_model;
2046
-    }
2047
-
2048
-
2049
-    /**
2050
-     * @param $props_n_values
2051
-     * @param $classname
2052
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2053
-     * @throws ReflectionException
2054
-     * @throws InvalidArgumentException
2055
-     * @throws InvalidInterfaceException
2056
-     * @throws InvalidDataTypeException
2057
-     * @throws EE_Error
2058
-     */
2059
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2060
-    {
2061
-        // TODO: will not work for Term_Relationships because they have no PK!
2062
-        $primary_id_ref = self::_get_primary_key_name($classname);
2063
-        if (
2064
-            array_key_exists($primary_id_ref, $props_n_values)
2065
-            && ! empty($props_n_values[ $primary_id_ref ])
2066
-        ) {
2067
-            $id = $props_n_values[ $primary_id_ref ];
2068
-            return self::_get_model($classname)->get_from_entity_map($id);
2069
-        }
2070
-        return false;
2071
-    }
2072
-
2073
-
2074
-    /**
2075
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2076
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2077
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2078
-     * we return false.
2079
-     *
2080
-     * @param  array  $props_n_values   incoming array of properties and their values
2081
-     * @param  string $classname        the classname of the child class
2082
-     * @param null    $timezone
2083
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2084
-     *                                  date_format and the second value is the time format
2085
-     * @return mixed (EE_Base_Class|bool)
2086
-     * @throws InvalidArgumentException
2087
-     * @throws InvalidInterfaceException
2088
-     * @throws InvalidDataTypeException
2089
-     * @throws EE_Error
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     * @throws ReflectionException
2093
-     */
2094
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2095
-    {
2096
-        $existing = null;
2097
-        $model = self::_get_model($classname, $timezone);
2098
-        if ($model->has_primary_key_field()) {
2099
-            $primary_id_ref = self::_get_primary_key_name($classname);
2100
-            if (
2101
-                array_key_exists($primary_id_ref, $props_n_values)
2102
-                && ! empty($props_n_values[ $primary_id_ref ])
2103
-            ) {
2104
-                $existing = $model->get_one_by_ID(
2105
-                    $props_n_values[ $primary_id_ref ]
2106
-                );
2107
-            }
2108
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2109
-            // no primary key on this model, but there's still a matching item in the DB
2110
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2111
-                self::_get_model($classname, $timezone)
2112
-                    ->get_index_primary_key_string($props_n_values)
2113
-            );
2114
-        }
2115
-        if ($existing) {
2116
-            // set date formats if present before setting values
2117
-            if (! empty($date_formats) && is_array($date_formats)) {
2118
-                $existing->set_date_format($date_formats[0]);
2119
-                $existing->set_time_format($date_formats[1]);
2120
-            } else {
2121
-                // set default formats for date and time
2122
-                $existing->set_date_format(get_option('date_format'));
2123
-                $existing->set_time_format(get_option('time_format'));
2124
-            }
2125
-            foreach ($props_n_values as $property => $field_value) {
2126
-                $existing->set($property, $field_value);
2127
-            }
2128
-            return $existing;
2129
-        }
2130
-        return false;
2131
-    }
2132
-
2133
-
2134
-    /**
2135
-     * Gets the EEM_*_Model for this class
2136
-     *
2137
-     * @access public now, as this is more convenient
2138
-     * @param      $classname
2139
-     * @param null $timezone
2140
-     * @throws ReflectionException
2141
-     * @throws InvalidArgumentException
2142
-     * @throws InvalidInterfaceException
2143
-     * @throws InvalidDataTypeException
2144
-     * @throws EE_Error
2145
-     * @return EEM_Base
2146
-     */
2147
-    protected static function _get_model($classname, $timezone = null)
2148
-    {
2149
-        // find model for this class
2150
-        if (! $classname) {
2151
-            throw new EE_Error(
2152
-                sprintf(
2153
-                    esc_html__(
2154
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2155
-                        'event_espresso'
2156
-                    ),
2157
-                    $classname
2158
-                )
2159
-            );
2160
-        }
2161
-        $modelName = self::_get_model_classname($classname);
2162
-        return self::_get_model_instance_with_name($modelName, $timezone);
2163
-    }
2164
-
2165
-
2166
-    /**
2167
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2168
-     *
2169
-     * @param string $model_classname
2170
-     * @param null   $timezone
2171
-     * @return EEM_Base
2172
-     * @throws ReflectionException
2173
-     * @throws InvalidArgumentException
2174
-     * @throws InvalidInterfaceException
2175
-     * @throws InvalidDataTypeException
2176
-     * @throws EE_Error
2177
-     */
2178
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2179
-    {
2180
-        $model_classname = str_replace('EEM_', '', $model_classname);
2181
-        $model = EE_Registry::instance()->load_model($model_classname);
2182
-        $model->set_timezone($timezone);
2183
-        return $model;
2184
-    }
2185
-
2186
-
2187
-    /**
2188
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2189
-     * Also works if a model class's classname is provided (eg EE_Registration).
2190
-     *
2191
-     * @param null $model_name
2192
-     * @return string like EEM_Attendee
2193
-     */
2194
-    private static function _get_model_classname($model_name = null)
2195
-    {
2196
-        if (strpos($model_name, 'EE_') === 0) {
2197
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2198
-        } else {
2199
-            $model_classname = 'EEM_' . $model_name;
2200
-        }
2201
-        return $model_classname;
2202
-    }
2203
-
2204
-
2205
-    /**
2206
-     * returns the name of the primary key attribute
2207
-     *
2208
-     * @param null $classname
2209
-     * @throws ReflectionException
2210
-     * @throws InvalidArgumentException
2211
-     * @throws InvalidInterfaceException
2212
-     * @throws InvalidDataTypeException
2213
-     * @throws EE_Error
2214
-     * @return string
2215
-     */
2216
-    protected static function _get_primary_key_name($classname = null)
2217
-    {
2218
-        if (! $classname) {
2219
-            throw new EE_Error(
2220
-                sprintf(
2221
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2222
-                    $classname
2223
-                )
2224
-            );
2225
-        }
2226
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2227
-    }
2228
-
2229
-
2230
-    /**
2231
-     * Gets the value of the primary key.
2232
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2233
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2234
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2235
-     *
2236
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2237
-     * @throws ReflectionException
2238
-     * @throws InvalidArgumentException
2239
-     * @throws InvalidInterfaceException
2240
-     * @throws InvalidDataTypeException
2241
-     * @throws EE_Error
2242
-     */
2243
-    public function ID()
2244
-    {
2245
-        $model = $this->get_model();
2246
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2247
-        if ($model->has_primary_key_field()) {
2248
-            return $this->_fields[ $model->primary_key_name() ];
2249
-        }
2250
-        return $model->get_index_primary_key_string($this->_fields);
2251
-    }
2252
-
2253
-
2254
-    /**
2255
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2256
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2257
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2258
-     *
2259
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2260
-     * @param string $relationName                     eg 'Events','Question',etc.
2261
-     *                                                 an attendee to a group, you also want to specify which role they
2262
-     *                                                 will have in that group. So you would use this parameter to
2263
-     *                                                 specify array('role-column-name'=>'role-id')
2264
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2265
-     *                                                 allow you to further constrict the relation to being added.
2266
-     *                                                 However, keep in mind that the columns (keys) given must match a
2267
-     *                                                 column on the JOIN table and currently only the HABTM models
2268
-     *                                                 accept these additional conditions.  Also remember that if an
2269
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2270
-     *                                                 NEW row is created in the join table.
2271
-     * @param null   $cache_id
2272
-     * @throws ReflectionException
2273
-     * @throws InvalidArgumentException
2274
-     * @throws InvalidInterfaceException
2275
-     * @throws InvalidDataTypeException
2276
-     * @throws EE_Error
2277
-     * @return EE_Base_Class the object the relation was added to
2278
-     */
2279
-    public function _add_relation_to(
2280
-        $otherObjectModelObjectOrID,
2281
-        $relationName,
2282
-        $extra_join_model_fields_n_values = array(),
2283
-        $cache_id = null
2284
-    ) {
2285
-        $model = $this->get_model();
2286
-        // if this thing exists in the DB, save the relation to the DB
2287
-        if ($this->ID()) {
2288
-            $otherObject = $model->add_relationship_to(
2289
-                $this,
2290
-                $otherObjectModelObjectOrID,
2291
-                $relationName,
2292
-                $extra_join_model_fields_n_values
2293
-            );
2294
-            // clear cache so future get_many_related and get_first_related() return new results.
2295
-            $this->clear_cache($relationName, $otherObject, true);
2296
-            if ($otherObject instanceof EE_Base_Class) {
2297
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2298
-            }
2299
-        } else {
2300
-            // this thing doesn't exist in the DB,  so just cache it
2301
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2302
-                throw new EE_Error(
2303
-                    sprintf(
2304
-                        esc_html__(
2305
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2306
-                            'event_espresso'
2307
-                        ),
2308
-                        $otherObjectModelObjectOrID,
2309
-                        get_class($this)
2310
-                    )
2311
-                );
2312
-            }
2313
-            $otherObject = $otherObjectModelObjectOrID;
2314
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2315
-        }
2316
-        if ($otherObject instanceof EE_Base_Class) {
2317
-            // fix the reciprocal relation too
2318
-            if ($otherObject->ID()) {
2319
-                // its saved so assumed relations exist in the DB, so we can just
2320
-                // clear the cache so future queries use the updated info in the DB
2321
-                $otherObject->clear_cache(
2322
-                    $model->get_this_model_name(),
2323
-                    null,
2324
-                    true
2325
-                );
2326
-            } else {
2327
-                // it's not saved, so it caches relations like this
2328
-                $otherObject->cache($model->get_this_model_name(), $this);
2329
-            }
2330
-        }
2331
-        return $otherObject;
2332
-    }
2333
-
2334
-
2335
-    /**
2336
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2337
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2338
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2339
-     * from the cache
2340
-     *
2341
-     * @param mixed  $otherObjectModelObjectOrID
2342
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2343
-     *                to the DB yet
2344
-     * @param string $relationName
2345
-     * @param array  $where_query
2346
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2347
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2348
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2349
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2350
-     *                deleted.
2351
-     * @return EE_Base_Class the relation was removed from
2352
-     * @throws ReflectionException
2353
-     * @throws InvalidArgumentException
2354
-     * @throws InvalidInterfaceException
2355
-     * @throws InvalidDataTypeException
2356
-     * @throws EE_Error
2357
-     */
2358
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2359
-    {
2360
-        if ($this->ID()) {
2361
-            // if this exists in the DB, save the relation change to the DB too
2362
-            $otherObject = $this->get_model()->remove_relationship_to(
2363
-                $this,
2364
-                $otherObjectModelObjectOrID,
2365
-                $relationName,
2366
-                $where_query
2367
-            );
2368
-            $this->clear_cache(
2369
-                $relationName,
2370
-                $otherObject
2371
-            );
2372
-        } else {
2373
-            // this doesn't exist in the DB, just remove it from the cache
2374
-            $otherObject = $this->clear_cache(
2375
-                $relationName,
2376
-                $otherObjectModelObjectOrID
2377
-            );
2378
-        }
2379
-        if ($otherObject instanceof EE_Base_Class) {
2380
-            $otherObject->clear_cache(
2381
-                $this->get_model()->get_this_model_name(),
2382
-                $this
2383
-            );
2384
-        }
2385
-        return $otherObject;
2386
-    }
2387
-
2388
-
2389
-    /**
2390
-     * Removes ALL the related things for the $relationName.
2391
-     *
2392
-     * @param string $relationName
2393
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2394
-     * @return EE_Base_Class
2395
-     * @throws ReflectionException
2396
-     * @throws InvalidArgumentException
2397
-     * @throws InvalidInterfaceException
2398
-     * @throws InvalidDataTypeException
2399
-     * @throws EE_Error
2400
-     */
2401
-    public function _remove_relations($relationName, $where_query_params = array())
2402
-    {
2403
-        if ($this->ID()) {
2404
-            // if this exists in the DB, save the relation change to the DB too
2405
-            $otherObjects = $this->get_model()->remove_relations(
2406
-                $this,
2407
-                $relationName,
2408
-                $where_query_params
2409
-            );
2410
-            $this->clear_cache(
2411
-                $relationName,
2412
-                null,
2413
-                true
2414
-            );
2415
-        } else {
2416
-            // this doesn't exist in the DB, just remove it from the cache
2417
-            $otherObjects = $this->clear_cache(
2418
-                $relationName,
2419
-                null,
2420
-                true
2421
-            );
2422
-        }
2423
-        if (is_array($otherObjects)) {
2424
-            foreach ($otherObjects as $otherObject) {
2425
-                $otherObject->clear_cache(
2426
-                    $this->get_model()->get_this_model_name(),
2427
-                    $this
2428
-                );
2429
-            }
2430
-        }
2431
-        return $otherObjects;
2432
-    }
2433
-
2434
-
2435
-    /**
2436
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2437
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2438
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2439
-     * because we want to get even deleted items etc.
2440
-     *
2441
-     * @param string $relationName key in the model's _model_relations array
2442
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2443
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2444
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2445
-     *                             results if you want IDs
2446
-     * @throws ReflectionException
2447
-     * @throws InvalidArgumentException
2448
-     * @throws InvalidInterfaceException
2449
-     * @throws InvalidDataTypeException
2450
-     * @throws EE_Error
2451
-     */
2452
-    public function get_many_related($relationName, $query_params = array())
2453
-    {
2454
-        if ($this->ID()) {
2455
-            // this exists in the DB, so get the related things from either the cache or the DB
2456
-            // if there are query parameters, forget about caching the related model objects.
2457
-            if ($query_params) {
2458
-                $related_model_objects = $this->get_model()->get_all_related(
2459
-                    $this,
2460
-                    $relationName,
2461
-                    $query_params
2462
-                );
2463
-            } else {
2464
-                // did we already cache the result of this query?
2465
-                $cached_results = $this->get_all_from_cache($relationName);
2466
-                if (! $cached_results) {
2467
-                    $related_model_objects = $this->get_model()->get_all_related(
2468
-                        $this,
2469
-                        $relationName,
2470
-                        $query_params
2471
-                    );
2472
-                    // if no query parameters were passed, then we got all the related model objects
2473
-                    // for that relation. We can cache them then.
2474
-                    foreach ($related_model_objects as $related_model_object) {
2475
-                        $this->cache($relationName, $related_model_object);
2476
-                    }
2477
-                } else {
2478
-                    $related_model_objects = $cached_results;
2479
-                }
2480
-            }
2481
-        } else {
2482
-            // this doesn't exist in the DB, so just get the related things from the cache
2483
-            $related_model_objects = $this->get_all_from_cache($relationName);
2484
-        }
2485
-        return $related_model_objects;
2486
-    }
2487
-
2488
-
2489
-    /**
2490
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2491
-     * unless otherwise specified in the $query_params
2492
-     *
2493
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2494
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2495
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2496
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2497
-     *                               that by the setting $distinct to TRUE;
2498
-     * @return int
2499
-     * @throws ReflectionException
2500
-     * @throws InvalidArgumentException
2501
-     * @throws InvalidInterfaceException
2502
-     * @throws InvalidDataTypeException
2503
-     * @throws EE_Error
2504
-     */
2505
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2506
-    {
2507
-        return $this->get_model()->count_related(
2508
-            $this,
2509
-            $relation_name,
2510
-            $query_params,
2511
-            $field_to_count,
2512
-            $distinct
2513
-        );
2514
-    }
2515
-
2516
-
2517
-    /**
2518
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2519
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2520
-     *
2521
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2522
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2523
-     * @param string $field_to_sum  name of field to count by.
2524
-     *                              By default, uses primary key
2525
-     *                              (which doesn't make much sense, so you should probably change it)
2526
-     * @return int
2527
-     * @throws ReflectionException
2528
-     * @throws InvalidArgumentException
2529
-     * @throws InvalidInterfaceException
2530
-     * @throws InvalidDataTypeException
2531
-     * @throws EE_Error
2532
-     */
2533
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2534
-    {
2535
-        return $this->get_model()->sum_related(
2536
-            $this,
2537
-            $relation_name,
2538
-            $query_params,
2539
-            $field_to_sum
2540
-        );
2541
-    }
2542
-
2543
-
2544
-    /**
2545
-     * Gets the first (ie, one) related model object of the specified type.
2546
-     *
2547
-     * @param string $relationName key in the model's _model_relations array
2548
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
-     * @return EE_Base_Class (not an array, a single object)
2550
-     * @throws ReflectionException
2551
-     * @throws InvalidArgumentException
2552
-     * @throws InvalidInterfaceException
2553
-     * @throws InvalidDataTypeException
2554
-     * @throws EE_Error
2555
-     */
2556
-    public function get_first_related($relationName, $query_params = array())
2557
-    {
2558
-        $model = $this->get_model();
2559
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2560
-            // if they've provided some query parameters, don't bother trying to cache the result
2561
-            // also make sure we're not caching the result of get_first_related
2562
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2563
-            if (
2564
-                $query_params
2565
-                || ! $model->related_settings_for($relationName)
2566
-                     instanceof
2567
-                     EE_Belongs_To_Relation
2568
-            ) {
2569
-                $related_model_object = $model->get_first_related(
2570
-                    $this,
2571
-                    $relationName,
2572
-                    $query_params
2573
-                );
2574
-            } else {
2575
-                // first, check if we've already cached the result of this query
2576
-                $cached_result = $this->get_one_from_cache($relationName);
2577
-                if (! $cached_result) {
2578
-                    $related_model_object = $model->get_first_related(
2579
-                        $this,
2580
-                        $relationName,
2581
-                        $query_params
2582
-                    );
2583
-                    $this->cache($relationName, $related_model_object);
2584
-                } else {
2585
-                    $related_model_object = $cached_result;
2586
-                }
2587
-            }
2588
-        } else {
2589
-            $related_model_object = null;
2590
-            // this doesn't exist in the Db,
2591
-            // but maybe the relation is of type belongs to, and so the related thing might
2592
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2593
-                $related_model_object = $model->get_first_related(
2594
-                    $this,
2595
-                    $relationName,
2596
-                    $query_params
2597
-                );
2598
-            }
2599
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2600
-            // just get what's cached on this object
2601
-            if (! $related_model_object) {
2602
-                $related_model_object = $this->get_one_from_cache($relationName);
2603
-            }
2604
-        }
2605
-        return $related_model_object;
2606
-    }
2607
-
2608
-
2609
-    /**
2610
-     * Does a delete on all related objects of type $relationName and removes
2611
-     * the current model object's relation to them. If they can't be deleted (because
2612
-     * of blocking related model objects) does nothing. If the related model objects are
2613
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2614
-     * If this model object doesn't exist yet in the DB, just removes its related things
2615
-     *
2616
-     * @param string $relationName
2617
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2618
-     * @return int how many deleted
2619
-     * @throws ReflectionException
2620
-     * @throws InvalidArgumentException
2621
-     * @throws InvalidInterfaceException
2622
-     * @throws InvalidDataTypeException
2623
-     * @throws EE_Error
2624
-     */
2625
-    public function delete_related($relationName, $query_params = array())
2626
-    {
2627
-        if ($this->ID()) {
2628
-            $count = $this->get_model()->delete_related(
2629
-                $this,
2630
-                $relationName,
2631
-                $query_params
2632
-            );
2633
-        } else {
2634
-            $count = count($this->get_all_from_cache($relationName));
2635
-            $this->clear_cache($relationName, null, true);
2636
-        }
2637
-        return $count;
2638
-    }
2639
-
2640
-
2641
-    /**
2642
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2643
-     * the current model object's relation to them. If they can't be deleted (because
2644
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2645
-     * If the related thing isn't a soft-deletable model object, this function is identical
2646
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2647
-     *
2648
-     * @param string $relationName
2649
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
-     * @return int how many deleted (including those soft deleted)
2651
-     * @throws ReflectionException
2652
-     * @throws InvalidArgumentException
2653
-     * @throws InvalidInterfaceException
2654
-     * @throws InvalidDataTypeException
2655
-     * @throws EE_Error
2656
-     */
2657
-    public function delete_related_permanently($relationName, $query_params = array())
2658
-    {
2659
-        if ($this->ID()) {
2660
-            $count = $this->get_model()->delete_related_permanently(
2661
-                $this,
2662
-                $relationName,
2663
-                $query_params
2664
-            );
2665
-        } else {
2666
-            $count = count($this->get_all_from_cache($relationName));
2667
-        }
2668
-        $this->clear_cache($relationName, null, true);
2669
-        return $count;
2670
-    }
2671
-
2672
-
2673
-    /**
2674
-     * is_set
2675
-     * Just a simple utility function children can use for checking if property exists
2676
-     *
2677
-     * @access  public
2678
-     * @param  string $field_name property to check
2679
-     * @return bool                              TRUE if existing,FALSE if not.
2680
-     */
2681
-    public function is_set($field_name)
2682
-    {
2683
-        return isset($this->_fields[ $field_name ]);
2684
-    }
2685
-
2686
-
2687
-    /**
2688
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2689
-     * EE_Error exception if they don't
2690
-     *
2691
-     * @param  mixed (string|array) $properties properties to check
2692
-     * @throws EE_Error
2693
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2694
-     */
2695
-    protected function _property_exists($properties)
2696
-    {
2697
-        foreach ((array) $properties as $property_name) {
2698
-            // first make sure this property exists
2699
-            if (! $this->_fields[ $property_name ]) {
2700
-                throw new EE_Error(
2701
-                    sprintf(
2702
-                        esc_html__(
2703
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2704
-                            'event_espresso'
2705
-                        ),
2706
-                        $property_name
2707
-                    )
2708
-                );
2709
-            }
2710
-        }
2711
-        return true;
2712
-    }
2713
-
2714
-
2715
-    /**
2716
-     * This simply returns an array of model fields for this object
2717
-     *
2718
-     * @return array
2719
-     * @throws ReflectionException
2720
-     * @throws InvalidArgumentException
2721
-     * @throws InvalidInterfaceException
2722
-     * @throws InvalidDataTypeException
2723
-     * @throws EE_Error
2724
-     */
2725
-    public function model_field_array()
2726
-    {
2727
-        $fields = $this->get_model()->field_settings(false);
2728
-        $properties = array();
2729
-        // remove prepended underscore
2730
-        foreach ($fields as $field_name => $settings) {
2731
-            $properties[ $field_name ] = $this->get($field_name);
2732
-        }
2733
-        return $properties;
2734
-    }
2735
-
2736
-
2737
-    /**
2738
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2739
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2740
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2741
-     * Instead of requiring a plugin to extend the EE_Base_Class
2742
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2743
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2744
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2745
-     * and accepts 2 arguments: the object on which the function was called,
2746
-     * and an array of the original arguments passed to the function.
2747
-     * Whatever their callback function returns will be returned by this function.
2748
-     * Example: in functions.php (or in a plugin):
2749
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2750
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2751
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2752
-     *          return $previousReturnValue.$returnString;
2753
-     *      }
2754
-     * require('EE_Answer.class.php');
2755
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2756
-     *      ->my_callback('monkeys',100);
2757
-     * // will output "you called my_callback! and passed args:monkeys,100"
2758
-     *
2759
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2760
-     * @param array  $args       array of original arguments passed to the function
2761
-     * @throws EE_Error
2762
-     * @return mixed whatever the plugin which calls add_filter decides
2763
-     */
2764
-    public function __call($methodName, $args)
2765
-    {
2766
-        $className = get_class($this);
2767
-        $tagName = "FHEE__{$className}__{$methodName}";
2768
-        if (! has_filter($tagName)) {
2769
-            throw new EE_Error(
2770
-                sprintf(
2771
-                    esc_html__(
2772
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2773
-                        'event_espresso'
2774
-                    ),
2775
-                    $methodName,
2776
-                    $className,
2777
-                    $tagName
2778
-                )
2779
-            );
2780
-        }
2781
-        return apply_filters($tagName, null, $this, $args);
2782
-    }
2783
-
2784
-
2785
-    /**
2786
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2787
-     * A $previous_value can be specified in case there are many meta rows with the same key
2788
-     *
2789
-     * @param string $meta_key
2790
-     * @param mixed  $meta_value
2791
-     * @param mixed  $previous_value
2792
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2793
-     *                  NOTE: if the values haven't changed, returns 0
2794
-     * @throws InvalidArgumentException
2795
-     * @throws InvalidInterfaceException
2796
-     * @throws InvalidDataTypeException
2797
-     * @throws EE_Error
2798
-     * @throws ReflectionException
2799
-     */
2800
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2801
-    {
2802
-        $query_params = array(
2803
-            array(
2804
-                'EXM_key'  => $meta_key,
2805
-                'OBJ_ID'   => $this->ID(),
2806
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2807
-            ),
2808
-        );
2809
-        if ($previous_value !== null) {
2810
-            $query_params[0]['EXM_value'] = $meta_value;
2811
-        }
2812
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2813
-        if (! $existing_rows_like_that) {
2814
-            return $this->add_extra_meta($meta_key, $meta_value);
2815
-        }
2816
-        foreach ($existing_rows_like_that as $existing_row) {
2817
-            $existing_row->save(array('EXM_value' => $meta_value));
2818
-        }
2819
-        return count($existing_rows_like_that);
2820
-    }
2821
-
2822
-
2823
-    /**
2824
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2825
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2826
-     * extra meta row was entered, false if not
2827
-     *
2828
-     * @param string  $meta_key
2829
-     * @param mixed   $meta_value
2830
-     * @param boolean $unique
2831
-     * @return boolean
2832
-     * @throws InvalidArgumentException
2833
-     * @throws InvalidInterfaceException
2834
-     * @throws InvalidDataTypeException
2835
-     * @throws EE_Error
2836
-     * @throws ReflectionException
2837
-     * @throws ReflectionException
2838
-     */
2839
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2840
-    {
2841
-        if ($unique) {
2842
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2843
-                array(
2844
-                    array(
2845
-                        'EXM_key'  => $meta_key,
2846
-                        'OBJ_ID'   => $this->ID(),
2847
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2848
-                    ),
2849
-                )
2850
-            );
2851
-            if ($existing_extra_meta) {
2852
-                return false;
2853
-            }
2854
-        }
2855
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2856
-            array(
2857
-                'EXM_key'   => $meta_key,
2858
-                'EXM_value' => $meta_value,
2859
-                'OBJ_ID'    => $this->ID(),
2860
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2861
-            )
2862
-        );
2863
-        $new_extra_meta->save();
2864
-        return true;
2865
-    }
2866
-
2867
-
2868
-    /**
2869
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2870
-     * is specified, only deletes extra meta records with that value.
2871
-     *
2872
-     * @param string $meta_key
2873
-     * @param mixed  $meta_value
2874
-     * @return int number of extra meta rows deleted
2875
-     * @throws InvalidArgumentException
2876
-     * @throws InvalidInterfaceException
2877
-     * @throws InvalidDataTypeException
2878
-     * @throws EE_Error
2879
-     * @throws ReflectionException
2880
-     */
2881
-    public function delete_extra_meta($meta_key, $meta_value = null)
2882
-    {
2883
-        $query_params = array(
2884
-            array(
2885
-                'EXM_key'  => $meta_key,
2886
-                'OBJ_ID'   => $this->ID(),
2887
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2888
-            ),
2889
-        );
2890
-        if ($meta_value !== null) {
2891
-            $query_params[0]['EXM_value'] = $meta_value;
2892
-        }
2893
-        return EEM_Extra_Meta::instance()->delete($query_params);
2894
-    }
2895
-
2896
-
2897
-    /**
2898
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2899
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2900
-     * You can specify $default is case you haven't found the extra meta
2901
-     *
2902
-     * @param string  $meta_key
2903
-     * @param boolean $single
2904
-     * @param mixed   $default if we don't find anything, what should we return?
2905
-     * @return mixed single value if $single; array if ! $single
2906
-     * @throws ReflectionException
2907
-     * @throws InvalidArgumentException
2908
-     * @throws InvalidInterfaceException
2909
-     * @throws InvalidDataTypeException
2910
-     * @throws EE_Error
2911
-     */
2912
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2913
-    {
2914
-        if ($single) {
2915
-            $result = $this->get_first_related(
2916
-                'Extra_Meta',
2917
-                array(array('EXM_key' => $meta_key))
2918
-            );
2919
-            if ($result instanceof EE_Extra_Meta) {
2920
-                return $result->value();
2921
-            }
2922
-        } else {
2923
-            $results = $this->get_many_related(
2924
-                'Extra_Meta',
2925
-                array(array('EXM_key' => $meta_key))
2926
-            );
2927
-            if ($results) {
2928
-                $values = array();
2929
-                foreach ($results as $result) {
2930
-                    if ($result instanceof EE_Extra_Meta) {
2931
-                        $values[ $result->ID() ] = $result->value();
2932
-                    }
2933
-                }
2934
-                return $values;
2935
-            }
2936
-        }
2937
-        // if nothing discovered yet return default.
2938
-        return apply_filters(
2939
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2940
-            $default,
2941
-            $meta_key,
2942
-            $single,
2943
-            $this
2944
-        );
2945
-    }
2946
-
2947
-
2948
-    /**
2949
-     * Returns a simple array of all the extra meta associated with this model object.
2950
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2951
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2952
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2953
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2954
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2955
-     * finally the extra meta's value as each sub-value. (eg
2956
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2957
-     *
2958
-     * @param boolean $one_of_each_key
2959
-     * @return array
2960
-     * @throws ReflectionException
2961
-     * @throws InvalidArgumentException
2962
-     * @throws InvalidInterfaceException
2963
-     * @throws InvalidDataTypeException
2964
-     * @throws EE_Error
2965
-     */
2966
-    public function all_extra_meta_array($one_of_each_key = true)
2967
-    {
2968
-        $return_array = array();
2969
-        if ($one_of_each_key) {
2970
-            $extra_meta_objs = $this->get_many_related(
2971
-                'Extra_Meta',
2972
-                array('group_by' => 'EXM_key')
2973
-            );
2974
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2975
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2976
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2977
-                }
2978
-            }
2979
-        } else {
2980
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2981
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2982
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2983
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2984
-                        $return_array[ $extra_meta_obj->key() ] = array();
2985
-                    }
2986
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2987
-                }
2988
-            }
2989
-        }
2990
-        return $return_array;
2991
-    }
2992
-
2993
-
2994
-    /**
2995
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2996
-     *
2997
-     * @return string
2998
-     * @throws ReflectionException
2999
-     * @throws InvalidArgumentException
3000
-     * @throws InvalidInterfaceException
3001
-     * @throws InvalidDataTypeException
3002
-     * @throws EE_Error
3003
-     */
3004
-    public function name()
3005
-    {
3006
-        // find a field that's not a text field
3007
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3008
-        if ($field_we_can_use) {
3009
-            return $this->get($field_we_can_use->get_name());
3010
-        }
3011
-        $first_few_properties = $this->model_field_array();
3012
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3013
-        $name_parts = array();
3014
-        foreach ($first_few_properties as $name => $value) {
3015
-            $name_parts[] = "$name:$value";
3016
-        }
3017
-        return implode(',', $name_parts);
3018
-    }
3019
-
3020
-
3021
-    /**
3022
-     * in_entity_map
3023
-     * Checks if this model object has been proven to already be in the entity map
3024
-     *
3025
-     * @return boolean
3026
-     * @throws ReflectionException
3027
-     * @throws InvalidArgumentException
3028
-     * @throws InvalidInterfaceException
3029
-     * @throws InvalidDataTypeException
3030
-     * @throws EE_Error
3031
-     */
3032
-    public function in_entity_map()
3033
-    {
3034
-        // well, if we looked, did we find it in the entity map?
3035
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3036
-    }
3037
-
3038
-
3039
-    /**
3040
-     * refresh_from_db
3041
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3042
-     *
3043
-     * @throws ReflectionException
3044
-     * @throws InvalidArgumentException
3045
-     * @throws InvalidInterfaceException
3046
-     * @throws InvalidDataTypeException
3047
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3048
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3049
-     */
3050
-    public function refresh_from_db()
3051
-    {
3052
-        if ($this->ID() && $this->in_entity_map()) {
3053
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3054
-        } else {
3055
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3056
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3057
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3058
-            // absolutely nothing in it for this ID
3059
-            if (WP_DEBUG) {
3060
-                throw new EE_Error(
3061
-                    sprintf(
3062
-                        esc_html__(
3063
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3064
-                            'event_espresso'
3065
-                        ),
3066
-                        $this->ID(),
3067
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3068
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3069
-                    )
3070
-                );
3071
-            }
3072
-        }
3073
-    }
3074
-
3075
-
3076
-    /**
3077
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3078
-     *
3079
-     * @since 4.9.80.p
3080
-     * @param EE_Model_Field_Base[] $fields
3081
-     * @param string $new_value_sql
3082
-     *      example: 'column_name=123',
3083
-     *      or 'column_name=column_name+1',
3084
-     *      or 'column_name= CASE
3085
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3086
-     *          THEN `column_name` + 5
3087
-     *          ELSE `column_name`
3088
-     *      END'
3089
-     *      Also updates $field on this model object with the latest value from the database.
3090
-     * @return bool
3091
-     * @throws EE_Error
3092
-     * @throws InvalidArgumentException
3093
-     * @throws InvalidDataTypeException
3094
-     * @throws InvalidInterfaceException
3095
-     * @throws ReflectionException
3096
-     */
3097
-    protected function updateFieldsInDB($fields, $new_value_sql)
3098
-    {
3099
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3100
-        // if it wasn't even there to start off.
3101
-        if (! $this->ID()) {
3102
-            $this->save();
3103
-        }
3104
-        global $wpdb;
3105
-        if (empty($fields)) {
3106
-            throw new InvalidArgumentException(
3107
-                esc_html__(
3108
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3109
-                    'event_espresso'
3110
-                )
3111
-            );
3112
-        }
3113
-        $first_field = reset($fields);
3114
-        $table_alias = $first_field->get_table_alias();
3115
-        foreach ($fields as $field) {
3116
-            if ($table_alias !== $field->get_table_alias()) {
3117
-                throw new InvalidArgumentException(
3118
-                    sprintf(
3119
-                        esc_html__(
3120
-                            // @codingStandardsIgnoreStart
3121
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3122
-                            // @codingStandardsIgnoreEnd
3123
-                            'event_espresso'
3124
-                        ),
3125
-                        $table_alias,
3126
-                        $field->get_table_alias()
3127
-                    )
3128
-                );
3129
-            }
3130
-        }
3131
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3132
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3133
-        $table_pk_value = $this->ID();
3134
-        $table_name = $table_obj->get_table_name();
3135
-        if ($table_obj instanceof EE_Secondary_Table) {
3136
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3137
-        } else {
3138
-            $table_pk_field_name = $table_obj->get_pk_column();
3139
-        }
3140
-
3141
-        $query =
3142
-            "UPDATE `{$table_name}`
338
+				$this->_props_n_values_provided_in_constructor
339
+				&& $field_value
340
+				&& $field_name === $model->primary_key_name()
341
+			) {
342
+				// if so, we want all this object's fields to be filled either with
343
+				// what we've explicitly set on this model
344
+				// or what we have in the db
345
+				// echo "setting primary key!";
346
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
347
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
348
+				foreach ($fields_on_model as $field_obj) {
349
+					if (
350
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
351
+						&& $field_obj->get_name() !== $field_name
352
+					) {
353
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
354
+					}
355
+				}
356
+				// oh this model object has an ID? well make sure its in the entity mapper
357
+				$model->add_to_entity_map($this);
358
+			}
359
+			// let's unset any cache for this field_name from the $_cached_properties property.
360
+			$this->_clear_cached_property($field_name);
361
+		} else {
362
+			throw new EE_Error(
363
+				sprintf(
364
+					esc_html__(
365
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
366
+						'event_espresso'
367
+					),
368
+					$field_name
369
+				)
370
+			);
371
+		}
372
+	}
373
+
374
+
375
+	/**
376
+	 * Set custom select values for model.
377
+	 *
378
+	 * @param array $custom_select_values
379
+	 */
380
+	public function setCustomSelectsValues(array $custom_select_values)
381
+	{
382
+		$this->custom_selection_results = $custom_select_values;
383
+	}
384
+
385
+
386
+	/**
387
+	 * Returns the custom select value for the provided alias if its set.
388
+	 * If not set, returns null.
389
+	 *
390
+	 * @param string $alias
391
+	 * @return string|int|float|null
392
+	 */
393
+	public function getCustomSelect($alias)
394
+	{
395
+		return isset($this->custom_selection_results[ $alias ])
396
+			? $this->custom_selection_results[ $alias ]
397
+			: null;
398
+	}
399
+
400
+
401
+	/**
402
+	 * This sets the field value on the db column if it exists for the given $column_name or
403
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
404
+	 *
405
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
406
+	 * @param string $field_name  Must be the exact column name.
407
+	 * @param mixed  $field_value The value to set.
408
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
+	 * @throws InvalidArgumentException
410
+	 * @throws InvalidInterfaceException
411
+	 * @throws InvalidDataTypeException
412
+	 * @throws EE_Error
413
+	 * @throws ReflectionException
414
+	 */
415
+	public function set_field_or_extra_meta($field_name, $field_value)
416
+	{
417
+		if ($this->get_model()->has_field($field_name)) {
418
+			$this->set($field_name, $field_value);
419
+			return true;
420
+		}
421
+		// ensure this object is saved first so that extra meta can be properly related.
422
+		$this->save();
423
+		return $this->update_extra_meta($field_name, $field_value);
424
+	}
425
+
426
+
427
+	/**
428
+	 * This retrieves the value of the db column set on this class or if that's not present
429
+	 * it will attempt to retrieve from extra_meta if found.
430
+	 * Example Usage:
431
+	 * Via EE_Message child class:
432
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
433
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
434
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
435
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
436
+	 * value for those extra fields dynamically via the EE_message object.
437
+	 *
438
+	 * @param  string $field_name expecting the fully qualified field name.
439
+	 * @return mixed|null  value for the field if found.  null if not found.
440
+	 * @throws ReflectionException
441
+	 * @throws InvalidArgumentException
442
+	 * @throws InvalidInterfaceException
443
+	 * @throws InvalidDataTypeException
444
+	 * @throws EE_Error
445
+	 */
446
+	public function get_field_or_extra_meta($field_name)
447
+	{
448
+		if ($this->get_model()->has_field($field_name)) {
449
+			$column_value = $this->get($field_name);
450
+		} else {
451
+			// This isn't a column in the main table, let's see if it is in the extra meta.
452
+			$column_value = $this->get_extra_meta($field_name, true, null);
453
+		}
454
+		return $column_value;
455
+	}
456
+
457
+
458
+	/**
459
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
460
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
461
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
462
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
463
+	 *
464
+	 * @access public
465
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
466
+	 * @return void
467
+	 * @throws InvalidArgumentException
468
+	 * @throws InvalidInterfaceException
469
+	 * @throws InvalidDataTypeException
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function set_timezone($timezone = '')
474
+	{
475
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
476
+		// make sure we clear all cached properties because they won't be relevant now
477
+		$this->_clear_cached_properties();
478
+		// make sure we update field settings and the date for all EE_Datetime_Fields
479
+		$model_fields = $this->get_model()->field_settings(false);
480
+		foreach ($model_fields as $field_name => $field_obj) {
481
+			if ($field_obj instanceof EE_Datetime_Field) {
482
+				$field_obj->set_timezone($this->_timezone);
483
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
484
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
485
+				}
486
+			}
487
+		}
488
+	}
489
+
490
+
491
+	/**
492
+	 * This just returns whatever is set for the current timezone.
493
+	 *
494
+	 * @access public
495
+	 * @return string timezone string
496
+	 */
497
+	public function get_timezone()
498
+	{
499
+		return $this->_timezone;
500
+	}
501
+
502
+
503
+	/**
504
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
505
+	 * internally instead of wp set date format options
506
+	 *
507
+	 * @since 4.6
508
+	 * @param string $format should be a format recognizable by PHP date() functions.
509
+	 */
510
+	public function set_date_format($format)
511
+	{
512
+		$this->_dt_frmt = $format;
513
+		// clear cached_properties because they won't be relevant now.
514
+		$this->_clear_cached_properties();
515
+	}
516
+
517
+
518
+	/**
519
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
520
+	 * class internally instead of wp set time format options.
521
+	 *
522
+	 * @since 4.6
523
+	 * @param string $format should be a format recognizable by PHP date() functions.
524
+	 */
525
+	public function set_time_format($format)
526
+	{
527
+		$this->_tm_frmt = $format;
528
+		// clear cached_properties because they won't be relevant now.
529
+		$this->_clear_cached_properties();
530
+	}
531
+
532
+
533
+	/**
534
+	 * This returns the current internal set format for the date and time formats.
535
+	 *
536
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
537
+	 *                             where the first value is the date format and the second value is the time format.
538
+	 * @return mixed string|array
539
+	 */
540
+	public function get_format($full = true)
541
+	{
542
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
543
+	}
544
+
545
+
546
+	/**
547
+	 * cache
548
+	 * stores the passed model object on the current model object.
549
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
550
+	 *
551
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
552
+	 *                                       'Registration' associated with this model object
553
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
554
+	 *                                       that could be a payment or a registration)
555
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
556
+	 *                                       items which will be stored in an array on this object
557
+	 * @throws ReflectionException
558
+	 * @throws InvalidArgumentException
559
+	 * @throws InvalidInterfaceException
560
+	 * @throws InvalidDataTypeException
561
+	 * @throws EE_Error
562
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
563
+	 *                                       related thing, no array)
564
+	 */
565
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
566
+	{
567
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
568
+		if (! $object_to_cache instanceof EE_Base_Class) {
569
+			return false;
570
+		}
571
+		// also get "how" the object is related, or throw an error
572
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
573
+			throw new EE_Error(
574
+				sprintf(
575
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
576
+					$relationName,
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		// how many things are related ?
582
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
583
+			// if it's a "belongs to" relationship, then there's only one related model object
584
+			// eg, if this is a registration, there's only 1 attendee for it
585
+			// so for these model objects just set it to be cached
586
+			$this->_model_relations[ $relationName ] = $object_to_cache;
587
+			$return = true;
588
+		} else {
589
+			// otherwise, this is the "many" side of a one to many relationship,
590
+			// so we'll add the object to the array of related objects for that type.
591
+			// eg: if this is an event, there are many registrations for that event,
592
+			// so we cache the registrations in an array
593
+			if (! is_array($this->_model_relations[ $relationName ])) {
594
+				// if for some reason, the cached item is a model object,
595
+				// then stick that in the array, otherwise start with an empty array
596
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
597
+														   instanceof
598
+														   EE_Base_Class
599
+					? array($this->_model_relations[ $relationName ]) : array();
600
+			}
601
+			// first check for a cache_id which is normally empty
602
+			if (! empty($cache_id)) {
603
+				// if the cache_id exists, then it means we are purposely trying to cache this
604
+				// with a known key that can then be used to retrieve the object later on
605
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
606
+				$return = $cache_id;
607
+			} elseif ($object_to_cache->ID()) {
608
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
609
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
610
+				$return = $object_to_cache->ID();
611
+			} else {
612
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
613
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
614
+				// move the internal pointer to the end of the array
615
+				end($this->_model_relations[ $relationName ]);
616
+				// and grab the key so that we can return it
617
+				$return = key($this->_model_relations[ $relationName ]);
618
+			}
619
+		}
620
+		return $return;
621
+	}
622
+
623
+
624
+	/**
625
+	 * For adding an item to the cached_properties property.
626
+	 *
627
+	 * @access protected
628
+	 * @param string      $fieldname the property item the corresponding value is for.
629
+	 * @param mixed       $value     The value we are caching.
630
+	 * @param string|null $cache_type
631
+	 * @return void
632
+	 * @throws ReflectionException
633
+	 * @throws InvalidArgumentException
634
+	 * @throws InvalidInterfaceException
635
+	 * @throws InvalidDataTypeException
636
+	 * @throws EE_Error
637
+	 */
638
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
639
+	{
640
+		// first make sure this property exists
641
+		$this->get_model()->field_settings_for($fieldname);
642
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
643
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
644
+	}
645
+
646
+
647
+	/**
648
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
649
+	 * This also SETS the cache if we return the actual property!
650
+	 *
651
+	 * @param string $fieldname        the name of the property we're trying to retrieve
652
+	 * @param bool   $pretty
653
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
654
+	 *                                 (in cases where the same property may be used for different outputs
655
+	 *                                 - i.e. datetime, money etc.)
656
+	 *                                 It can also accept certain pre-defined "schema" strings
657
+	 *                                 to define how to output the property.
658
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
659
+	 * @return mixed                   whatever the value for the property is we're retrieving
660
+	 * @throws ReflectionException
661
+	 * @throws InvalidArgumentException
662
+	 * @throws InvalidInterfaceException
663
+	 * @throws InvalidDataTypeException
664
+	 * @throws EE_Error
665
+	 */
666
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
667
+	{
668
+		// verify the field exists
669
+		$model = $this->get_model();
670
+		$model->field_settings_for($fieldname);
671
+		$cache_type = $pretty ? 'pretty' : 'standard';
672
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
673
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
674
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
675
+		}
676
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
677
+		$this->_set_cached_property($fieldname, $value, $cache_type);
678
+		return $value;
679
+	}
680
+
681
+
682
+	/**
683
+	 * If the cache didn't fetch the needed item, this fetches it.
684
+	 *
685
+	 * @param string $fieldname
686
+	 * @param bool   $pretty
687
+	 * @param string $extra_cache_ref
688
+	 * @return mixed
689
+	 * @throws InvalidArgumentException
690
+	 * @throws InvalidInterfaceException
691
+	 * @throws InvalidDataTypeException
692
+	 * @throws EE_Error
693
+	 * @throws ReflectionException
694
+	 */
695
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
696
+	{
697
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
698
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
699
+		if ($field_obj instanceof EE_Datetime_Field) {
700
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
701
+		}
702
+		if (! isset($this->_fields[ $fieldname ])) {
703
+			$this->_fields[ $fieldname ] = null;
704
+		}
705
+		$value = $pretty
706
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
707
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
708
+		return $value;
709
+	}
710
+
711
+
712
+	/**
713
+	 * set timezone, formats, and output for EE_Datetime_Field objects
714
+	 *
715
+	 * @param \EE_Datetime_Field $datetime_field
716
+	 * @param bool               $pretty
717
+	 * @param null               $date_or_time
718
+	 * @return void
719
+	 * @throws InvalidArgumentException
720
+	 * @throws InvalidInterfaceException
721
+	 * @throws InvalidDataTypeException
722
+	 * @throws EE_Error
723
+	 */
724
+	protected function _prepare_datetime_field(
725
+		EE_Datetime_Field $datetime_field,
726
+		$pretty = false,
727
+		$date_or_time = null
728
+	) {
729
+		$datetime_field->set_timezone($this->_timezone);
730
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
731
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
732
+		// set the output returned
733
+		switch ($date_or_time) {
734
+			case 'D':
735
+				$datetime_field->set_date_time_output('date');
736
+				break;
737
+			case 'T':
738
+				$datetime_field->set_date_time_output('time');
739
+				break;
740
+			default:
741
+				$datetime_field->set_date_time_output();
742
+		}
743
+	}
744
+
745
+
746
+	/**
747
+	 * This just takes care of clearing out the cached_properties
748
+	 *
749
+	 * @return void
750
+	 */
751
+	protected function _clear_cached_properties()
752
+	{
753
+		$this->_cached_properties = array();
754
+	}
755
+
756
+
757
+	/**
758
+	 * This just clears out ONE property if it exists in the cache
759
+	 *
760
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
761
+	 * @return void
762
+	 */
763
+	protected function _clear_cached_property($property_name)
764
+	{
765
+		if (isset($this->_cached_properties[ $property_name ])) {
766
+			unset($this->_cached_properties[ $property_name ]);
767
+		}
768
+	}
769
+
770
+
771
+	/**
772
+	 * Ensures that this related thing is a model object.
773
+	 *
774
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
775
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
776
+	 * @return EE_Base_Class
777
+	 * @throws ReflectionException
778
+	 * @throws InvalidArgumentException
779
+	 * @throws InvalidInterfaceException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws EE_Error
782
+	 */
783
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
784
+	{
785
+		$other_model_instance = self::_get_model_instance_with_name(
786
+			self::_get_model_classname($model_name),
787
+			$this->_timezone
788
+		);
789
+		return $other_model_instance->ensure_is_obj($object_or_id);
790
+	}
791
+
792
+
793
+	/**
794
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
795
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
796
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
797
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
798
+	 *
799
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
800
+	 *                                                     Eg 'Registration'
801
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
802
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
803
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
804
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
805
+	 *                                                     this is HasMany or HABTM.
806
+	 * @throws ReflectionException
807
+	 * @throws InvalidArgumentException
808
+	 * @throws InvalidInterfaceException
809
+	 * @throws InvalidDataTypeException
810
+	 * @throws EE_Error
811
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
812
+	 *                                                     relation from all
813
+	 */
814
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
815
+	{
816
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
817
+		$index_in_cache = '';
818
+		if (! $relationship_to_model) {
819
+			throw new EE_Error(
820
+				sprintf(
821
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
822
+					$relationName,
823
+					get_class($this)
824
+				)
825
+			);
826
+		}
827
+		if ($clear_all) {
828
+			$obj_removed = true;
829
+			$this->_model_relations[ $relationName ] = null;
830
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
831
+			$obj_removed = $this->_model_relations[ $relationName ];
832
+			$this->_model_relations[ $relationName ] = null;
833
+		} else {
834
+			if (
835
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
836
+				&& $object_to_remove_or_index_into_array->ID()
837
+			) {
838
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
839
+				if (
840
+					is_array($this->_model_relations[ $relationName ])
841
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
842
+				) {
843
+					$index_found_at = null;
844
+					// find this object in the array even though it has a different key
845
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
846
+						/** @noinspection TypeUnsafeComparisonInspection */
847
+						if (
848
+							$obj instanceof EE_Base_Class
849
+							&& (
850
+								$obj == $object_to_remove_or_index_into_array
851
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
852
+							)
853
+						) {
854
+							$index_found_at = $index;
855
+							break;
856
+						}
857
+					}
858
+					if ($index_found_at) {
859
+						$index_in_cache = $index_found_at;
860
+					} else {
861
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
862
+						// if it wasn't in it to begin with. So we're done
863
+						return $object_to_remove_or_index_into_array;
864
+					}
865
+				}
866
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
867
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
868
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
869
+					/** @noinspection TypeUnsafeComparisonInspection */
870
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
871
+						$index_in_cache = $index;
872
+					}
873
+				}
874
+			} else {
875
+				$index_in_cache = $object_to_remove_or_index_into_array;
876
+			}
877
+			// supposedly we've found it. But it could just be that the client code
878
+			// provided a bad index/object
879
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
880
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
881
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
882
+			} else {
883
+				// that thing was never cached anyways.
884
+				$obj_removed = null;
885
+			}
886
+		}
887
+		return $obj_removed;
888
+	}
889
+
890
+
891
+	/**
892
+	 * update_cache_after_object_save
893
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
894
+	 * obtained after being saved to the db
895
+	 *
896
+	 * @param string        $relationName       - the type of object that is cached
897
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
898
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
899
+	 * @return boolean TRUE on success, FALSE on fail
900
+	 * @throws ReflectionException
901
+	 * @throws InvalidArgumentException
902
+	 * @throws InvalidInterfaceException
903
+	 * @throws InvalidDataTypeException
904
+	 * @throws EE_Error
905
+	 */
906
+	public function update_cache_after_object_save(
907
+		$relationName,
908
+		EE_Base_Class $newly_saved_object,
909
+		$current_cache_id = ''
910
+	) {
911
+		// verify that incoming object is of the correct type
912
+		$obj_class = 'EE_' . $relationName;
913
+		if ($newly_saved_object instanceof $obj_class) {
914
+			/* @type EE_Base_Class $newly_saved_object */
915
+			// now get the type of relation
916
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
917
+			// if this is a 1:1 relationship
918
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
919
+				// then just replace the cached object with the newly saved object
920
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
921
+				return true;
922
+				// or if it's some kind of sordid feral polyamorous relationship...
923
+			}
924
+			if (
925
+				is_array($this->_model_relations[ $relationName ])
926
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
927
+			) {
928
+				// then remove the current cached item
929
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
930
+				// and cache the newly saved object using it's new ID
931
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
932
+				return true;
933
+			}
934
+		}
935
+		return false;
936
+	}
937
+
938
+
939
+	/**
940
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
941
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
942
+	 *
943
+	 * @param string $relationName
944
+	 * @return EE_Base_Class
945
+	 */
946
+	public function get_one_from_cache($relationName)
947
+	{
948
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
949
+			? $this->_model_relations[ $relationName ]
950
+			: null;
951
+		if (is_array($cached_array_or_object)) {
952
+			return array_shift($cached_array_or_object);
953
+		}
954
+		return $cached_array_or_object;
955
+	}
956
+
957
+
958
+	/**
959
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
960
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
961
+	 *
962
+	 * @param string $relationName
963
+	 * @throws ReflectionException
964
+	 * @throws InvalidArgumentException
965
+	 * @throws InvalidInterfaceException
966
+	 * @throws InvalidDataTypeException
967
+	 * @throws EE_Error
968
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
969
+	 */
970
+	public function get_all_from_cache($relationName)
971
+	{
972
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
973
+		// if the result is not an array, but exists, make it an array
974
+		$objects = is_array($objects) ? $objects : array($objects);
975
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
976
+		// basically, if this model object was stored in the session, and these cached model objects
977
+		// already have IDs, let's make sure they're in their model's entity mapper
978
+		// otherwise we will have duplicates next time we call
979
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
980
+		$model = EE_Registry::instance()->load_model($relationName);
981
+		foreach ($objects as $model_object) {
982
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
983
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
984
+				if ($model_object->ID()) {
985
+					$model->add_to_entity_map($model_object);
986
+				}
987
+			} else {
988
+				throw new EE_Error(
989
+					sprintf(
990
+						esc_html__(
991
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
992
+							'event_espresso'
993
+						),
994
+						$relationName,
995
+						gettype($model_object)
996
+					)
997
+				);
998
+			}
999
+		}
1000
+		return $objects;
1001
+	}
1002
+
1003
+
1004
+	/**
1005
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1006
+	 * matching the given query conditions.
1007
+	 *
1008
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1009
+	 * @param int   $limit              How many objects to return.
1010
+	 * @param array $query_params       Any additional conditions on the query.
1011
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1012
+	 *                                  you can indicate just the columns you want returned
1013
+	 * @return array|EE_Base_Class[]
1014
+	 * @throws ReflectionException
1015
+	 * @throws InvalidArgumentException
1016
+	 * @throws InvalidInterfaceException
1017
+	 * @throws InvalidDataTypeException
1018
+	 * @throws EE_Error
1019
+	 */
1020
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1021
+	{
1022
+		$model = $this->get_model();
1023
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1024
+			? $model->get_primary_key_field()->get_name()
1025
+			: $field_to_order_by;
1026
+		$current_value = ! empty($field) ? $this->get($field) : null;
1027
+		if (empty($field) || empty($current_value)) {
1028
+			return array();
1029
+		}
1030
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1031
+	}
1032
+
1033
+
1034
+	/**
1035
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1036
+	 * matching the given query conditions.
1037
+	 *
1038
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1039
+	 * @param int   $limit              How many objects to return.
1040
+	 * @param array $query_params       Any additional conditions on the query.
1041
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1042
+	 *                                  you can indicate just the columns you want returned
1043
+	 * @return array|EE_Base_Class[]
1044
+	 * @throws ReflectionException
1045
+	 * @throws InvalidArgumentException
1046
+	 * @throws InvalidInterfaceException
1047
+	 * @throws InvalidDataTypeException
1048
+	 * @throws EE_Error
1049
+	 */
1050
+	public function previous_x(
1051
+		$field_to_order_by = null,
1052
+		$limit = 1,
1053
+		$query_params = array(),
1054
+		$columns_to_select = null
1055
+	) {
1056
+		$model = $this->get_model();
1057
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1058
+			? $model->get_primary_key_field()->get_name()
1059
+			: $field_to_order_by;
1060
+		$current_value = ! empty($field) ? $this->get($field) : null;
1061
+		if (empty($field) || empty($current_value)) {
1062
+			return array();
1063
+		}
1064
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1070
+	 * matching the given query conditions.
1071
+	 *
1072
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1073
+	 * @param array $query_params       Any additional conditions on the query.
1074
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1075
+	 *                                  you can indicate just the columns you want returned
1076
+	 * @return array|EE_Base_Class
1077
+	 * @throws ReflectionException
1078
+	 * @throws InvalidArgumentException
1079
+	 * @throws InvalidInterfaceException
1080
+	 * @throws InvalidDataTypeException
1081
+	 * @throws EE_Error
1082
+	 */
1083
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1084
+	{
1085
+		$model = $this->get_model();
1086
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1087
+			? $model->get_primary_key_field()->get_name()
1088
+			: $field_to_order_by;
1089
+		$current_value = ! empty($field) ? $this->get($field) : null;
1090
+		if (empty($field) || empty($current_value)) {
1091
+			return array();
1092
+		}
1093
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1094
+	}
1095
+
1096
+
1097
+	/**
1098
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1099
+	 * matching the given query conditions.
1100
+	 *
1101
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1102
+	 * @param array $query_params       Any additional conditions on the query.
1103
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1104
+	 *                                  you can indicate just the column you want returned
1105
+	 * @return array|EE_Base_Class
1106
+	 * @throws ReflectionException
1107
+	 * @throws InvalidArgumentException
1108
+	 * @throws InvalidInterfaceException
1109
+	 * @throws InvalidDataTypeException
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1113
+	{
1114
+		$model = $this->get_model();
1115
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1116
+			? $model->get_primary_key_field()->get_name()
1117
+			: $field_to_order_by;
1118
+		$current_value = ! empty($field) ? $this->get($field) : null;
1119
+		if (empty($field) || empty($current_value)) {
1120
+			return array();
1121
+		}
1122
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * Overrides parent because parent expects old models.
1128
+	 * This also doesn't do any validation, and won't work for serialized arrays
1129
+	 *
1130
+	 * @param string $field_name
1131
+	 * @param mixed  $field_value_from_db
1132
+	 * @throws ReflectionException
1133
+	 * @throws InvalidArgumentException
1134
+	 * @throws InvalidInterfaceException
1135
+	 * @throws InvalidDataTypeException
1136
+	 * @throws EE_Error
1137
+	 */
1138
+	public function set_from_db($field_name, $field_value_from_db)
1139
+	{
1140
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1141
+		if ($field_obj instanceof EE_Model_Field_Base) {
1142
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1143
+			// eg, a CPT model object could have an entry in the posts table, but no
1144
+			// entry in the meta table. Meaning that all its columns in the meta table
1145
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1146
+			if ($field_value_from_db === null) {
1147
+				if ($field_obj->is_nullable()) {
1148
+					// if the field allows nulls, then let it be null
1149
+					$field_value = null;
1150
+				} else {
1151
+					$field_value = $field_obj->get_default_value();
1152
+				}
1153
+			} else {
1154
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1155
+			}
1156
+			$this->_fields[ $field_name ] = $field_value;
1157
+			$this->_clear_cached_property($field_name);
1158
+		}
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * verifies that the specified field is of the correct type
1164
+	 *
1165
+	 * @param string $field_name
1166
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
+	 *                                (in cases where the same property may be used for different outputs
1168
+	 *                                - i.e. datetime, money etc.)
1169
+	 * @return mixed
1170
+	 * @throws ReflectionException
1171
+	 * @throws InvalidArgumentException
1172
+	 * @throws InvalidInterfaceException
1173
+	 * @throws InvalidDataTypeException
1174
+	 * @throws EE_Error
1175
+	 */
1176
+	public function get($field_name, $extra_cache_ref = null)
1177
+	{
1178
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1179
+	}
1180
+
1181
+
1182
+	/**
1183
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1184
+	 *
1185
+	 * @param  string $field_name A valid fieldname
1186
+	 * @return mixed              Whatever the raw value stored on the property is.
1187
+	 * @throws ReflectionException
1188
+	 * @throws InvalidArgumentException
1189
+	 * @throws InvalidInterfaceException
1190
+	 * @throws InvalidDataTypeException
1191
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1192
+	 */
1193
+	public function get_raw($field_name)
1194
+	{
1195
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1196
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1197
+			? $this->_fields[ $field_name ]->format('U')
1198
+			: $this->_fields[ $field_name ];
1199
+	}
1200
+
1201
+
1202
+	/**
1203
+	 * This is used to return the internal DateTime object used for a field that is a
1204
+	 * EE_Datetime_Field.
1205
+	 *
1206
+	 * @param string $field_name               The field name retrieving the DateTime object.
1207
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1208
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1209
+	 *                                         EE_Datetime_Field and but the field value is null, then
1210
+	 *                                         just null is returned (because that indicates that likely
1211
+	 *                                         this field is nullable).
1212
+	 * @throws InvalidArgumentException
1213
+	 * @throws InvalidDataTypeException
1214
+	 * @throws InvalidInterfaceException
1215
+	 * @throws ReflectionException
1216
+	 */
1217
+	public function get_DateTime_object($field_name)
1218
+	{
1219
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1220
+		if (! $field_settings instanceof EE_Datetime_Field) {
1221
+			EE_Error::add_error(
1222
+				sprintf(
1223
+					esc_html__(
1224
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1225
+						'event_espresso'
1226
+					),
1227
+					$field_name
1228
+				),
1229
+				__FILE__,
1230
+				__FUNCTION__,
1231
+				__LINE__
1232
+			);
1233
+			return false;
1234
+		}
1235
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1236
+			? clone $this->_fields[ $field_name ]
1237
+			: null;
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 * To be used in template to immediately echo out the value, and format it for output.
1243
+	 * Eg, should call stripslashes and whatnot before echoing
1244
+	 *
1245
+	 * @param string $field_name      the name of the field as it appears in the DB
1246
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1247
+	 *                                (in cases where the same property may be used for different outputs
1248
+	 *                                - i.e. datetime, money etc.)
1249
+	 * @return void
1250
+	 * @throws ReflectionException
1251
+	 * @throws InvalidArgumentException
1252
+	 * @throws InvalidInterfaceException
1253
+	 * @throws InvalidDataTypeException
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function e($field_name, $extra_cache_ref = null)
1257
+	{
1258
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1264
+	 * can be easily used as the value of form input.
1265
+	 *
1266
+	 * @param string $field_name
1267
+	 * @return void
1268
+	 * @throws ReflectionException
1269
+	 * @throws InvalidArgumentException
1270
+	 * @throws InvalidInterfaceException
1271
+	 * @throws InvalidDataTypeException
1272
+	 * @throws EE_Error
1273
+	 */
1274
+	public function f($field_name)
1275
+	{
1276
+		$this->e($field_name, 'form_input');
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * Same as `f()` but just returns the value instead of echoing it
1282
+	 *
1283
+	 * @param string $field_name
1284
+	 * @return string
1285
+	 * @throws ReflectionException
1286
+	 * @throws InvalidArgumentException
1287
+	 * @throws InvalidInterfaceException
1288
+	 * @throws InvalidDataTypeException
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public function get_f($field_name)
1292
+	{
1293
+		return (string) $this->get_pretty($field_name, 'form_input');
1294
+	}
1295
+
1296
+
1297
+	/**
1298
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1299
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1300
+	 * to see what options are available.
1301
+	 *
1302
+	 * @param string $field_name
1303
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1304
+	 *                                (in cases where the same property may be used for different outputs
1305
+	 *                                - i.e. datetime, money etc.)
1306
+	 * @return mixed
1307
+	 * @throws ReflectionException
1308
+	 * @throws InvalidArgumentException
1309
+	 * @throws InvalidInterfaceException
1310
+	 * @throws InvalidDataTypeException
1311
+	 * @throws EE_Error
1312
+	 */
1313
+	public function get_pretty($field_name, $extra_cache_ref = null)
1314
+	{
1315
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1316
+	}
1317
+
1318
+
1319
+	/**
1320
+	 * This simply returns the datetime for the given field name
1321
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1322
+	 * (and the equivalent e_date, e_time, e_datetime).
1323
+	 *
1324
+	 * @access   protected
1325
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1326
+	 * @param string   $dt_frmt      valid datetime format used for date
1327
+	 *                               (if '' then we just use the default on the field,
1328
+	 *                               if NULL we use the last-used format)
1329
+	 * @param string   $tm_frmt      Same as above except this is for time format
1330
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1331
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1332
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1333
+	 *                               if field is not a valid dtt field, or void if echoing
1334
+	 * @throws ReflectionException
1335
+	 * @throws InvalidArgumentException
1336
+	 * @throws InvalidInterfaceException
1337
+	 * @throws InvalidDataTypeException
1338
+	 * @throws EE_Error
1339
+	 */
1340
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1341
+	{
1342
+		// clear cached property
1343
+		$this->_clear_cached_property($field_name);
1344
+		// reset format properties because they are used in get()
1345
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1346
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1347
+		if ($echo) {
1348
+			$this->e($field_name, $date_or_time);
1349
+			return '';
1350
+		}
1351
+		return $this->get($field_name, $date_or_time);
1352
+	}
1353
+
1354
+
1355
+	/**
1356
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1357
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1358
+	 * other echoes the pretty value for dtt)
1359
+	 *
1360
+	 * @param  string $field_name name of model object datetime field holding the value
1361
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1362
+	 * @return string            datetime value formatted
1363
+	 * @throws ReflectionException
1364
+	 * @throws InvalidArgumentException
1365
+	 * @throws InvalidInterfaceException
1366
+	 * @throws InvalidDataTypeException
1367
+	 * @throws EE_Error
1368
+	 */
1369
+	public function get_date($field_name, $format = '')
1370
+	{
1371
+		return $this->_get_datetime($field_name, $format, null, 'D');
1372
+	}
1373
+
1374
+
1375
+	/**
1376
+	 * @param        $field_name
1377
+	 * @param string $format
1378
+	 * @throws ReflectionException
1379
+	 * @throws InvalidArgumentException
1380
+	 * @throws InvalidInterfaceException
1381
+	 * @throws InvalidDataTypeException
1382
+	 * @throws EE_Error
1383
+	 */
1384
+	public function e_date($field_name, $format = '')
1385
+	{
1386
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1387
+	}
1388
+
1389
+
1390
+	/**
1391
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1392
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1393
+	 * other echoes the pretty value for dtt)
1394
+	 *
1395
+	 * @param  string $field_name name of model object datetime field holding the value
1396
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1397
+	 * @return string             datetime value formatted
1398
+	 * @throws ReflectionException
1399
+	 * @throws InvalidArgumentException
1400
+	 * @throws InvalidInterfaceException
1401
+	 * @throws InvalidDataTypeException
1402
+	 * @throws EE_Error
1403
+	 */
1404
+	public function get_time($field_name, $format = '')
1405
+	{
1406
+		return $this->_get_datetime($field_name, null, $format, 'T');
1407
+	}
1408
+
1409
+
1410
+	/**
1411
+	 * @param        $field_name
1412
+	 * @param string $format
1413
+	 * @throws ReflectionException
1414
+	 * @throws InvalidArgumentException
1415
+	 * @throws InvalidInterfaceException
1416
+	 * @throws InvalidDataTypeException
1417
+	 * @throws EE_Error
1418
+	 */
1419
+	public function e_time($field_name, $format = '')
1420
+	{
1421
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1422
+	}
1423
+
1424
+
1425
+	/**
1426
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1427
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1428
+	 * other echoes the pretty value for dtt)
1429
+	 *
1430
+	 * @param  string $field_name name of model object datetime field holding the value
1431
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1432
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1433
+	 * @return string             datetime value formatted
1434
+	 * @throws ReflectionException
1435
+	 * @throws InvalidArgumentException
1436
+	 * @throws InvalidInterfaceException
1437
+	 * @throws InvalidDataTypeException
1438
+	 * @throws EE_Error
1439
+	 */
1440
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1441
+	{
1442
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1443
+	}
1444
+
1445
+
1446
+	/**
1447
+	 * @param string $field_name
1448
+	 * @param string $dt_frmt
1449
+	 * @param string $tm_frmt
1450
+	 * @throws ReflectionException
1451
+	 * @throws InvalidArgumentException
1452
+	 * @throws InvalidInterfaceException
1453
+	 * @throws InvalidDataTypeException
1454
+	 * @throws EE_Error
1455
+	 */
1456
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1457
+	{
1458
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1459
+	}
1460
+
1461
+
1462
+	/**
1463
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1464
+	 *
1465
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1466
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1467
+	 *                           on the object will be used.
1468
+	 * @return string Date and time string in set locale or false if no field exists for the given
1469
+	 * @throws ReflectionException
1470
+	 * @throws InvalidArgumentException
1471
+	 * @throws InvalidInterfaceException
1472
+	 * @throws InvalidDataTypeException
1473
+	 * @throws EE_Error
1474
+	 *                           field name.
1475
+	 */
1476
+	public function get_i18n_datetime($field_name, $format = '')
1477
+	{
1478
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1479
+		return date_i18n(
1480
+			$format,
1481
+			EEH_DTT_Helper::get_timestamp_with_offset(
1482
+				$this->get_raw($field_name),
1483
+				$this->_timezone
1484
+			)
1485
+		);
1486
+	}
1487
+
1488
+
1489
+	/**
1490
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1491
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1492
+	 * thrown.
1493
+	 *
1494
+	 * @param  string $field_name The field name being checked
1495
+	 * @throws ReflectionException
1496
+	 * @throws InvalidArgumentException
1497
+	 * @throws InvalidInterfaceException
1498
+	 * @throws InvalidDataTypeException
1499
+	 * @throws EE_Error
1500
+	 * @return EE_Datetime_Field
1501
+	 */
1502
+	protected function _get_dtt_field_settings($field_name)
1503
+	{
1504
+		$field = $this->get_model()->field_settings_for($field_name);
1505
+		// check if field is dtt
1506
+		if ($field instanceof EE_Datetime_Field) {
1507
+			return $field;
1508
+		}
1509
+		throw new EE_Error(
1510
+			sprintf(
1511
+				esc_html__(
1512
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1513
+					'event_espresso'
1514
+				),
1515
+				$field_name,
1516
+				self::_get_model_classname(get_class($this))
1517
+			)
1518
+		);
1519
+	}
1520
+
1521
+
1522
+
1523
+
1524
+	/**
1525
+	 * NOTE ABOUT BELOW:
1526
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1527
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1528
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1529
+	 * method and make sure you send the entire datetime value for setting.
1530
+	 */
1531
+	/**
1532
+	 * sets the time on a datetime property
1533
+	 *
1534
+	 * @access protected
1535
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1536
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1537
+	 * @throws ReflectionException
1538
+	 * @throws InvalidArgumentException
1539
+	 * @throws InvalidInterfaceException
1540
+	 * @throws InvalidDataTypeException
1541
+	 * @throws EE_Error
1542
+	 */
1543
+	protected function _set_time_for($time, $fieldname)
1544
+	{
1545
+		$this->_set_date_time('T', $time, $fieldname);
1546
+	}
1547
+
1548
+
1549
+	/**
1550
+	 * sets the date on a datetime property
1551
+	 *
1552
+	 * @access protected
1553
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1554
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1555
+	 * @throws ReflectionException
1556
+	 * @throws InvalidArgumentException
1557
+	 * @throws InvalidInterfaceException
1558
+	 * @throws InvalidDataTypeException
1559
+	 * @throws EE_Error
1560
+	 */
1561
+	protected function _set_date_for($date, $fieldname)
1562
+	{
1563
+		$this->_set_date_time('D', $date, $fieldname);
1564
+	}
1565
+
1566
+
1567
+	/**
1568
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1569
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1570
+	 *
1571
+	 * @access protected
1572
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1573
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1574
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1575
+	 *                                        EE_Datetime_Field property)
1576
+	 * @throws ReflectionException
1577
+	 * @throws InvalidArgumentException
1578
+	 * @throws InvalidInterfaceException
1579
+	 * @throws InvalidDataTypeException
1580
+	 * @throws EE_Error
1581
+	 */
1582
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1583
+	{
1584
+		$field = $this->_get_dtt_field_settings($fieldname);
1585
+		$field->set_timezone($this->_timezone);
1586
+		$field->set_date_format($this->_dt_frmt);
1587
+		$field->set_time_format($this->_tm_frmt);
1588
+		switch ($what) {
1589
+			case 'T':
1590
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1591
+					$datetime_value,
1592
+					$this->_fields[ $fieldname ]
1593
+				);
1594
+				$this->_has_changes = true;
1595
+				break;
1596
+			case 'D':
1597
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1598
+					$datetime_value,
1599
+					$this->_fields[ $fieldname ]
1600
+				);
1601
+				$this->_has_changes = true;
1602
+				break;
1603
+			case 'B':
1604
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1605
+				$this->_has_changes = true;
1606
+				break;
1607
+		}
1608
+		$this->_clear_cached_property($fieldname);
1609
+	}
1610
+
1611
+
1612
+	/**
1613
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1614
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1615
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1616
+	 * that could lead to some unexpected results!
1617
+	 *
1618
+	 * @access public
1619
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1620
+	 *                                         value being returned.
1621
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1622
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1623
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1624
+	 * @param string $append                   You can include something to append on the timestamp
1625
+	 * @throws ReflectionException
1626
+	 * @throws InvalidArgumentException
1627
+	 * @throws InvalidInterfaceException
1628
+	 * @throws InvalidDataTypeException
1629
+	 * @throws EE_Error
1630
+	 * @return string timestamp
1631
+	 */
1632
+	public function display_in_my_timezone(
1633
+		$field_name,
1634
+		$callback = 'get_datetime',
1635
+		$args = null,
1636
+		$prepend = '',
1637
+		$append = ''
1638
+	) {
1639
+		$timezone = EEH_DTT_Helper::get_timezone();
1640
+		if ($timezone === $this->_timezone) {
1641
+			return '';
1642
+		}
1643
+		$original_timezone = $this->_timezone;
1644
+		$this->set_timezone($timezone);
1645
+		$fn = (array) $field_name;
1646
+		$args = array_merge($fn, (array) $args);
1647
+		if (! method_exists($this, $callback)) {
1648
+			throw new EE_Error(
1649
+				sprintf(
1650
+					esc_html__(
1651
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1652
+						'event_espresso'
1653
+					),
1654
+					$callback
1655
+				)
1656
+			);
1657
+		}
1658
+		$args = (array) $args;
1659
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
+		$this->set_timezone($original_timezone);
1661
+		return $return;
1662
+	}
1663
+
1664
+
1665
+	/**
1666
+	 * Deletes this model object.
1667
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1668
+	 * override
1669
+	 * `EE_Base_Class::_delete` NOT this class.
1670
+	 *
1671
+	 * @return boolean | int
1672
+	 * @throws ReflectionException
1673
+	 * @throws InvalidArgumentException
1674
+	 * @throws InvalidInterfaceException
1675
+	 * @throws InvalidDataTypeException
1676
+	 * @throws EE_Error
1677
+	 */
1678
+	public function delete()
1679
+	{
1680
+		/**
1681
+		 * Called just before the `EE_Base_Class::_delete` method call.
1682
+		 * Note:
1683
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1684
+		 * should be aware that `_delete` may not always result in a permanent delete.
1685
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1686
+		 * soft deletes (trash) the object and does not permanently delete it.
1687
+		 *
1688
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1689
+		 */
1690
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1691
+		$result = $this->_delete();
1692
+		/**
1693
+		 * Called just after the `EE_Base_Class::_delete` method call.
1694
+		 * Note:
1695
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1696
+		 * should be aware that `_delete` may not always result in a permanent delete.
1697
+		 * For example `EE_Soft_Base_Class::_delete`
1698
+		 * soft deletes (trash) the object and does not permanently delete it.
1699
+		 *
1700
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1701
+		 * @param boolean       $result
1702
+		 */
1703
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1704
+		return $result;
1705
+	}
1706
+
1707
+
1708
+	/**
1709
+	 * Calls the specific delete method for the instantiated class.
1710
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1711
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1712
+	 * `EE_Base_Class::delete`
1713
+	 *
1714
+	 * @return bool|int
1715
+	 * @throws ReflectionException
1716
+	 * @throws InvalidArgumentException
1717
+	 * @throws InvalidInterfaceException
1718
+	 * @throws InvalidDataTypeException
1719
+	 * @throws EE_Error
1720
+	 */
1721
+	protected function _delete()
1722
+	{
1723
+		return $this->delete_permanently();
1724
+	}
1725
+
1726
+
1727
+	/**
1728
+	 * Deletes this model object permanently from db
1729
+	 * (but keep in mind related models may block the delete and return an error)
1730
+	 *
1731
+	 * @return bool | int
1732
+	 * @throws ReflectionException
1733
+	 * @throws InvalidArgumentException
1734
+	 * @throws InvalidInterfaceException
1735
+	 * @throws InvalidDataTypeException
1736
+	 * @throws EE_Error
1737
+	 */
1738
+	public function delete_permanently()
1739
+	{
1740
+		/**
1741
+		 * Called just before HARD deleting a model object
1742
+		 *
1743
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1744
+		 */
1745
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1746
+		$model = $this->get_model();
1747
+		$result = $model->delete_permanently_by_ID($this->ID());
1748
+		$this->refresh_cache_of_related_objects();
1749
+		/**
1750
+		 * Called just after HARD deleting a model object
1751
+		 *
1752
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1753
+		 * @param boolean       $result
1754
+		 */
1755
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1756
+		return $result;
1757
+	}
1758
+
1759
+
1760
+	/**
1761
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1762
+	 * related model objects
1763
+	 *
1764
+	 * @throws ReflectionException
1765
+	 * @throws InvalidArgumentException
1766
+	 * @throws InvalidInterfaceException
1767
+	 * @throws InvalidDataTypeException
1768
+	 * @throws EE_Error
1769
+	 */
1770
+	public function refresh_cache_of_related_objects()
1771
+	{
1772
+		$model = $this->get_model();
1773
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1774
+			if (! empty($this->_model_relations[ $relation_name ])) {
1775
+				$related_objects = $this->_model_relations[ $relation_name ];
1776
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1777
+					// this relation only stores a single model object, not an array
1778
+					// but let's make it consistent
1779
+					$related_objects = array($related_objects);
1780
+				}
1781
+				foreach ($related_objects as $related_object) {
1782
+					// only refresh their cache if they're in memory
1783
+					if ($related_object instanceof EE_Base_Class) {
1784
+						$related_object->clear_cache(
1785
+							$model->get_this_model_name(),
1786
+							$this
1787
+						);
1788
+					}
1789
+				}
1790
+			}
1791
+		}
1792
+	}
1793
+
1794
+
1795
+	/**
1796
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1797
+	 * object just before saving.
1798
+	 *
1799
+	 * @access public
1800
+	 * @param array $set_cols_n_values  keys are field names, values are their new values,
1801
+	 *                                  if provided during the save() method
1802
+	 *                                  (often client code will change the fields' values before calling save)
1803
+	 * @return false|int|string         1 on a successful update;
1804
+	 *                                  the ID of the new entry on insert;
1805
+	 *                                  0 on failure, or if the model object isn't allowed to persist
1806
+	 *                                  (as determined by EE_Base_Class::allow_persist())
1807
+	 * @throws InvalidInterfaceException
1808
+	 * @throws InvalidDataTypeException
1809
+	 * @throws EE_Error
1810
+	 * @throws InvalidArgumentException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 * @throws ReflectionException
1814
+	 */
1815
+	public function save($set_cols_n_values = array())
1816
+	{
1817
+		$model = $this->get_model();
1818
+		/**
1819
+		 * Filters the fields we're about to save on the model object
1820
+		 *
1821
+		 * @param array         $set_cols_n_values
1822
+		 * @param EE_Base_Class $model_object
1823
+		 */
1824
+		$set_cols_n_values = (array) apply_filters(
1825
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1826
+			$set_cols_n_values,
1827
+			$this
1828
+		);
1829
+		// set attributes as provided in $set_cols_n_values
1830
+		foreach ($set_cols_n_values as $column => $value) {
1831
+			$this->set($column, $value);
1832
+		}
1833
+		// no changes ? then don't do anything
1834
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
+			return 0;
1836
+		}
1837
+		/**
1838
+		 * Saving a model object.
1839
+		 * Before we perform a save, this action is fired.
1840
+		 *
1841
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1842
+		 */
1843
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1844
+		if (! $this->allow_persist()) {
1845
+			return 0;
1846
+		}
1847
+		// now get current attribute values
1848
+		$save_cols_n_values = $this->_fields;
1849
+		// if the object already has an ID, update it. Otherwise, insert it
1850
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1851
+		// They have been
1852
+		$old_assumption_concerning_value_preparation = $model
1853
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1854
+		$model->assume_values_already_prepared_by_model_object(true);
1855
+		// does this model have an autoincrement PK?
1856
+		if ($model->has_primary_key_field()) {
1857
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1858
+				// ok check if it's set, if so: update; if not, insert
1859
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1861
+				} else {
1862
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
+					$results = $model->insert($save_cols_n_values);
1864
+					if ($results) {
1865
+						// if successful, set the primary key
1866
+						// but don't use the normal SET method, because it will check if
1867
+						// an item with the same ID exists in the mapper & db, then
1868
+						// will find it in the db (because we just added it) and THAT object
1869
+						// will get added to the mapper before we can add this one!
1870
+						// but if we just avoid using the SET method, all that headache can be avoided
1871
+						$pk_field_name = $model->primary_key_name();
1872
+						$this->_fields[ $pk_field_name ] = $results;
1873
+						$this->_clear_cached_property($pk_field_name);
1874
+						$model->add_to_entity_map($this);
1875
+						$this->_update_cached_related_model_objs_fks();
1876
+					}
1877
+				}
1878
+			} else {// PK is NOT auto-increment
1879
+				// so check if one like it already exists in the db
1880
+				if ($model->exists_by_ID($this->ID())) {
1881
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1882
+						throw new EE_Error(
1883
+							sprintf(
1884
+								esc_html__(
1885
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1886
+									'event_espresso'
1887
+								),
1888
+								get_class($this),
1889
+								get_class($model) . '::instance()->add_to_entity_map()',
1890
+								get_class($model) . '::instance()->get_one_by_ID()',
1891
+								'<br />'
1892
+							)
1893
+						);
1894
+					}
1895
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1896
+				} else {
1897
+					$results = $model->insert($save_cols_n_values);
1898
+					$this->_update_cached_related_model_objs_fks();
1899
+				}
1900
+			}
1901
+		} else {// there is NO primary key
1902
+			$already_in_db = false;
1903
+			foreach ($model->unique_indexes() as $index) {
1904
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1905
+				if ($model->exists(array($uniqueness_where_params))) {
1906
+					$already_in_db = true;
1907
+				}
1908
+			}
1909
+			if ($already_in_db) {
1910
+				$combined_pk_fields_n_values = array_intersect_key(
1911
+					$save_cols_n_values,
1912
+					$model->get_combined_primary_key_fields()
1913
+				);
1914
+				$results = $model->update(
1915
+					$save_cols_n_values,
1916
+					$combined_pk_fields_n_values
1917
+				);
1918
+			} else {
1919
+				$results = $model->insert($save_cols_n_values);
1920
+			}
1921
+		}
1922
+		// restore the old assumption about values being prepared by the model object
1923
+		$model->assume_values_already_prepared_by_model_object(
1924
+			$old_assumption_concerning_value_preparation
1925
+		);
1926
+		/**
1927
+		 * After saving the model object this action is called
1928
+		 *
1929
+		 * @param EE_Base_Class $model_object which was just saved
1930
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1931
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1932
+		 */
1933
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1934
+		$this->_has_changes = false;
1935
+		return $results;
1936
+	}
1937
+
1938
+
1939
+	/**
1940
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1941
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1942
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1943
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1944
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1945
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1946
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1947
+	 *
1948
+	 * @return void
1949
+	 * @throws ReflectionException
1950
+	 * @throws InvalidArgumentException
1951
+	 * @throws InvalidInterfaceException
1952
+	 * @throws InvalidDataTypeException
1953
+	 * @throws EE_Error
1954
+	 */
1955
+	protected function _update_cached_related_model_objs_fks()
1956
+	{
1957
+		$model = $this->get_model();
1958
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1959
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1960
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1961
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1962
+						$model->get_this_model_name()
1963
+					);
1964
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1965
+					if ($related_model_obj_in_cache->ID()) {
1966
+						$related_model_obj_in_cache->save();
1967
+					}
1968
+				}
1969
+			}
1970
+		}
1971
+	}
1972
+
1973
+
1974
+	/**
1975
+	 * Saves this model object and its NEW cached relations to the database.
1976
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1977
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1978
+	 * because otherwise, there's a potential for infinite looping of saving
1979
+	 * Saves the cached related model objects, and ensures the relation between them
1980
+	 * and this object and properly setup
1981
+	 *
1982
+	 * @return int ID of new model object on save; 0 on failure+
1983
+	 * @throws ReflectionException
1984
+	 * @throws InvalidArgumentException
1985
+	 * @throws InvalidInterfaceException
1986
+	 * @throws InvalidDataTypeException
1987
+	 * @throws EE_Error
1988
+	 */
1989
+	public function save_new_cached_related_model_objs()
1990
+	{
1991
+		// make sure this has been saved
1992
+		if (! $this->ID()) {
1993
+			$id = $this->save();
1994
+		} else {
1995
+			$id = $this->ID();
1996
+		}
1997
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1998
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1999
+			if ($this->_model_relations[ $relationName ]) {
2000
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2001
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2002
+				/* @var $related_model_obj EE_Base_Class */
2003
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2004
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2005
+					// but ONLY if it DOES NOT exist in the DB
2006
+					$related_model_obj = $this->_model_relations[ $relationName ];
2007
+					// if( ! $related_model_obj->ID()){
2008
+					$this->_add_relation_to($related_model_obj, $relationName);
2009
+					$related_model_obj->save_new_cached_related_model_objs();
2010
+					// }
2011
+				} else {
2012
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2014
+						// but ONLY if it DOES NOT exist in the DB
2015
+						// if( ! $related_model_obj->ID()){
2016
+						$this->_add_relation_to($related_model_obj, $relationName);
2017
+						$related_model_obj->save_new_cached_related_model_objs();
2018
+						// }
2019
+					}
2020
+				}
2021
+			}
2022
+		}
2023
+		return $id;
2024
+	}
2025
+
2026
+
2027
+	/**
2028
+	 * for getting a model while instantiated.
2029
+	 *
2030
+	 * @return EEM_Base | EEM_CPT_Base
2031
+	 * @throws ReflectionException
2032
+	 * @throws InvalidArgumentException
2033
+	 * @throws InvalidInterfaceException
2034
+	 * @throws InvalidDataTypeException
2035
+	 * @throws EE_Error
2036
+	 */
2037
+	public function get_model()
2038
+	{
2039
+		if (! $this->_model) {
2040
+			$modelName = self::_get_model_classname(get_class($this));
2041
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2042
+		} else {
2043
+			$this->_model->set_timezone($this->_timezone);
2044
+		}
2045
+		return $this->_model;
2046
+	}
2047
+
2048
+
2049
+	/**
2050
+	 * @param $props_n_values
2051
+	 * @param $classname
2052
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2053
+	 * @throws ReflectionException
2054
+	 * @throws InvalidArgumentException
2055
+	 * @throws InvalidInterfaceException
2056
+	 * @throws InvalidDataTypeException
2057
+	 * @throws EE_Error
2058
+	 */
2059
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2060
+	{
2061
+		// TODO: will not work for Term_Relationships because they have no PK!
2062
+		$primary_id_ref = self::_get_primary_key_name($classname);
2063
+		if (
2064
+			array_key_exists($primary_id_ref, $props_n_values)
2065
+			&& ! empty($props_n_values[ $primary_id_ref ])
2066
+		) {
2067
+			$id = $props_n_values[ $primary_id_ref ];
2068
+			return self::_get_model($classname)->get_from_entity_map($id);
2069
+		}
2070
+		return false;
2071
+	}
2072
+
2073
+
2074
+	/**
2075
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2076
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2077
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2078
+	 * we return false.
2079
+	 *
2080
+	 * @param  array  $props_n_values   incoming array of properties and their values
2081
+	 * @param  string $classname        the classname of the child class
2082
+	 * @param null    $timezone
2083
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2084
+	 *                                  date_format and the second value is the time format
2085
+	 * @return mixed (EE_Base_Class|bool)
2086
+	 * @throws InvalidArgumentException
2087
+	 * @throws InvalidInterfaceException
2088
+	 * @throws InvalidDataTypeException
2089
+	 * @throws EE_Error
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 * @throws ReflectionException
2093
+	 */
2094
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2095
+	{
2096
+		$existing = null;
2097
+		$model = self::_get_model($classname, $timezone);
2098
+		if ($model->has_primary_key_field()) {
2099
+			$primary_id_ref = self::_get_primary_key_name($classname);
2100
+			if (
2101
+				array_key_exists($primary_id_ref, $props_n_values)
2102
+				&& ! empty($props_n_values[ $primary_id_ref ])
2103
+			) {
2104
+				$existing = $model->get_one_by_ID(
2105
+					$props_n_values[ $primary_id_ref ]
2106
+				);
2107
+			}
2108
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2109
+			// no primary key on this model, but there's still a matching item in the DB
2110
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2111
+				self::_get_model($classname, $timezone)
2112
+					->get_index_primary_key_string($props_n_values)
2113
+			);
2114
+		}
2115
+		if ($existing) {
2116
+			// set date formats if present before setting values
2117
+			if (! empty($date_formats) && is_array($date_formats)) {
2118
+				$existing->set_date_format($date_formats[0]);
2119
+				$existing->set_time_format($date_formats[1]);
2120
+			} else {
2121
+				// set default formats for date and time
2122
+				$existing->set_date_format(get_option('date_format'));
2123
+				$existing->set_time_format(get_option('time_format'));
2124
+			}
2125
+			foreach ($props_n_values as $property => $field_value) {
2126
+				$existing->set($property, $field_value);
2127
+			}
2128
+			return $existing;
2129
+		}
2130
+		return false;
2131
+	}
2132
+
2133
+
2134
+	/**
2135
+	 * Gets the EEM_*_Model for this class
2136
+	 *
2137
+	 * @access public now, as this is more convenient
2138
+	 * @param      $classname
2139
+	 * @param null $timezone
2140
+	 * @throws ReflectionException
2141
+	 * @throws InvalidArgumentException
2142
+	 * @throws InvalidInterfaceException
2143
+	 * @throws InvalidDataTypeException
2144
+	 * @throws EE_Error
2145
+	 * @return EEM_Base
2146
+	 */
2147
+	protected static function _get_model($classname, $timezone = null)
2148
+	{
2149
+		// find model for this class
2150
+		if (! $classname) {
2151
+			throw new EE_Error(
2152
+				sprintf(
2153
+					esc_html__(
2154
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2155
+						'event_espresso'
2156
+					),
2157
+					$classname
2158
+				)
2159
+			);
2160
+		}
2161
+		$modelName = self::_get_model_classname($classname);
2162
+		return self::_get_model_instance_with_name($modelName, $timezone);
2163
+	}
2164
+
2165
+
2166
+	/**
2167
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2168
+	 *
2169
+	 * @param string $model_classname
2170
+	 * @param null   $timezone
2171
+	 * @return EEM_Base
2172
+	 * @throws ReflectionException
2173
+	 * @throws InvalidArgumentException
2174
+	 * @throws InvalidInterfaceException
2175
+	 * @throws InvalidDataTypeException
2176
+	 * @throws EE_Error
2177
+	 */
2178
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2179
+	{
2180
+		$model_classname = str_replace('EEM_', '', $model_classname);
2181
+		$model = EE_Registry::instance()->load_model($model_classname);
2182
+		$model->set_timezone($timezone);
2183
+		return $model;
2184
+	}
2185
+
2186
+
2187
+	/**
2188
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2189
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2190
+	 *
2191
+	 * @param null $model_name
2192
+	 * @return string like EEM_Attendee
2193
+	 */
2194
+	private static function _get_model_classname($model_name = null)
2195
+	{
2196
+		if (strpos($model_name, 'EE_') === 0) {
2197
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2198
+		} else {
2199
+			$model_classname = 'EEM_' . $model_name;
2200
+		}
2201
+		return $model_classname;
2202
+	}
2203
+
2204
+
2205
+	/**
2206
+	 * returns the name of the primary key attribute
2207
+	 *
2208
+	 * @param null $classname
2209
+	 * @throws ReflectionException
2210
+	 * @throws InvalidArgumentException
2211
+	 * @throws InvalidInterfaceException
2212
+	 * @throws InvalidDataTypeException
2213
+	 * @throws EE_Error
2214
+	 * @return string
2215
+	 */
2216
+	protected static function _get_primary_key_name($classname = null)
2217
+	{
2218
+		if (! $classname) {
2219
+			throw new EE_Error(
2220
+				sprintf(
2221
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2222
+					$classname
2223
+				)
2224
+			);
2225
+		}
2226
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2227
+	}
2228
+
2229
+
2230
+	/**
2231
+	 * Gets the value of the primary key.
2232
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2233
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2234
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2235
+	 *
2236
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2237
+	 * @throws ReflectionException
2238
+	 * @throws InvalidArgumentException
2239
+	 * @throws InvalidInterfaceException
2240
+	 * @throws InvalidDataTypeException
2241
+	 * @throws EE_Error
2242
+	 */
2243
+	public function ID()
2244
+	{
2245
+		$model = $this->get_model();
2246
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2247
+		if ($model->has_primary_key_field()) {
2248
+			return $this->_fields[ $model->primary_key_name() ];
2249
+		}
2250
+		return $model->get_index_primary_key_string($this->_fields);
2251
+	}
2252
+
2253
+
2254
+	/**
2255
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2256
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2257
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2258
+	 *
2259
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2260
+	 * @param string $relationName                     eg 'Events','Question',etc.
2261
+	 *                                                 an attendee to a group, you also want to specify which role they
2262
+	 *                                                 will have in that group. So you would use this parameter to
2263
+	 *                                                 specify array('role-column-name'=>'role-id')
2264
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2265
+	 *                                                 allow you to further constrict the relation to being added.
2266
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2267
+	 *                                                 column on the JOIN table and currently only the HABTM models
2268
+	 *                                                 accept these additional conditions.  Also remember that if an
2269
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2270
+	 *                                                 NEW row is created in the join table.
2271
+	 * @param null   $cache_id
2272
+	 * @throws ReflectionException
2273
+	 * @throws InvalidArgumentException
2274
+	 * @throws InvalidInterfaceException
2275
+	 * @throws InvalidDataTypeException
2276
+	 * @throws EE_Error
2277
+	 * @return EE_Base_Class the object the relation was added to
2278
+	 */
2279
+	public function _add_relation_to(
2280
+		$otherObjectModelObjectOrID,
2281
+		$relationName,
2282
+		$extra_join_model_fields_n_values = array(),
2283
+		$cache_id = null
2284
+	) {
2285
+		$model = $this->get_model();
2286
+		// if this thing exists in the DB, save the relation to the DB
2287
+		if ($this->ID()) {
2288
+			$otherObject = $model->add_relationship_to(
2289
+				$this,
2290
+				$otherObjectModelObjectOrID,
2291
+				$relationName,
2292
+				$extra_join_model_fields_n_values
2293
+			);
2294
+			// clear cache so future get_many_related and get_first_related() return new results.
2295
+			$this->clear_cache($relationName, $otherObject, true);
2296
+			if ($otherObject instanceof EE_Base_Class) {
2297
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2298
+			}
2299
+		} else {
2300
+			// this thing doesn't exist in the DB,  so just cache it
2301
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2302
+				throw new EE_Error(
2303
+					sprintf(
2304
+						esc_html__(
2305
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2306
+							'event_espresso'
2307
+						),
2308
+						$otherObjectModelObjectOrID,
2309
+						get_class($this)
2310
+					)
2311
+				);
2312
+			}
2313
+			$otherObject = $otherObjectModelObjectOrID;
2314
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2315
+		}
2316
+		if ($otherObject instanceof EE_Base_Class) {
2317
+			// fix the reciprocal relation too
2318
+			if ($otherObject->ID()) {
2319
+				// its saved so assumed relations exist in the DB, so we can just
2320
+				// clear the cache so future queries use the updated info in the DB
2321
+				$otherObject->clear_cache(
2322
+					$model->get_this_model_name(),
2323
+					null,
2324
+					true
2325
+				);
2326
+			} else {
2327
+				// it's not saved, so it caches relations like this
2328
+				$otherObject->cache($model->get_this_model_name(), $this);
2329
+			}
2330
+		}
2331
+		return $otherObject;
2332
+	}
2333
+
2334
+
2335
+	/**
2336
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2337
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2338
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2339
+	 * from the cache
2340
+	 *
2341
+	 * @param mixed  $otherObjectModelObjectOrID
2342
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2343
+	 *                to the DB yet
2344
+	 * @param string $relationName
2345
+	 * @param array  $where_query
2346
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2347
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2348
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2349
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2350
+	 *                deleted.
2351
+	 * @return EE_Base_Class the relation was removed from
2352
+	 * @throws ReflectionException
2353
+	 * @throws InvalidArgumentException
2354
+	 * @throws InvalidInterfaceException
2355
+	 * @throws InvalidDataTypeException
2356
+	 * @throws EE_Error
2357
+	 */
2358
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2359
+	{
2360
+		if ($this->ID()) {
2361
+			// if this exists in the DB, save the relation change to the DB too
2362
+			$otherObject = $this->get_model()->remove_relationship_to(
2363
+				$this,
2364
+				$otherObjectModelObjectOrID,
2365
+				$relationName,
2366
+				$where_query
2367
+			);
2368
+			$this->clear_cache(
2369
+				$relationName,
2370
+				$otherObject
2371
+			);
2372
+		} else {
2373
+			// this doesn't exist in the DB, just remove it from the cache
2374
+			$otherObject = $this->clear_cache(
2375
+				$relationName,
2376
+				$otherObjectModelObjectOrID
2377
+			);
2378
+		}
2379
+		if ($otherObject instanceof EE_Base_Class) {
2380
+			$otherObject->clear_cache(
2381
+				$this->get_model()->get_this_model_name(),
2382
+				$this
2383
+			);
2384
+		}
2385
+		return $otherObject;
2386
+	}
2387
+
2388
+
2389
+	/**
2390
+	 * Removes ALL the related things for the $relationName.
2391
+	 *
2392
+	 * @param string $relationName
2393
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2394
+	 * @return EE_Base_Class
2395
+	 * @throws ReflectionException
2396
+	 * @throws InvalidArgumentException
2397
+	 * @throws InvalidInterfaceException
2398
+	 * @throws InvalidDataTypeException
2399
+	 * @throws EE_Error
2400
+	 */
2401
+	public function _remove_relations($relationName, $where_query_params = array())
2402
+	{
2403
+		if ($this->ID()) {
2404
+			// if this exists in the DB, save the relation change to the DB too
2405
+			$otherObjects = $this->get_model()->remove_relations(
2406
+				$this,
2407
+				$relationName,
2408
+				$where_query_params
2409
+			);
2410
+			$this->clear_cache(
2411
+				$relationName,
2412
+				null,
2413
+				true
2414
+			);
2415
+		} else {
2416
+			// this doesn't exist in the DB, just remove it from the cache
2417
+			$otherObjects = $this->clear_cache(
2418
+				$relationName,
2419
+				null,
2420
+				true
2421
+			);
2422
+		}
2423
+		if (is_array($otherObjects)) {
2424
+			foreach ($otherObjects as $otherObject) {
2425
+				$otherObject->clear_cache(
2426
+					$this->get_model()->get_this_model_name(),
2427
+					$this
2428
+				);
2429
+			}
2430
+		}
2431
+		return $otherObjects;
2432
+	}
2433
+
2434
+
2435
+	/**
2436
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2437
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2438
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2439
+	 * because we want to get even deleted items etc.
2440
+	 *
2441
+	 * @param string $relationName key in the model's _model_relations array
2442
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2443
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2444
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2445
+	 *                             results if you want IDs
2446
+	 * @throws ReflectionException
2447
+	 * @throws InvalidArgumentException
2448
+	 * @throws InvalidInterfaceException
2449
+	 * @throws InvalidDataTypeException
2450
+	 * @throws EE_Error
2451
+	 */
2452
+	public function get_many_related($relationName, $query_params = array())
2453
+	{
2454
+		if ($this->ID()) {
2455
+			// this exists in the DB, so get the related things from either the cache or the DB
2456
+			// if there are query parameters, forget about caching the related model objects.
2457
+			if ($query_params) {
2458
+				$related_model_objects = $this->get_model()->get_all_related(
2459
+					$this,
2460
+					$relationName,
2461
+					$query_params
2462
+				);
2463
+			} else {
2464
+				// did we already cache the result of this query?
2465
+				$cached_results = $this->get_all_from_cache($relationName);
2466
+				if (! $cached_results) {
2467
+					$related_model_objects = $this->get_model()->get_all_related(
2468
+						$this,
2469
+						$relationName,
2470
+						$query_params
2471
+					);
2472
+					// if no query parameters were passed, then we got all the related model objects
2473
+					// for that relation. We can cache them then.
2474
+					foreach ($related_model_objects as $related_model_object) {
2475
+						$this->cache($relationName, $related_model_object);
2476
+					}
2477
+				} else {
2478
+					$related_model_objects = $cached_results;
2479
+				}
2480
+			}
2481
+		} else {
2482
+			// this doesn't exist in the DB, so just get the related things from the cache
2483
+			$related_model_objects = $this->get_all_from_cache($relationName);
2484
+		}
2485
+		return $related_model_objects;
2486
+	}
2487
+
2488
+
2489
+	/**
2490
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2491
+	 * unless otherwise specified in the $query_params
2492
+	 *
2493
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2494
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2495
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2496
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2497
+	 *                               that by the setting $distinct to TRUE;
2498
+	 * @return int
2499
+	 * @throws ReflectionException
2500
+	 * @throws InvalidArgumentException
2501
+	 * @throws InvalidInterfaceException
2502
+	 * @throws InvalidDataTypeException
2503
+	 * @throws EE_Error
2504
+	 */
2505
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2506
+	{
2507
+		return $this->get_model()->count_related(
2508
+			$this,
2509
+			$relation_name,
2510
+			$query_params,
2511
+			$field_to_count,
2512
+			$distinct
2513
+		);
2514
+	}
2515
+
2516
+
2517
+	/**
2518
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2519
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2520
+	 *
2521
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2522
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2523
+	 * @param string $field_to_sum  name of field to count by.
2524
+	 *                              By default, uses primary key
2525
+	 *                              (which doesn't make much sense, so you should probably change it)
2526
+	 * @return int
2527
+	 * @throws ReflectionException
2528
+	 * @throws InvalidArgumentException
2529
+	 * @throws InvalidInterfaceException
2530
+	 * @throws InvalidDataTypeException
2531
+	 * @throws EE_Error
2532
+	 */
2533
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2534
+	{
2535
+		return $this->get_model()->sum_related(
2536
+			$this,
2537
+			$relation_name,
2538
+			$query_params,
2539
+			$field_to_sum
2540
+		);
2541
+	}
2542
+
2543
+
2544
+	/**
2545
+	 * Gets the first (ie, one) related model object of the specified type.
2546
+	 *
2547
+	 * @param string $relationName key in the model's _model_relations array
2548
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
+	 * @return EE_Base_Class (not an array, a single object)
2550
+	 * @throws ReflectionException
2551
+	 * @throws InvalidArgumentException
2552
+	 * @throws InvalidInterfaceException
2553
+	 * @throws InvalidDataTypeException
2554
+	 * @throws EE_Error
2555
+	 */
2556
+	public function get_first_related($relationName, $query_params = array())
2557
+	{
2558
+		$model = $this->get_model();
2559
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2560
+			// if they've provided some query parameters, don't bother trying to cache the result
2561
+			// also make sure we're not caching the result of get_first_related
2562
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2563
+			if (
2564
+				$query_params
2565
+				|| ! $model->related_settings_for($relationName)
2566
+					 instanceof
2567
+					 EE_Belongs_To_Relation
2568
+			) {
2569
+				$related_model_object = $model->get_first_related(
2570
+					$this,
2571
+					$relationName,
2572
+					$query_params
2573
+				);
2574
+			} else {
2575
+				// first, check if we've already cached the result of this query
2576
+				$cached_result = $this->get_one_from_cache($relationName);
2577
+				if (! $cached_result) {
2578
+					$related_model_object = $model->get_first_related(
2579
+						$this,
2580
+						$relationName,
2581
+						$query_params
2582
+					);
2583
+					$this->cache($relationName, $related_model_object);
2584
+				} else {
2585
+					$related_model_object = $cached_result;
2586
+				}
2587
+			}
2588
+		} else {
2589
+			$related_model_object = null;
2590
+			// this doesn't exist in the Db,
2591
+			// but maybe the relation is of type belongs to, and so the related thing might
2592
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2593
+				$related_model_object = $model->get_first_related(
2594
+					$this,
2595
+					$relationName,
2596
+					$query_params
2597
+				);
2598
+			}
2599
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2600
+			// just get what's cached on this object
2601
+			if (! $related_model_object) {
2602
+				$related_model_object = $this->get_one_from_cache($relationName);
2603
+			}
2604
+		}
2605
+		return $related_model_object;
2606
+	}
2607
+
2608
+
2609
+	/**
2610
+	 * Does a delete on all related objects of type $relationName and removes
2611
+	 * the current model object's relation to them. If they can't be deleted (because
2612
+	 * of blocking related model objects) does nothing. If the related model objects are
2613
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2614
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2615
+	 *
2616
+	 * @param string $relationName
2617
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2618
+	 * @return int how many deleted
2619
+	 * @throws ReflectionException
2620
+	 * @throws InvalidArgumentException
2621
+	 * @throws InvalidInterfaceException
2622
+	 * @throws InvalidDataTypeException
2623
+	 * @throws EE_Error
2624
+	 */
2625
+	public function delete_related($relationName, $query_params = array())
2626
+	{
2627
+		if ($this->ID()) {
2628
+			$count = $this->get_model()->delete_related(
2629
+				$this,
2630
+				$relationName,
2631
+				$query_params
2632
+			);
2633
+		} else {
2634
+			$count = count($this->get_all_from_cache($relationName));
2635
+			$this->clear_cache($relationName, null, true);
2636
+		}
2637
+		return $count;
2638
+	}
2639
+
2640
+
2641
+	/**
2642
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2643
+	 * the current model object's relation to them. If they can't be deleted (because
2644
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2645
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2646
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2647
+	 *
2648
+	 * @param string $relationName
2649
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
+	 * @return int how many deleted (including those soft deleted)
2651
+	 * @throws ReflectionException
2652
+	 * @throws InvalidArgumentException
2653
+	 * @throws InvalidInterfaceException
2654
+	 * @throws InvalidDataTypeException
2655
+	 * @throws EE_Error
2656
+	 */
2657
+	public function delete_related_permanently($relationName, $query_params = array())
2658
+	{
2659
+		if ($this->ID()) {
2660
+			$count = $this->get_model()->delete_related_permanently(
2661
+				$this,
2662
+				$relationName,
2663
+				$query_params
2664
+			);
2665
+		} else {
2666
+			$count = count($this->get_all_from_cache($relationName));
2667
+		}
2668
+		$this->clear_cache($relationName, null, true);
2669
+		return $count;
2670
+	}
2671
+
2672
+
2673
+	/**
2674
+	 * is_set
2675
+	 * Just a simple utility function children can use for checking if property exists
2676
+	 *
2677
+	 * @access  public
2678
+	 * @param  string $field_name property to check
2679
+	 * @return bool                              TRUE if existing,FALSE if not.
2680
+	 */
2681
+	public function is_set($field_name)
2682
+	{
2683
+		return isset($this->_fields[ $field_name ]);
2684
+	}
2685
+
2686
+
2687
+	/**
2688
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2689
+	 * EE_Error exception if they don't
2690
+	 *
2691
+	 * @param  mixed (string|array) $properties properties to check
2692
+	 * @throws EE_Error
2693
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2694
+	 */
2695
+	protected function _property_exists($properties)
2696
+	{
2697
+		foreach ((array) $properties as $property_name) {
2698
+			// first make sure this property exists
2699
+			if (! $this->_fields[ $property_name ]) {
2700
+				throw new EE_Error(
2701
+					sprintf(
2702
+						esc_html__(
2703
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2704
+							'event_espresso'
2705
+						),
2706
+						$property_name
2707
+					)
2708
+				);
2709
+			}
2710
+		}
2711
+		return true;
2712
+	}
2713
+
2714
+
2715
+	/**
2716
+	 * This simply returns an array of model fields for this object
2717
+	 *
2718
+	 * @return array
2719
+	 * @throws ReflectionException
2720
+	 * @throws InvalidArgumentException
2721
+	 * @throws InvalidInterfaceException
2722
+	 * @throws InvalidDataTypeException
2723
+	 * @throws EE_Error
2724
+	 */
2725
+	public function model_field_array()
2726
+	{
2727
+		$fields = $this->get_model()->field_settings(false);
2728
+		$properties = array();
2729
+		// remove prepended underscore
2730
+		foreach ($fields as $field_name => $settings) {
2731
+			$properties[ $field_name ] = $this->get($field_name);
2732
+		}
2733
+		return $properties;
2734
+	}
2735
+
2736
+
2737
+	/**
2738
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2739
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2740
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2741
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2742
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2743
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2744
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2745
+	 * and accepts 2 arguments: the object on which the function was called,
2746
+	 * and an array of the original arguments passed to the function.
2747
+	 * Whatever their callback function returns will be returned by this function.
2748
+	 * Example: in functions.php (or in a plugin):
2749
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2750
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2751
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2752
+	 *          return $previousReturnValue.$returnString;
2753
+	 *      }
2754
+	 * require('EE_Answer.class.php');
2755
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2756
+	 *      ->my_callback('monkeys',100);
2757
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2758
+	 *
2759
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2760
+	 * @param array  $args       array of original arguments passed to the function
2761
+	 * @throws EE_Error
2762
+	 * @return mixed whatever the plugin which calls add_filter decides
2763
+	 */
2764
+	public function __call($methodName, $args)
2765
+	{
2766
+		$className = get_class($this);
2767
+		$tagName = "FHEE__{$className}__{$methodName}";
2768
+		if (! has_filter($tagName)) {
2769
+			throw new EE_Error(
2770
+				sprintf(
2771
+					esc_html__(
2772
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2773
+						'event_espresso'
2774
+					),
2775
+					$methodName,
2776
+					$className,
2777
+					$tagName
2778
+				)
2779
+			);
2780
+		}
2781
+		return apply_filters($tagName, null, $this, $args);
2782
+	}
2783
+
2784
+
2785
+	/**
2786
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2787
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2788
+	 *
2789
+	 * @param string $meta_key
2790
+	 * @param mixed  $meta_value
2791
+	 * @param mixed  $previous_value
2792
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2793
+	 *                  NOTE: if the values haven't changed, returns 0
2794
+	 * @throws InvalidArgumentException
2795
+	 * @throws InvalidInterfaceException
2796
+	 * @throws InvalidDataTypeException
2797
+	 * @throws EE_Error
2798
+	 * @throws ReflectionException
2799
+	 */
2800
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2801
+	{
2802
+		$query_params = array(
2803
+			array(
2804
+				'EXM_key'  => $meta_key,
2805
+				'OBJ_ID'   => $this->ID(),
2806
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2807
+			),
2808
+		);
2809
+		if ($previous_value !== null) {
2810
+			$query_params[0]['EXM_value'] = $meta_value;
2811
+		}
2812
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2813
+		if (! $existing_rows_like_that) {
2814
+			return $this->add_extra_meta($meta_key, $meta_value);
2815
+		}
2816
+		foreach ($existing_rows_like_that as $existing_row) {
2817
+			$existing_row->save(array('EXM_value' => $meta_value));
2818
+		}
2819
+		return count($existing_rows_like_that);
2820
+	}
2821
+
2822
+
2823
+	/**
2824
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2825
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2826
+	 * extra meta row was entered, false if not
2827
+	 *
2828
+	 * @param string  $meta_key
2829
+	 * @param mixed   $meta_value
2830
+	 * @param boolean $unique
2831
+	 * @return boolean
2832
+	 * @throws InvalidArgumentException
2833
+	 * @throws InvalidInterfaceException
2834
+	 * @throws InvalidDataTypeException
2835
+	 * @throws EE_Error
2836
+	 * @throws ReflectionException
2837
+	 * @throws ReflectionException
2838
+	 */
2839
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2840
+	{
2841
+		if ($unique) {
2842
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2843
+				array(
2844
+					array(
2845
+						'EXM_key'  => $meta_key,
2846
+						'OBJ_ID'   => $this->ID(),
2847
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2848
+					),
2849
+				)
2850
+			);
2851
+			if ($existing_extra_meta) {
2852
+				return false;
2853
+			}
2854
+		}
2855
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2856
+			array(
2857
+				'EXM_key'   => $meta_key,
2858
+				'EXM_value' => $meta_value,
2859
+				'OBJ_ID'    => $this->ID(),
2860
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2861
+			)
2862
+		);
2863
+		$new_extra_meta->save();
2864
+		return true;
2865
+	}
2866
+
2867
+
2868
+	/**
2869
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2870
+	 * is specified, only deletes extra meta records with that value.
2871
+	 *
2872
+	 * @param string $meta_key
2873
+	 * @param mixed  $meta_value
2874
+	 * @return int number of extra meta rows deleted
2875
+	 * @throws InvalidArgumentException
2876
+	 * @throws InvalidInterfaceException
2877
+	 * @throws InvalidDataTypeException
2878
+	 * @throws EE_Error
2879
+	 * @throws ReflectionException
2880
+	 */
2881
+	public function delete_extra_meta($meta_key, $meta_value = null)
2882
+	{
2883
+		$query_params = array(
2884
+			array(
2885
+				'EXM_key'  => $meta_key,
2886
+				'OBJ_ID'   => $this->ID(),
2887
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2888
+			),
2889
+		);
2890
+		if ($meta_value !== null) {
2891
+			$query_params[0]['EXM_value'] = $meta_value;
2892
+		}
2893
+		return EEM_Extra_Meta::instance()->delete($query_params);
2894
+	}
2895
+
2896
+
2897
+	/**
2898
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2899
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2900
+	 * You can specify $default is case you haven't found the extra meta
2901
+	 *
2902
+	 * @param string  $meta_key
2903
+	 * @param boolean $single
2904
+	 * @param mixed   $default if we don't find anything, what should we return?
2905
+	 * @return mixed single value if $single; array if ! $single
2906
+	 * @throws ReflectionException
2907
+	 * @throws InvalidArgumentException
2908
+	 * @throws InvalidInterfaceException
2909
+	 * @throws InvalidDataTypeException
2910
+	 * @throws EE_Error
2911
+	 */
2912
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2913
+	{
2914
+		if ($single) {
2915
+			$result = $this->get_first_related(
2916
+				'Extra_Meta',
2917
+				array(array('EXM_key' => $meta_key))
2918
+			);
2919
+			if ($result instanceof EE_Extra_Meta) {
2920
+				return $result->value();
2921
+			}
2922
+		} else {
2923
+			$results = $this->get_many_related(
2924
+				'Extra_Meta',
2925
+				array(array('EXM_key' => $meta_key))
2926
+			);
2927
+			if ($results) {
2928
+				$values = array();
2929
+				foreach ($results as $result) {
2930
+					if ($result instanceof EE_Extra_Meta) {
2931
+						$values[ $result->ID() ] = $result->value();
2932
+					}
2933
+				}
2934
+				return $values;
2935
+			}
2936
+		}
2937
+		// if nothing discovered yet return default.
2938
+		return apply_filters(
2939
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2940
+			$default,
2941
+			$meta_key,
2942
+			$single,
2943
+			$this
2944
+		);
2945
+	}
2946
+
2947
+
2948
+	/**
2949
+	 * Returns a simple array of all the extra meta associated with this model object.
2950
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2951
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2952
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2953
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2954
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2955
+	 * finally the extra meta's value as each sub-value. (eg
2956
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2957
+	 *
2958
+	 * @param boolean $one_of_each_key
2959
+	 * @return array
2960
+	 * @throws ReflectionException
2961
+	 * @throws InvalidArgumentException
2962
+	 * @throws InvalidInterfaceException
2963
+	 * @throws InvalidDataTypeException
2964
+	 * @throws EE_Error
2965
+	 */
2966
+	public function all_extra_meta_array($one_of_each_key = true)
2967
+	{
2968
+		$return_array = array();
2969
+		if ($one_of_each_key) {
2970
+			$extra_meta_objs = $this->get_many_related(
2971
+				'Extra_Meta',
2972
+				array('group_by' => 'EXM_key')
2973
+			);
2974
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2975
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2976
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2977
+				}
2978
+			}
2979
+		} else {
2980
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2981
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2982
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2983
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2984
+						$return_array[ $extra_meta_obj->key() ] = array();
2985
+					}
2986
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2987
+				}
2988
+			}
2989
+		}
2990
+		return $return_array;
2991
+	}
2992
+
2993
+
2994
+	/**
2995
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2996
+	 *
2997
+	 * @return string
2998
+	 * @throws ReflectionException
2999
+	 * @throws InvalidArgumentException
3000
+	 * @throws InvalidInterfaceException
3001
+	 * @throws InvalidDataTypeException
3002
+	 * @throws EE_Error
3003
+	 */
3004
+	public function name()
3005
+	{
3006
+		// find a field that's not a text field
3007
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3008
+		if ($field_we_can_use) {
3009
+			return $this->get($field_we_can_use->get_name());
3010
+		}
3011
+		$first_few_properties = $this->model_field_array();
3012
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3013
+		$name_parts = array();
3014
+		foreach ($first_few_properties as $name => $value) {
3015
+			$name_parts[] = "$name:$value";
3016
+		}
3017
+		return implode(',', $name_parts);
3018
+	}
3019
+
3020
+
3021
+	/**
3022
+	 * in_entity_map
3023
+	 * Checks if this model object has been proven to already be in the entity map
3024
+	 *
3025
+	 * @return boolean
3026
+	 * @throws ReflectionException
3027
+	 * @throws InvalidArgumentException
3028
+	 * @throws InvalidInterfaceException
3029
+	 * @throws InvalidDataTypeException
3030
+	 * @throws EE_Error
3031
+	 */
3032
+	public function in_entity_map()
3033
+	{
3034
+		// well, if we looked, did we find it in the entity map?
3035
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3036
+	}
3037
+
3038
+
3039
+	/**
3040
+	 * refresh_from_db
3041
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3042
+	 *
3043
+	 * @throws ReflectionException
3044
+	 * @throws InvalidArgumentException
3045
+	 * @throws InvalidInterfaceException
3046
+	 * @throws InvalidDataTypeException
3047
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3048
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3049
+	 */
3050
+	public function refresh_from_db()
3051
+	{
3052
+		if ($this->ID() && $this->in_entity_map()) {
3053
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3054
+		} else {
3055
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3056
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3057
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3058
+			// absolutely nothing in it for this ID
3059
+			if (WP_DEBUG) {
3060
+				throw new EE_Error(
3061
+					sprintf(
3062
+						esc_html__(
3063
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3064
+							'event_espresso'
3065
+						),
3066
+						$this->ID(),
3067
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3068
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3069
+					)
3070
+				);
3071
+			}
3072
+		}
3073
+	}
3074
+
3075
+
3076
+	/**
3077
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3078
+	 *
3079
+	 * @since 4.9.80.p
3080
+	 * @param EE_Model_Field_Base[] $fields
3081
+	 * @param string $new_value_sql
3082
+	 *      example: 'column_name=123',
3083
+	 *      or 'column_name=column_name+1',
3084
+	 *      or 'column_name= CASE
3085
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3086
+	 *          THEN `column_name` + 5
3087
+	 *          ELSE `column_name`
3088
+	 *      END'
3089
+	 *      Also updates $field on this model object with the latest value from the database.
3090
+	 * @return bool
3091
+	 * @throws EE_Error
3092
+	 * @throws InvalidArgumentException
3093
+	 * @throws InvalidDataTypeException
3094
+	 * @throws InvalidInterfaceException
3095
+	 * @throws ReflectionException
3096
+	 */
3097
+	protected function updateFieldsInDB($fields, $new_value_sql)
3098
+	{
3099
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3100
+		// if it wasn't even there to start off.
3101
+		if (! $this->ID()) {
3102
+			$this->save();
3103
+		}
3104
+		global $wpdb;
3105
+		if (empty($fields)) {
3106
+			throw new InvalidArgumentException(
3107
+				esc_html__(
3108
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3109
+					'event_espresso'
3110
+				)
3111
+			);
3112
+		}
3113
+		$first_field = reset($fields);
3114
+		$table_alias = $first_field->get_table_alias();
3115
+		foreach ($fields as $field) {
3116
+			if ($table_alias !== $field->get_table_alias()) {
3117
+				throw new InvalidArgumentException(
3118
+					sprintf(
3119
+						esc_html__(
3120
+							// @codingStandardsIgnoreStart
3121
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3122
+							// @codingStandardsIgnoreEnd
3123
+							'event_espresso'
3124
+						),
3125
+						$table_alias,
3126
+						$field->get_table_alias()
3127
+					)
3128
+				);
3129
+			}
3130
+		}
3131
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3132
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3133
+		$table_pk_value = $this->ID();
3134
+		$table_name = $table_obj->get_table_name();
3135
+		if ($table_obj instanceof EE_Secondary_Table) {
3136
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3137
+		} else {
3138
+			$table_pk_field_name = $table_obj->get_pk_column();
3139
+		}
3140
+
3141
+		$query =
3142
+			"UPDATE `{$table_name}`
3143 3143
             SET "
3144
-            . $new_value_sql
3145
-            . $wpdb->prepare(
3146
-                "
3144
+			. $new_value_sql
3145
+			. $wpdb->prepare(
3146
+				"
3147 3147
             WHERE `{$table_pk_field_name}` = %d;",
3148
-                $table_pk_value
3149
-            );
3150
-        $result = $wpdb->query($query);
3151
-        foreach ($fields as $field) {
3152
-            // If it was successful, we'd like to know the new value.
3153
-            // If it failed, we'd also like to know the new value.
3154
-            $new_value = $this->get_model()->get_var(
3155
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3156
-                    $this->get_model()->get_index_primary_key_string(
3157
-                        $this->model_field_array()
3158
-                    ),
3159
-                    array(
3160
-                        'default_where_conditions' => 'minimum',
3161
-                    )
3162
-                ),
3163
-                $field->get_name()
3164
-            );
3165
-            $this->set_from_db(
3166
-                $field->get_name(),
3167
-                $new_value
3168
-            );
3169
-        }
3170
-        return (bool) $result;
3171
-    }
3172
-
3173
-
3174
-    /**
3175
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3176
-     * Does not allow negative values, however.
3177
-     *
3178
-     * @since 4.9.80.p
3179
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3180
-     *                                   (positive or negative). One important gotcha: all these values must be
3181
-     *                                   on the same table (eg don't pass in one field for the posts table and
3182
-     *                                   another for the event meta table.)
3183
-     * @return bool
3184
-     * @throws EE_Error
3185
-     * @throws InvalidArgumentException
3186
-     * @throws InvalidDataTypeException
3187
-     * @throws InvalidInterfaceException
3188
-     * @throws ReflectionException
3189
-     */
3190
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3191
-    {
3192
-        global $wpdb;
3193
-        if (empty($fields_n_quantities)) {
3194
-            // No fields to update? Well sure, we updated them to that value just fine.
3195
-            return true;
3196
-        }
3197
-        $fields = [];
3198
-        $set_sql_statements = [];
3199
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3200
-            $field = $this->get_model()->field_settings_for($field_name, true);
3201
-            $fields[] = $field;
3202
-            $column_name = $field->get_table_column();
3203
-
3204
-            $abs_qty = absint($quantity);
3205
-            if ($quantity > 0) {
3206
-                // don't let the value be negative as often these fields are unsigned
3207
-                $set_sql_statements[] = $wpdb->prepare(
3208
-                    "`{$column_name}` = `{$column_name}` + %d",
3209
-                    $abs_qty
3210
-                );
3211
-            } else {
3212
-                $set_sql_statements[] = $wpdb->prepare(
3213
-                    "`{$column_name}` = CASE
3148
+				$table_pk_value
3149
+			);
3150
+		$result = $wpdb->query($query);
3151
+		foreach ($fields as $field) {
3152
+			// If it was successful, we'd like to know the new value.
3153
+			// If it failed, we'd also like to know the new value.
3154
+			$new_value = $this->get_model()->get_var(
3155
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3156
+					$this->get_model()->get_index_primary_key_string(
3157
+						$this->model_field_array()
3158
+					),
3159
+					array(
3160
+						'default_where_conditions' => 'minimum',
3161
+					)
3162
+				),
3163
+				$field->get_name()
3164
+			);
3165
+			$this->set_from_db(
3166
+				$field->get_name(),
3167
+				$new_value
3168
+			);
3169
+		}
3170
+		return (bool) $result;
3171
+	}
3172
+
3173
+
3174
+	/**
3175
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3176
+	 * Does not allow negative values, however.
3177
+	 *
3178
+	 * @since 4.9.80.p
3179
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3180
+	 *                                   (positive or negative). One important gotcha: all these values must be
3181
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3182
+	 *                                   another for the event meta table.)
3183
+	 * @return bool
3184
+	 * @throws EE_Error
3185
+	 * @throws InvalidArgumentException
3186
+	 * @throws InvalidDataTypeException
3187
+	 * @throws InvalidInterfaceException
3188
+	 * @throws ReflectionException
3189
+	 */
3190
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3191
+	{
3192
+		global $wpdb;
3193
+		if (empty($fields_n_quantities)) {
3194
+			// No fields to update? Well sure, we updated them to that value just fine.
3195
+			return true;
3196
+		}
3197
+		$fields = [];
3198
+		$set_sql_statements = [];
3199
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3200
+			$field = $this->get_model()->field_settings_for($field_name, true);
3201
+			$fields[] = $field;
3202
+			$column_name = $field->get_table_column();
3203
+
3204
+			$abs_qty = absint($quantity);
3205
+			if ($quantity > 0) {
3206
+				// don't let the value be negative as often these fields are unsigned
3207
+				$set_sql_statements[] = $wpdb->prepare(
3208
+					"`{$column_name}` = `{$column_name}` + %d",
3209
+					$abs_qty
3210
+				);
3211
+			} else {
3212
+				$set_sql_statements[] = $wpdb->prepare(
3213
+					"`{$column_name}` = CASE
3214 3214
                        WHEN (`{$column_name}` >= %d)
3215 3215
                        THEN `{$column_name}` - %d
3216 3216
                        ELSE 0
3217 3217
                     END",
3218
-                    $abs_qty,
3219
-                    $abs_qty
3220
-                );
3221
-            }
3222
-        }
3223
-        return $this->updateFieldsInDB(
3224
-            $fields,
3225
-            implode(', ', $set_sql_statements)
3226
-        );
3227
-    }
3228
-
3229
-
3230
-    /**
3231
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3232
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3233
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3234
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3235
-     * Otherwise returns false.
3236
-     *
3237
-     * @since 4.9.80.p
3238
-     * @param string $field_name_to_bump
3239
-     * @param string $field_name_affecting_total
3240
-     * @param string $limit_field_name
3241
-     * @param int    $quantity
3242
-     * @return bool
3243
-     * @throws EE_Error
3244
-     * @throws InvalidArgumentException
3245
-     * @throws InvalidDataTypeException
3246
-     * @throws InvalidInterfaceException
3247
-     * @throws ReflectionException
3248
-     */
3249
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3250
-    {
3251
-        global $wpdb;
3252
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3253
-        $column_name = $field->get_table_column();
3254
-
3255
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3256
-        $column_affecting_total = $field_affecting_total->get_table_column();
3257
-
3258
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3259
-        $limiting_column = $limiting_field->get_table_column();
3260
-        return $this->updateFieldsInDB(
3261
-            [$field],
3262
-            $wpdb->prepare(
3263
-                "`{$column_name}` =
3218
+					$abs_qty,
3219
+					$abs_qty
3220
+				);
3221
+			}
3222
+		}
3223
+		return $this->updateFieldsInDB(
3224
+			$fields,
3225
+			implode(', ', $set_sql_statements)
3226
+		);
3227
+	}
3228
+
3229
+
3230
+	/**
3231
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3232
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3233
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3234
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3235
+	 * Otherwise returns false.
3236
+	 *
3237
+	 * @since 4.9.80.p
3238
+	 * @param string $field_name_to_bump
3239
+	 * @param string $field_name_affecting_total
3240
+	 * @param string $limit_field_name
3241
+	 * @param int    $quantity
3242
+	 * @return bool
3243
+	 * @throws EE_Error
3244
+	 * @throws InvalidArgumentException
3245
+	 * @throws InvalidDataTypeException
3246
+	 * @throws InvalidInterfaceException
3247
+	 * @throws ReflectionException
3248
+	 */
3249
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3250
+	{
3251
+		global $wpdb;
3252
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3253
+		$column_name = $field->get_table_column();
3254
+
3255
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3256
+		$column_affecting_total = $field_affecting_total->get_table_column();
3257
+
3258
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3259
+		$limiting_column = $limiting_field->get_table_column();
3260
+		return $this->updateFieldsInDB(
3261
+			[$field],
3262
+			$wpdb->prepare(
3263
+				"`{$column_name}` =
3264 3264
             CASE
3265 3265
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3266 3266
                THEN `{$column_name}` + %d
3267 3267
                ELSE `{$column_name}`
3268 3268
             END",
3269
-                $quantity,
3270
-                EE_INF_IN_DB,
3271
-                $quantity
3272
-            )
3273
-        );
3274
-    }
3275
-
3276
-
3277
-    /**
3278
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3279
-     * (probably a bad assumption they have made, oh well)
3280
-     *
3281
-     * @return string
3282
-     */
3283
-    public function __toString()
3284
-    {
3285
-        try {
3286
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3287
-        } catch (Exception $e) {
3288
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3289
-            return '';
3290
-        }
3291
-    }
3292
-
3293
-
3294
-    /**
3295
-     * Clear related model objects if they're already in the DB, because otherwise when we
3296
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3297
-     * This means if we have made changes to those related model objects, and want to unserialize
3298
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3299
-     * Instead, those related model objects should be directly serialized and stored.
3300
-     * Eg, the following won't work:
3301
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3302
-     * $att = $reg->attendee();
3303
-     * $att->set( 'ATT_fname', 'Dirk' );
3304
-     * update_option( 'my_option', serialize( $reg ) );
3305
-     * //END REQUEST
3306
-     * //START NEXT REQUEST
3307
-     * $reg = get_option( 'my_option' );
3308
-     * $reg->attendee()->save();
3309
-     * And would need to be replace with:
3310
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3311
-     * $att = $reg->attendee();
3312
-     * $att->set( 'ATT_fname', 'Dirk' );
3313
-     * update_option( 'my_option', serialize( $reg ) );
3314
-     * //END REQUEST
3315
-     * //START NEXT REQUEST
3316
-     * $att = get_option( 'my_option' );
3317
-     * $att->save();
3318
-     *
3319
-     * @return array
3320
-     * @throws ReflectionException
3321
-     * @throws InvalidArgumentException
3322
-     * @throws InvalidInterfaceException
3323
-     * @throws InvalidDataTypeException
3324
-     * @throws EE_Error
3325
-     */
3326
-    public function __sleep()
3327
-    {
3328
-        $model = $this->get_model();
3329
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3330
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3331
-                $classname = 'EE_' . $model->get_this_model_name();
3332
-                if (
3333
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3334
-                    && $this->get_one_from_cache($relation_name)->ID()
3335
-                ) {
3336
-                    $this->clear_cache(
3337
-                        $relation_name,
3338
-                        $this->get_one_from_cache($relation_name)->ID()
3339
-                    );
3340
-                }
3341
-            }
3342
-        }
3343
-        $this->_props_n_values_provided_in_constructor = array();
3344
-        $properties_to_serialize = get_object_vars($this);
3345
-        // don't serialize the model. It's big and that risks recursion
3346
-        unset($properties_to_serialize['_model']);
3347
-        return array_keys($properties_to_serialize);
3348
-    }
3349
-
3350
-
3351
-    /**
3352
-     * restore _props_n_values_provided_in_constructor
3353
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3354
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3355
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3356
-     */
3357
-    public function __wakeup()
3358
-    {
3359
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3360
-    }
3361
-
3362
-
3363
-    /**
3364
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3365
-     * distinct with the clone host instance are also cloned.
3366
-     */
3367
-    public function __clone()
3368
-    {
3369
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3370
-        foreach ($this->_fields as $field => $value) {
3371
-            if ($value instanceof DateTime) {
3372
-                $this->_fields[ $field ] = clone $value;
3373
-            }
3374
-        }
3375
-    }
3269
+				$quantity,
3270
+				EE_INF_IN_DB,
3271
+				$quantity
3272
+			)
3273
+		);
3274
+	}
3275
+
3276
+
3277
+	/**
3278
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3279
+	 * (probably a bad assumption they have made, oh well)
3280
+	 *
3281
+	 * @return string
3282
+	 */
3283
+	public function __toString()
3284
+	{
3285
+		try {
3286
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3287
+		} catch (Exception $e) {
3288
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3289
+			return '';
3290
+		}
3291
+	}
3292
+
3293
+
3294
+	/**
3295
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3296
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3297
+	 * This means if we have made changes to those related model objects, and want to unserialize
3298
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3299
+	 * Instead, those related model objects should be directly serialized and stored.
3300
+	 * Eg, the following won't work:
3301
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3302
+	 * $att = $reg->attendee();
3303
+	 * $att->set( 'ATT_fname', 'Dirk' );
3304
+	 * update_option( 'my_option', serialize( $reg ) );
3305
+	 * //END REQUEST
3306
+	 * //START NEXT REQUEST
3307
+	 * $reg = get_option( 'my_option' );
3308
+	 * $reg->attendee()->save();
3309
+	 * And would need to be replace with:
3310
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3311
+	 * $att = $reg->attendee();
3312
+	 * $att->set( 'ATT_fname', 'Dirk' );
3313
+	 * update_option( 'my_option', serialize( $reg ) );
3314
+	 * //END REQUEST
3315
+	 * //START NEXT REQUEST
3316
+	 * $att = get_option( 'my_option' );
3317
+	 * $att->save();
3318
+	 *
3319
+	 * @return array
3320
+	 * @throws ReflectionException
3321
+	 * @throws InvalidArgumentException
3322
+	 * @throws InvalidInterfaceException
3323
+	 * @throws InvalidDataTypeException
3324
+	 * @throws EE_Error
3325
+	 */
3326
+	public function __sleep()
3327
+	{
3328
+		$model = $this->get_model();
3329
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3330
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3331
+				$classname = 'EE_' . $model->get_this_model_name();
3332
+				if (
3333
+					$this->get_one_from_cache($relation_name) instanceof $classname
3334
+					&& $this->get_one_from_cache($relation_name)->ID()
3335
+				) {
3336
+					$this->clear_cache(
3337
+						$relation_name,
3338
+						$this->get_one_from_cache($relation_name)->ID()
3339
+					);
3340
+				}
3341
+			}
3342
+		}
3343
+		$this->_props_n_values_provided_in_constructor = array();
3344
+		$properties_to_serialize = get_object_vars($this);
3345
+		// don't serialize the model. It's big and that risks recursion
3346
+		unset($properties_to_serialize['_model']);
3347
+		return array_keys($properties_to_serialize);
3348
+	}
3349
+
3350
+
3351
+	/**
3352
+	 * restore _props_n_values_provided_in_constructor
3353
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3354
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3355
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3356
+	 */
3357
+	public function __wakeup()
3358
+	{
3359
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3360
+	}
3361
+
3362
+
3363
+	/**
3364
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3365
+	 * distinct with the clone host instance are also cloned.
3366
+	 */
3367
+	public function __clone()
3368
+	{
3369
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3370
+		foreach ($this->_fields as $field => $value) {
3371
+			if ($value instanceof DateTime) {
3372
+				$this->_fields[ $field ] = clone $value;
3373
+			}
3374
+		}
3375
+	}
3376 3376
 }
Please login to merge, or discard this patch.