Completed
Branch FET-3467-waitlists (4406f2)
by
unknown
46:31 queued 34:26
created
core/services/loaders/LoaderFactory.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@
 block discarded – undo
34 34
      */
35 35
     public static function getLoader()
36 36
     {
37
-        if (! LoaderFactory::$loader instanceof LoaderInterface) {
37
+        if ( ! LoaderFactory::$loader instanceof LoaderInterface) {
38 38
             LoaderFactory::$loader = new Loader();
39 39
         }
40 40
         return LoaderFactory::$loader;
Please login to merge, or discard this patch.
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -77,26 +77,26 @@
 block discarded – undo
77 77
 class LoaderFactory
78 78
 {
79 79
 
80
-    /**
81
-     * @var LoaderInterface $loader ;
82
-     */
83
-    private static $loader;
80
+	/**
81
+	 * @var LoaderInterface $loader ;
82
+	 */
83
+	private static $loader;
84 84
 
85 85
 
86 86
 
87
-    /**
88
-     * @return LoaderInterface
89
-     * @throws InvalidArgumentException
90
-     * @throws InvalidInterfaceException
91
-     * @throws InvalidDataTypeException
92
-     */
93
-    public static function getLoader()
94
-    {
95
-        if (! LoaderFactory::$loader instanceof LoaderInterface) {
96
-            LoaderFactory::$loader = new Loader();
97
-        }
98
-        return LoaderFactory::$loader;
99
-    }
87
+	/**
88
+	 * @return LoaderInterface
89
+	 * @throws InvalidArgumentException
90
+	 * @throws InvalidInterfaceException
91
+	 * @throws InvalidDataTypeException
92
+	 */
93
+	public static function getLoader()
94
+	{
95
+		if (! LoaderFactory::$loader instanceof LoaderInterface) {
96
+			LoaderFactory::$loader = new Loader();
97
+		}
98
+		return LoaderFactory::$loader;
99
+	}
100 100
 
101 101
 
102 102
 }
Please login to merge, or discard this patch.
core/EE_Maintenance_Mode.core.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
     public static function instance()
59 59
     {
60 60
         // check if class object is instantiated
61
-        if (! self::$_instance instanceof EE_Maintenance_Mode) {
61
+        if ( ! self::$_instance instanceof EE_Maintenance_Mode) {
62 62
             self::$_instance = new self();
63 63
         }
64 64
         return self::$_instance;
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
     public function set_maintenance_level($level)
178 178
     {
179 179
         do_action('AHEE__EE_Maintenance_Mode__set_maintenance_level', $level);
180
-        update_option(self::option_name_maintenance_mode, (int)$level);
180
+        update_option(self::option_name_maintenance_mode, (int) $level);
181 181
     }
182 182
 
183 183
 
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
      */
190 190
     public static function disable_frontend_for_maintenance()
191 191
     {
192
-        return (! is_admin() && EE_Maintenance_Mode::instance()->level());
192
+        return ( ! is_admin() && EE_Maintenance_Mode::instance()->level());
193 193
     }
194 194
 
195 195
 
@@ -205,14 +205,14 @@  discard block
 block discarded – undo
205 205
         ) {
206 206
             wp_register_style(
207 207
                 'espresso_default',
208
-                EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
208
+                EE_GLOBAL_ASSETS_URL.'css/espresso_default.css',
209 209
                 array('dashicons'),
210 210
                 EVENT_ESPRESSO_VERSION
211 211
             );
212 212
             wp_enqueue_style('espresso_default');
213 213
             wp_register_script(
214 214
                 'espresso_core',
215
-                EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
215
+                EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
216 216
                 array('jquery'),
217 217
                 EVENT_ESPRESSO_VERSION,
218 218
                 true
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
     public static function template_include()
234 234
     {
235 235
         // shut 'er down down for maintenance ? then don't use any of our templates for our endpoints
236
-        return get_template_directory() . '/index.php';
236
+        return get_template_directory().'/index.php';
237 237
     }
238 238
 
239 239
 
@@ -285,9 +285,9 @@  discard block
 block discarded – undo
285 285
                 ),
286 286
                 '<div id="ee-m-mode-admin-notice-dv" class="ee-really-important-notice-dv"><a class="close-espresso-notice" title="',
287 287
                 '"><span class="dashicons dashicons-no"></span></a><p>',
288
-                ' &raquo; <a href="' . add_query_arg(
288
+                ' &raquo; <a href="'.add_query_arg(
289 289
                     array('page' => 'espresso_maintenance_settings'), admin_url('admin.php')
290
-                ) . '">',
290
+                ).'">',
291 291
                 '</a></p></div>'
292 292
             );
293 293
         }
Please login to merge, or discard this patch.
Indentation   +317 added lines, -317 removed lines patch added patch discarded remove patch
@@ -17,362 +17,362 @@
 block discarded – undo
17 17
 class EE_Maintenance_Mode implements ResettableInterface
18 18
 {
19 19
 
20
-    /**
21
-     * constants available to client code for interpreting the values of EE_Maintenance_Mode::level().
22
-     * level_0_not_in_maintenance means the site is NOT in maintenance mode (so everything's normal)
23
-     */
24
-    const level_0_not_in_maintenance = 0;
25
-
26
-    /**
27
-     * level_1_frontend_only_maintenance means that the site's frontend EE code should be completely disabled
28
-     * but the admin backend should be running as normal. Maybe an admin can view the frontend though
29
-     */
30
-    const level_1_frontend_only_maintenance = 1;
31
-
32
-    /**
33
-     * level_2_complete_maintenance means the frontend AND EE backend code are disabled. The only system running
34
-     * is the maintenance mode stuff, which will require users to update all addons, and then finish running all
35
-     * migration scripts before taking the site out of maintenance mode
36
-     */
37
-    const level_2_complete_maintenance = 2;
38
-
39
-    /**
40
-     * the name of the option which stores the current level of maintenance mode
41
-     */
42
-    const option_name_maintenance_mode = 'ee_maintenance_mode';
43
-
44
-
45
-    /**
46
-     * @var EE_Maintenance_Mode $_instance
47
-     */
48
-    private static $_instance;
49
-
50
-    /**
51
-     * @var EE_Registry $EE
52
-     */
53
-    protected $EE;
54
-
55
-
56
-
57
-    /**
58
-     * @singleton method used to instantiate class object
59
-     * @return EE_Maintenance_Mode
60
-     */
61
-    public static function instance()
62
-    {
63
-        // check if class object is instantiated
64
-        if (! self::$_instance instanceof EE_Maintenance_Mode) {
65
-            self::$_instance = new self();
66
-        }
67
-        return self::$_instance;
68
-    }
69
-
70
-
71
-
72
-    /**
73
-     * Resets maintenance mode (mostly just re-checks whether or not we should be in maintenance mode)
74
-     *
75
-     * @return EE_Maintenance_Mode
76
-     */
77
-    public static function reset()
78
-    {
79
-        self::instance()->set_maintenance_mode_if_db_old();
80
-        return self::instance();
81
-    }
82
-
83
-
84
-
85
-    /**
86
-     *private constructor to prevent direct creation
87
-     */
88
-    private function __construct()
89
-    {
90
-        // if M-Mode level 2 is engaged, we still need basic assets loaded
91
-        add_action('wp_enqueue_scripts', array($this, 'load_assets_required_for_m_mode'));
92
-        // shut 'er down down for maintenance ?
93
-        add_filter('the_content', array($this, 'the_content'), 2);
94
-        // add powered by EE msg
95
-        add_action('shutdown', array($this, 'display_maintenance_mode_notice'), 10);
96
-    }
97
-
98
-
99
-
100
-    /**
101
-     * retrieves the maintenance mode option value from the db
102
-     *
103
-     * @return int
104
-     */
105
-    public function real_level()
106
-    {
107
-        return get_option(self::option_name_maintenance_mode, EE_Maintenance_Mode::level_0_not_in_maintenance);
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * Returns whether or not the models reportedly are able to run queries or not
114
-     * (ie, if the system thinks their tables are present and up-to-date).
115
-     *
116
-     * @return boolean
117
-     */
118
-    public function models_can_query()
119
-    {
120
-        return $this->real_level() !== EE_Maintenance_Mode::level_2_complete_maintenance;
121
-    }
122
-
123
-
124
-
125
-    /**
126
-     * Determines whether or not we're in maintenance mode and what level. However, while the site
127
-     * is in level 1 maintenance, and an admin visits the frontend, this function makes it appear
128
-     * to them as if teh site isn't in maintenance mode.
129
-     * EE_Maintenance_Mode::level_0_not_in_maintenance => not in maintenance mode (in normal mode)
130
-     * EE_Maintenance_Mode::level_1_frontend_only_maintenance=> frontend-only maintenance mode
131
-     * EE_Maintenance_Mode::level_2_complete_maintenance => frontend and backend maintenance mode
132
-     *
133
-     * @return int
134
-     */
135
-    public function level()
136
-    {
137
-        $maintenance_mode_level = $this->real_level();
138
-        // if this is an admin request, we'll be honest... except if it's ajax, because that might be from the frontend
139
-        if (
140
-            $maintenance_mode_level === EE_Maintenance_Mode::level_1_frontend_only_maintenance// we're in level 1
141
-            && ((defined('DOING_AJAX') && DOING_AJAX) || ! is_admin()) // on non-ajax frontend requests
142
-            && current_user_can('administrator') // when the user is an admin
143
-        ) {
144
-            $maintenance_mode_level = EE_Maintenance_Mode::level_0_not_in_maintenance;
145
-        }
146
-        return $maintenance_mode_level;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * Determines if we need to put EE in maintenance mode because the database needs updating
153
-     *
154
-     * @return boolean true if DB is old and maintenance mode was triggered; false otherwise
155
-     */
156
-    public function set_maintenance_mode_if_db_old()
157
-    {
158
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
159
-        if (EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
160
-            update_option(self::option_name_maintenance_mode, self::level_2_complete_maintenance);
161
-            return true;
162
-        }
163
-        if ($this->level() === self::level_2_complete_maintenance) {
164
-            //we also want to handle the opposite: if the site is mm2, but there aren't any migrations to run
165
-            //then we shouldn't be in mm2. (Maybe an addon got deactivated?)
166
-            update_option(self::option_name_maintenance_mode, self::level_0_not_in_maintenance);
167
-            return false;
168
-        }
169
-        return false;
170
-    }
171
-
172
-
173
-
174
-    /**
175
-     * Updates the maintenance level on the site
176
-     *
177
-     * @param int $level
178
-     * @return void
179
-     */
180
-    public function set_maintenance_level($level)
181
-    {
182
-        do_action('AHEE__EE_Maintenance_Mode__set_maintenance_level', $level);
183
-        update_option(self::option_name_maintenance_mode, (int)$level);
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     * returns TRUE if M-Mode is engaged and the current request is not for the admin
190
-     *
191
-     * @return    string
192
-     */
193
-    public static function disable_frontend_for_maintenance()
194
-    {
195
-        return (! is_admin() && EE_Maintenance_Mode::instance()->level());
196
-    }
197
-
198
-
199
-
200
-    /**
201
-     * @return void
202
-     */
203
-    public function load_assets_required_for_m_mode()
204
-    {
205
-        if (
206
-            $this->real_level() === EE_Maintenance_Mode::level_2_complete_maintenance
207
-            && ! wp_script_is('espresso_core')
208
-        ) {
209
-            wp_register_style(
210
-                'espresso_default',
211
-                EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
212
-                array('dashicons'),
213
-                EVENT_ESPRESSO_VERSION
214
-            );
215
-            wp_enqueue_style('espresso_default');
216
-            wp_register_script(
217
-                'espresso_core',
218
-                EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
219
-                array('jquery'),
220
-                EVENT_ESPRESSO_VERSION,
221
-                true
222
-            );
223
-            wp_enqueue_script('espresso_core');
224
-        }
225
-    }
226
-
227
-
228
-
229
-    /**
230
-     * replacement EE CPT template that displays message notifying site visitors
231
-     * that EE has been temporarily placed into maintenance mode
232
-     * does NOT get called on non-EE-CPT requests
233
-     *
234
-     * @return    string
235
-     */
236
-    public static function template_include()
237
-    {
238
-        // shut 'er down down for maintenance ? then don't use any of our templates for our endpoints
239
-        return get_template_directory() . '/index.php';
240
-    }
241
-
242
-
243
-
244
-    /**
245
-     * displays message notifying site visitors that EE has been temporarily
246
-     * placed into maintenance mode when post_type != EE CPT
247
-     *
248
-     * @param string $the_content
249
-     * @return string
250
-     */
251
-    public function the_content($the_content)
252
-    {
253
-        // check if M-mode is engaged and for EE shortcode
254
-        if ($this->level() && strpos($the_content, '[ESPRESSO_') !== false) {
255
-            // this can eventually be moved to a template, or edited via admin. But for now...
256
-            $the_content = sprintf(
257
-                esc_html__(
258
-                    '%sMaintenance Mode%sEvent Registration has been temporarily closed while system maintenance is being performed. We\'re sorry for any inconveniences this may have caused. Please try back again later.%s',
259
-                    'event_espresso'
260
-                ),
261
-                '<h3>',
262
-                '</h3><p>',
263
-                '</p>'
264
-            );
265
-        }
266
-        return $the_content;
267
-    }
20
+	/**
21
+	 * constants available to client code for interpreting the values of EE_Maintenance_Mode::level().
22
+	 * level_0_not_in_maintenance means the site is NOT in maintenance mode (so everything's normal)
23
+	 */
24
+	const level_0_not_in_maintenance = 0;
25
+
26
+	/**
27
+	 * level_1_frontend_only_maintenance means that the site's frontend EE code should be completely disabled
28
+	 * but the admin backend should be running as normal. Maybe an admin can view the frontend though
29
+	 */
30
+	const level_1_frontend_only_maintenance = 1;
31
+
32
+	/**
33
+	 * level_2_complete_maintenance means the frontend AND EE backend code are disabled. The only system running
34
+	 * is the maintenance mode stuff, which will require users to update all addons, and then finish running all
35
+	 * migration scripts before taking the site out of maintenance mode
36
+	 */
37
+	const level_2_complete_maintenance = 2;
38
+
39
+	/**
40
+	 * the name of the option which stores the current level of maintenance mode
41
+	 */
42
+	const option_name_maintenance_mode = 'ee_maintenance_mode';
43
+
44
+
45
+	/**
46
+	 * @var EE_Maintenance_Mode $_instance
47
+	 */
48
+	private static $_instance;
49
+
50
+	/**
51
+	 * @var EE_Registry $EE
52
+	 */
53
+	protected $EE;
54
+
55
+
56
+
57
+	/**
58
+	 * @singleton method used to instantiate class object
59
+	 * @return EE_Maintenance_Mode
60
+	 */
61
+	public static function instance()
62
+	{
63
+		// check if class object is instantiated
64
+		if (! self::$_instance instanceof EE_Maintenance_Mode) {
65
+			self::$_instance = new self();
66
+		}
67
+		return self::$_instance;
68
+	}
69
+
70
+
71
+
72
+	/**
73
+	 * Resets maintenance mode (mostly just re-checks whether or not we should be in maintenance mode)
74
+	 *
75
+	 * @return EE_Maintenance_Mode
76
+	 */
77
+	public static function reset()
78
+	{
79
+		self::instance()->set_maintenance_mode_if_db_old();
80
+		return self::instance();
81
+	}
82
+
83
+
84
+
85
+	/**
86
+	 *private constructor to prevent direct creation
87
+	 */
88
+	private function __construct()
89
+	{
90
+		// if M-Mode level 2 is engaged, we still need basic assets loaded
91
+		add_action('wp_enqueue_scripts', array($this, 'load_assets_required_for_m_mode'));
92
+		// shut 'er down down for maintenance ?
93
+		add_filter('the_content', array($this, 'the_content'), 2);
94
+		// add powered by EE msg
95
+		add_action('shutdown', array($this, 'display_maintenance_mode_notice'), 10);
96
+	}
97
+
98
+
99
+
100
+	/**
101
+	 * retrieves the maintenance mode option value from the db
102
+	 *
103
+	 * @return int
104
+	 */
105
+	public function real_level()
106
+	{
107
+		return get_option(self::option_name_maintenance_mode, EE_Maintenance_Mode::level_0_not_in_maintenance);
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * Returns whether or not the models reportedly are able to run queries or not
114
+	 * (ie, if the system thinks their tables are present and up-to-date).
115
+	 *
116
+	 * @return boolean
117
+	 */
118
+	public function models_can_query()
119
+	{
120
+		return $this->real_level() !== EE_Maintenance_Mode::level_2_complete_maintenance;
121
+	}
122
+
123
+
124
+
125
+	/**
126
+	 * Determines whether or not we're in maintenance mode and what level. However, while the site
127
+	 * is in level 1 maintenance, and an admin visits the frontend, this function makes it appear
128
+	 * to them as if teh site isn't in maintenance mode.
129
+	 * EE_Maintenance_Mode::level_0_not_in_maintenance => not in maintenance mode (in normal mode)
130
+	 * EE_Maintenance_Mode::level_1_frontend_only_maintenance=> frontend-only maintenance mode
131
+	 * EE_Maintenance_Mode::level_2_complete_maintenance => frontend and backend maintenance mode
132
+	 *
133
+	 * @return int
134
+	 */
135
+	public function level()
136
+	{
137
+		$maintenance_mode_level = $this->real_level();
138
+		// if this is an admin request, we'll be honest... except if it's ajax, because that might be from the frontend
139
+		if (
140
+			$maintenance_mode_level === EE_Maintenance_Mode::level_1_frontend_only_maintenance// we're in level 1
141
+			&& ((defined('DOING_AJAX') && DOING_AJAX) || ! is_admin()) // on non-ajax frontend requests
142
+			&& current_user_can('administrator') // when the user is an admin
143
+		) {
144
+			$maintenance_mode_level = EE_Maintenance_Mode::level_0_not_in_maintenance;
145
+		}
146
+		return $maintenance_mode_level;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * Determines if we need to put EE in maintenance mode because the database needs updating
153
+	 *
154
+	 * @return boolean true if DB is old and maintenance mode was triggered; false otherwise
155
+	 */
156
+	public function set_maintenance_mode_if_db_old()
157
+	{
158
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
159
+		if (EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
160
+			update_option(self::option_name_maintenance_mode, self::level_2_complete_maintenance);
161
+			return true;
162
+		}
163
+		if ($this->level() === self::level_2_complete_maintenance) {
164
+			//we also want to handle the opposite: if the site is mm2, but there aren't any migrations to run
165
+			//then we shouldn't be in mm2. (Maybe an addon got deactivated?)
166
+			update_option(self::option_name_maintenance_mode, self::level_0_not_in_maintenance);
167
+			return false;
168
+		}
169
+		return false;
170
+	}
171
+
172
+
173
+
174
+	/**
175
+	 * Updates the maintenance level on the site
176
+	 *
177
+	 * @param int $level
178
+	 * @return void
179
+	 */
180
+	public function set_maintenance_level($level)
181
+	{
182
+		do_action('AHEE__EE_Maintenance_Mode__set_maintenance_level', $level);
183
+		update_option(self::option_name_maintenance_mode, (int)$level);
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 * returns TRUE if M-Mode is engaged and the current request is not for the admin
190
+	 *
191
+	 * @return    string
192
+	 */
193
+	public static function disable_frontend_for_maintenance()
194
+	{
195
+		return (! is_admin() && EE_Maintenance_Mode::instance()->level());
196
+	}
197
+
198
+
199
+
200
+	/**
201
+	 * @return void
202
+	 */
203
+	public function load_assets_required_for_m_mode()
204
+	{
205
+		if (
206
+			$this->real_level() === EE_Maintenance_Mode::level_2_complete_maintenance
207
+			&& ! wp_script_is('espresso_core')
208
+		) {
209
+			wp_register_style(
210
+				'espresso_default',
211
+				EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
212
+				array('dashicons'),
213
+				EVENT_ESPRESSO_VERSION
214
+			);
215
+			wp_enqueue_style('espresso_default');
216
+			wp_register_script(
217
+				'espresso_core',
218
+				EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
219
+				array('jquery'),
220
+				EVENT_ESPRESSO_VERSION,
221
+				true
222
+			);
223
+			wp_enqueue_script('espresso_core');
224
+		}
225
+	}
226
+
227
+
228
+
229
+	/**
230
+	 * replacement EE CPT template that displays message notifying site visitors
231
+	 * that EE has been temporarily placed into maintenance mode
232
+	 * does NOT get called on non-EE-CPT requests
233
+	 *
234
+	 * @return    string
235
+	 */
236
+	public static function template_include()
237
+	{
238
+		// shut 'er down down for maintenance ? then don't use any of our templates for our endpoints
239
+		return get_template_directory() . '/index.php';
240
+	}
241
+
242
+
243
+
244
+	/**
245
+	 * displays message notifying site visitors that EE has been temporarily
246
+	 * placed into maintenance mode when post_type != EE CPT
247
+	 *
248
+	 * @param string $the_content
249
+	 * @return string
250
+	 */
251
+	public function the_content($the_content)
252
+	{
253
+		// check if M-mode is engaged and for EE shortcode
254
+		if ($this->level() && strpos($the_content, '[ESPRESSO_') !== false) {
255
+			// this can eventually be moved to a template, or edited via admin. But for now...
256
+			$the_content = sprintf(
257
+				esc_html__(
258
+					'%sMaintenance Mode%sEvent Registration has been temporarily closed while system maintenance is being performed. We\'re sorry for any inconveniences this may have caused. Please try back again later.%s',
259
+					'event_espresso'
260
+				),
261
+				'<h3>',
262
+				'</h3><p>',
263
+				'</p>'
264
+			);
265
+		}
266
+		return $the_content;
267
+	}
268 268
 
269 269
 
270 270
 
271
-    /**
272
-     * displays message on frontend of site notifying admin that EE has been temporarily placed into maintenance mode
273
-     */
274
-    public function display_maintenance_mode_notice()
275
-    {
276
-        // check if M-mode is engaged and for EE shortcode
277
-        if (
278
-            ! (defined('DOING_AJAX') && DOING_AJAX)
279
-            && $this->real_level()
280
-            && ! is_admin()
281
-            && current_user_can('administrator')
282
-            && EE_Registry::instance()->REQ->is_espresso_page()
283
-        ) {
284
-            printf(
285
-                esc_html__(
286
-                    '%sclose%sEvent Registration is currently disabled because Event Espresso has been placed into Maintenance Mode. To change Maintenance Mode settings, click here %sEE Maintenance Mode Admin Page%s',
287
-                    'event_espresso'
288
-                ),
289
-                '<div id="ee-m-mode-admin-notice-dv" class="ee-really-important-notice-dv"><a class="close-espresso-notice" title="',
290
-                '"><span class="dashicons dashicons-no"></span></a><p>',
291
-                ' &raquo; <a href="' . add_query_arg(
292
-                    array('page' => 'espresso_maintenance_settings'), admin_url('admin.php')
293
-                ) . '">',
294
-                '</a></p></div>'
295
-            );
296
-        }
297
-    }
298
-    // espresso-notices important-notice ee-attention
271
+	/**
272
+	 * displays message on frontend of site notifying admin that EE has been temporarily placed into maintenance mode
273
+	 */
274
+	public function display_maintenance_mode_notice()
275
+	{
276
+		// check if M-mode is engaged and for EE shortcode
277
+		if (
278
+			! (defined('DOING_AJAX') && DOING_AJAX)
279
+			&& $this->real_level()
280
+			&& ! is_admin()
281
+			&& current_user_can('administrator')
282
+			&& EE_Registry::instance()->REQ->is_espresso_page()
283
+		) {
284
+			printf(
285
+				esc_html__(
286
+					'%sclose%sEvent Registration is currently disabled because Event Espresso has been placed into Maintenance Mode. To change Maintenance Mode settings, click here %sEE Maintenance Mode Admin Page%s',
287
+					'event_espresso'
288
+				),
289
+				'<div id="ee-m-mode-admin-notice-dv" class="ee-really-important-notice-dv"><a class="close-espresso-notice" title="',
290
+				'"><span class="dashicons dashicons-no"></span></a><p>',
291
+				' &raquo; <a href="' . add_query_arg(
292
+					array('page' => 'espresso_maintenance_settings'), admin_url('admin.php')
293
+				) . '">',
294
+				'</a></p></div>'
295
+			);
296
+		}
297
+	}
298
+	// espresso-notices important-notice ee-attention
299 299
 
300 300
 
301 301
 
302
-    /**
303
-     * override magic methods
304
-     */
305
-    final public function __destruct()
306
-    {
307
-    }
302
+	/**
303
+	 * override magic methods
304
+	 */
305
+	final public function __destruct()
306
+	{
307
+	}
308 308
 
309 309
 
310 310
 
311
-    final public function __call($a, $b)
312
-    {
313
-    }
311
+	final public function __call($a, $b)
312
+	{
313
+	}
314 314
 
315 315
 
316 316
 
317
-    final public function __get($a)
318
-    {
319
-    }
317
+	final public function __get($a)
318
+	{
319
+	}
320 320
 
321 321
 
322 322
 
323
-    final public function __set($a, $b)
324
-    {
325
-    }
323
+	final public function __set($a, $b)
324
+	{
325
+	}
326 326
 
327 327
 
328 328
 
329
-    final public function __isset($a)
330
-    {
331
-    }
329
+	final public function __isset($a)
330
+	{
331
+	}
332 332
 
333 333
 
334 334
 
335
-    final public function __unset($a)
336
-    {
337
-    }
335
+	final public function __unset($a)
336
+	{
337
+	}
338 338
 
339 339
 
340 340
 
341
-    final public function __sleep()
342
-    {
343
-        return array();
344
-    }
341
+	final public function __sleep()
342
+	{
343
+		return array();
344
+	}
345 345
 
346 346
 
347 347
 
348
-    final public function __wakeup()
349
-    {
350
-    }
348
+	final public function __wakeup()
349
+	{
350
+	}
351 351
 
352 352
 
353 353
 
354
-    final public function __invoke()
355
-    {
356
-    }
354
+	final public function __invoke()
355
+	{
356
+	}
357 357
 
358 358
 
359 359
 
360
-    final public static function __set_state($a = null)
361
-    {
362
-        return EE_Maintenance_Mode::instance();
363
-    }
360
+	final public static function __set_state($a = null)
361
+	{
362
+		return EE_Maintenance_Mode::instance();
363
+	}
364 364
 
365 365
 
366 366
 
367
-    final public function __clone()
368
-    {
369
-    }
367
+	final public function __clone()
368
+	{
369
+	}
370 370
 
371 371
 
372 372
 
373
-    final public static function __callStatic($a, $b)
374
-    {
375
-    }
373
+	final public static function __callStatic($a, $b)
374
+	{
375
+	}
376 376
 
377 377
 }
378 378
 // End of file EE_Maintenance_Mode.core.php
Please login to merge, or discard this patch.
core/db_models/EEM_Attendee.model.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -351,7 +351,7 @@
 block discarded – undo
351 351
      * retrieve  a single attendee from db via their ID
352 352
      *
353 353
      * @param $ATT_ID
354
-     * @return mixed array on success, FALSE on fail
354
+     * @return EE_Base_Class|null array on success, FALSE on fail
355 355
      * @deprecated
356 356
      */
357 357
     public function get_attendee_by_ID($ATT_ID = false)
Please login to merge, or discard this patch.
Indentation   +417 added lines, -417 removed lines patch added patch discarded remove patch
@@ -16,431 +16,431 @@
 block discarded – undo
16 16
 class EEM_Attendee extends EEM_CPT_Base
17 17
 {
18 18
 
19
-    // private instance of the Attendee object
20
-    protected static $_instance = null;
19
+	// private instance of the Attendee object
20
+	protected static $_instance = null;
21 21
 
22
-    /**
23
-     * QST_system for questions are strings not integers now,
24
-     * so these constants are deprecated.
25
-     * Please instead use the EEM_Attendee::system_question_* constants
26
-     *
27
-     * @deprecated
28
-     */
29
-    const fname_question_id = 1;
22
+	/**
23
+	 * QST_system for questions are strings not integers now,
24
+	 * so these constants are deprecated.
25
+	 * Please instead use the EEM_Attendee::system_question_* constants
26
+	 *
27
+	 * @deprecated
28
+	 */
29
+	const fname_question_id = 1;
30 30
 
31
-    /**
32
-     * @deprecated
33
-     */
34
-    const lname_question_id = 2;
31
+	/**
32
+	 * @deprecated
33
+	 */
34
+	const lname_question_id = 2;
35 35
 
36 36
 
37
-    /**
38
-     * @deprecated
39
-     */
40
-    const email_question_id = 3;
37
+	/**
38
+	 * @deprecated
39
+	 */
40
+	const email_question_id = 3;
41 41
 
42 42
 
43
-    /**
44
-     * @deprecated
45
-     */
46
-    const address_question_id = 4;
43
+	/**
44
+	 * @deprecated
45
+	 */
46
+	const address_question_id = 4;
47 47
 
48 48
 
49
-    /**
50
-     * @deprecated
51
-     */
52
-    const address2_question_id = 5;
53
-
54
-
55
-    /**
56
-     * @deprecated
57
-     */
58
-    const city_question_id = 6;
59
-
60
-
61
-    /**
62
-     * @deprecated
63
-     */
64
-    const state_question_id = 7;
65
-
66
-
67
-    /**
68
-     * @deprecated
69
-     */
70
-    const country_question_id = 8;
71
-
72
-
73
-    /**
74
-     * @deprecated
75
-     */
76
-    const zip_question_id = 9;
77
-
78
-
79
-    /**
80
-     * @deprecated
81
-     */
82
-    const phone_question_id = 10;
83
-
84
-    /**
85
-     * When looking for questions that correspond to attendee fields,
86
-     * look for the question with this QST_system value.
87
-     * These replace the old constants like EEM_Attendee::*_question_id
88
-     */
89
-    const system_question_fname = 'fname';
90
-
91
-    const system_question_lname = 'lname';
92
-
93
-    const system_question_email = 'email';
94
-
95
-    const system_question_address = 'address';
96
-
97
-    const system_question_address2 = 'address2';
98
-
99
-    const system_question_city = 'city';
100
-
101
-    const system_question_state = 'state';
102
-
103
-    const system_question_country = 'country';
104
-
105
-    const system_question_zip = 'zip';
106
-
107
-    const system_question_phone = 'phone';
108
-
109
-    /**
110
-     * Keys are all the EEM_Attendee::system_question_* constants, which are
111
-     * also all the values of QST_system in the questions table, and values
112
-     * are their corresponding Attendee field names
113
-     *
114
-     * @var array
115
-     */
116
-    protected $_system_question_to_attendee_field_name = array(
117
-        EEM_Attendee::system_question_fname    => 'ATT_fname',
118
-        EEM_Attendee::system_question_lname    => 'ATT_lname',
119
-        EEM_Attendee::system_question_email    => 'ATT_email',
120
-        EEM_Attendee::system_question_address  => 'ATT_address',
121
-        EEM_Attendee::system_question_address2 => 'ATT_address2',
122
-        EEM_Attendee::system_question_city     => 'ATT_city',
123
-        EEM_Attendee::system_question_state    => 'STA_ID',
124
-        EEM_Attendee::system_question_country  => 'CNT_ISO',
125
-        EEM_Attendee::system_question_zip      => 'ATT_zip',
126
-        EEM_Attendee::system_question_phone    => 'ATT_phone',
127
-    );
128
-
129
-
130
-
131
-    /**
132
-     * EEM_Attendee constructor.
133
-     *
134
-     * @param null $timezone
135
-     * @throws EE_Error
136
-     */
137
-    protected function __construct($timezone = null)
138
-    {
139
-        $this->singular_item = esc_html__('Attendee', 'event_espresso');
140
-        $this->plural_item = esc_html__('Attendees', 'event_espresso');
141
-        $this->_tables = array(
142
-            'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
143
-            'Attendee_Meta' => new EE_Secondary_Table(
144
-                'esp_attendee_meta',
145
-                'ATTM_ID',
146
-                'ATT_ID'
147
-            ),
148
-        );
149
-        $this->_fields = array(
150
-            'Attendee_CPT'  => array(
151
-                'ATT_ID'        => new EE_Primary_Key_Int_Field(
152
-                    'ID',
153
-                    esc_html__('Attendee ID', 'event_espresso')
154
-                ),
155
-                'ATT_full_name' => new EE_Plain_Text_Field(
156
-                    'post_title',
157
-                    esc_html__('Attendee Full Name', 'event_espresso'),
158
-                    false,
159
-                    esc_html__('Unknown', 'event_espresso')
160
-                ),
161
-                'ATT_bio'       => new EE_Post_Content_Field(
162
-                    'post_content',
163
-                    esc_html__('Attendee Biography', 'event_espresso'),
164
-                    false,
165
-                    esc_html__('No Biography Provided', 'event_espresso')
166
-                ),
167
-                'ATT_slug'      => new EE_Slug_Field(
168
-                    'post_name',
169
-                    esc_html__('Attendee URL Slug', 'event_espresso'),
170
-                    false
171
-                ),
172
-                'ATT_created'   => new EE_Datetime_Field(
173
-                    'post_date',
174
-                    esc_html__('Time Attendee Created', 'event_espresso'),
175
-                    false,
176
-                    EE_Datetime_Field::now
177
-                ),
178
-                'ATT_short_bio' => new EE_Simple_HTML_Field(
179
-                    'post_excerpt',
180
-                    esc_html__('Attendee Short Biography', 'event_espresso'),
181
-                    true,
182
-                    esc_html__('No Biography Provided', 'event_espresso')
183
-                ),
184
-                'ATT_modified'  => new EE_Datetime_Field(
185
-                    'post_modified',
186
-                    esc_html__('Time Attendee Last Modified', 'event_espresso'),
187
-                    false,
188
-                    EE_Datetime_Field::now
189
-                ),
190
-                'ATT_author'    => new EE_WP_User_Field(
191
-                    'post_author',
192
-                    esc_html__('Creator ID of the first Event attended', 'event_espresso'),
193
-                    false
194
-                ),
195
-                'ATT_parent'    => new EE_DB_Only_Int_Field(
196
-                    'post_parent',
197
-                    esc_html__('Parent Attendee (unused)', 'event_espresso'),
198
-                    false,
199
-                    0
200
-                ),
201
-                'post_type'     => new EE_WP_Post_Type_Field('espresso_attendees'),
202
-                'status'        => new EE_WP_Post_Status_Field(
203
-                    'post_status',
204
-                    esc_html__('Attendee Status', 'event_espresso'),
205
-                    false,
206
-                    'publish'
207
-                ),
208
-            ),
209
-            'Attendee_Meta' => array(
210
-                'ATTM_ID'      => new EE_DB_Only_Int_Field(
211
-                    'ATTM_ID',
212
-                    esc_html__('Attendee Meta Row ID', 'event_espresso'),
213
-                    false
214
-                ),
215
-                'ATT_ID_fk'    => new EE_DB_Only_Int_Field(
216
-                    'ATT_ID',
217
-                    esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
218
-                    false
219
-                ),
220
-                'ATT_fname'    => new EE_Plain_Text_Field(
221
-                    'ATT_fname',
222
-                    esc_html__('First Name', 'event_espresso'),
223
-                    true,
224
-                    ''
225
-                ),
226
-                'ATT_lname'    => new EE_Plain_Text_Field(
227
-                    'ATT_lname', esc_html__('Last Name', 'event_espresso'),
228
-                    true,
229
-                    ''
230
-                ),
231
-                'ATT_address'  => new EE_Plain_Text_Field(
232
-                    'ATT_address',
233
-                    esc_html__('Address Part 1', 'event_espresso'),
234
-                    true,
235
-                    ''
236
-                ),
237
-                'ATT_address2' => new EE_Plain_Text_Field(
238
-                    'ATT_address2',
239
-                    esc_html__('Address Part 2', 'event_espresso'),
240
-                    true,
241
-                    ''
242
-                ),
243
-                'ATT_city'     => new EE_Plain_Text_Field(
244
-                    'ATT_city',
245
-                    esc_html__('City', 'event_espresso'),
246
-                    true,
247
-                    ''
248
-                ),
249
-                'STA_ID'       => new EE_Foreign_Key_Int_Field(
250
-                    'STA_ID',
251
-                    esc_html__('State', 'event_espresso'),
252
-                    true,
253
-                    0,
254
-                    'State'
255
-                ),
256
-                'CNT_ISO'      => new EE_Foreign_Key_String_Field(
257
-                    'CNT_ISO',
258
-                    esc_html__('Country', 'event_espresso'),
259
-                    true,
260
-                    '',
261
-                    'Country'
262
-                ),
263
-                'ATT_zip'      => new EE_Plain_Text_Field(
264
-                    'ATT_zip',
265
-                    esc_html__('ZIP/Postal Code', 'event_espresso'),
266
-                    true,
267
-                    ''
268
-                ),
269
-                'ATT_email'    => new EE_Email_Field(
270
-                    'ATT_email',
271
-                    esc_html__('Email Address', 'event_espresso'),
272
-                    true,
273
-                    ''
274
-                ),
275
-                'ATT_phone'    => new EE_Plain_Text_Field(
276
-                    'ATT_phone',
277
-                    esc_html__('Phone', 'event_espresso'),
278
-                    true,
279
-                    ''
280
-                ),
281
-            ),
282
-        );
283
-        $this->_model_relations = array(
284
-            'Registration'      => new EE_Has_Many_Relation(),
285
-            'State'             => new EE_Belongs_To_Relation(),
286
-            'Country'           => new EE_Belongs_To_Relation(),
287
-            'Event'             => new EE_HABTM_Relation('Registration', false),
288
-            'WP_User'           => new EE_Belongs_To_Relation(),
289
-            'Message'           => new EE_Has_Many_Any_Relation(false),
290
-            //allow deletion of attendees even if they have messages in the queue for them.
291
-            'Term_Relationship' => new EE_Has_Many_Relation(),
292
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
293
-        );
294
-        $this->_caps_slug = 'contacts';
295
-        parent::__construct($timezone);
296
-    }
297
-
298
-
299
-
300
-    /**
301
-     * Gets the name of the field on the attendee model corresponding to the system question string
302
-     * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
303
-     *
304
-     * @param string $system_question_string
305
-     * @return string|null if not found
306
-     */
307
-    public function get_attendee_field_for_system_question($system_question_string)
308
-    {
309
-        return isset($this->_system_question_to_attendee_field_name[$system_question_string])
310
-            ? $this->_system_question_to_attendee_field_name[$system_question_string]
311
-            : null;
312
-    }
313
-
314
-
315
-
316
-    /**
317
-     * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
318
-     *
319
-     * @return array
320
-     */
321
-    public function system_question_to_attendee_field_mapping()
322
-    {
323
-        return $this->_system_question_to_attendee_field_name;
324
-    }
325
-
326
-
327
-
328
-    /**
329
-     * Gets all the attendees for a transaction (by using the esp_registration as a join table)
330
-     *
331
-     * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
332
-     * @return EE_Attendee[]|EE_Base_Class[]
333
-     * @throws EE_Error
334
-     */
335
-    public function get_attendees_for_transaction($transaction_id_or_obj)
336
-    {
337
-        return $this->get_all(
338
-            array(
339
-                array(
340
-                    'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
341
-                        ? $transaction_id_or_obj->ID()
342
-                        : $transaction_id_or_obj,
343
-                ),
344
-            )
345
-        );
346
-    }
347
-
348
-
349
-
350
-    /**
351
-     * retrieve  a single attendee from db via their ID
352
-     *
353
-     * @param $ATT_ID
354
-     * @return mixed array on success, FALSE on fail
355
-     * @deprecated
356
-     */
357
-    public function get_attendee_by_ID($ATT_ID = false)
358
-    {
359
-        // retrieve a particular EE_Attendee
360
-        return $this->get_one_by_ID($ATT_ID);
361
-    }
362
-
363
-
364
-
365
-    /**
366
-     * retrieve  a single attendee from db via their ID
367
-     *
368
-     * @param array $where_cols_n_values
369
-     * @return mixed array on success, FALSE on fail
370
-     * @throws EE_Error
371
-     */
372
-    public function get_attendee($where_cols_n_values = array())
373
-    {
374
-        if (empty($where_cols_n_values)) {
375
-            return false;
376
-        }
377
-        $attendee = $this->get_all(array($where_cols_n_values));
378
-        if (! empty($attendee)) {
379
-            return array_shift($attendee);
380
-        }
381
-        return false;
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * Search for an existing Attendee record in the DB
388
-     *
389
-     * @param array $where_cols_n_values
390
-     * @return bool|mixed
391
-     * @throws EE_Error
392
-     */
393
-    public function find_existing_attendee($where_cols_n_values = null)
394
-    {
395
-        // search by combo of first and last names plus the email address
396
-        $attendee_data_keys = array(
397
-            'ATT_fname' => $this->_ATT_fname,
398
-            'ATT_lname' => $this->_ATT_lname,
399
-            'ATT_email' => $this->_ATT_email,
400
-        );
401
-        // no search params means attendee object already exists.
402
-        $where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
403
-            ? $where_cols_n_values
404
-            : $attendee_data_keys;
405
-        $valid_data = true;
406
-        // check for required values
407
-        $valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
408
-            ? $valid_data
409
-            : false;
410
-        $valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
411
-            ? $valid_data
412
-            : false;
413
-        $valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
414
-            ? $valid_data
415
-            : false;
416
-        if ($valid_data) {
417
-            $attendee = $this->get_attendee($where_cols_n_values);
418
-            if ($attendee instanceof EE_Attendee) {
419
-                return $attendee;
420
-            }
421
-        }
422
-        return false;
423
-    }
424
-
425
-
426
-
427
-    /**
428
-     * Takes an incoming array of EE_Registration ids
429
-     * and sends back a list of corresponding non duplicate EE_Attendee objects.
430
-     *
431
-     * @since  4.3.0
432
-     * @param  array $ids array of EE_Registration ids
433
-     * @return EE_Attendee[]|EE_Base_Class[]
434
-     * @throws EE_Error
435
-     */
436
-    public function get_array_of_contacts_from_reg_ids($ids)
437
-    {
438
-        $ids = (array)$ids;
439
-        $_where = array(
440
-            'Registration.REG_ID' => array('in', $ids),
441
-        );
442
-        return $this->get_all(array($_where));
443
-    }
49
+	/**
50
+	 * @deprecated
51
+	 */
52
+	const address2_question_id = 5;
53
+
54
+
55
+	/**
56
+	 * @deprecated
57
+	 */
58
+	const city_question_id = 6;
59
+
60
+
61
+	/**
62
+	 * @deprecated
63
+	 */
64
+	const state_question_id = 7;
65
+
66
+
67
+	/**
68
+	 * @deprecated
69
+	 */
70
+	const country_question_id = 8;
71
+
72
+
73
+	/**
74
+	 * @deprecated
75
+	 */
76
+	const zip_question_id = 9;
77
+
78
+
79
+	/**
80
+	 * @deprecated
81
+	 */
82
+	const phone_question_id = 10;
83
+
84
+	/**
85
+	 * When looking for questions that correspond to attendee fields,
86
+	 * look for the question with this QST_system value.
87
+	 * These replace the old constants like EEM_Attendee::*_question_id
88
+	 */
89
+	const system_question_fname = 'fname';
90
+
91
+	const system_question_lname = 'lname';
92
+
93
+	const system_question_email = 'email';
94
+
95
+	const system_question_address = 'address';
96
+
97
+	const system_question_address2 = 'address2';
98
+
99
+	const system_question_city = 'city';
100
+
101
+	const system_question_state = 'state';
102
+
103
+	const system_question_country = 'country';
104
+
105
+	const system_question_zip = 'zip';
106
+
107
+	const system_question_phone = 'phone';
108
+
109
+	/**
110
+	 * Keys are all the EEM_Attendee::system_question_* constants, which are
111
+	 * also all the values of QST_system in the questions table, and values
112
+	 * are their corresponding Attendee field names
113
+	 *
114
+	 * @var array
115
+	 */
116
+	protected $_system_question_to_attendee_field_name = array(
117
+		EEM_Attendee::system_question_fname    => 'ATT_fname',
118
+		EEM_Attendee::system_question_lname    => 'ATT_lname',
119
+		EEM_Attendee::system_question_email    => 'ATT_email',
120
+		EEM_Attendee::system_question_address  => 'ATT_address',
121
+		EEM_Attendee::system_question_address2 => 'ATT_address2',
122
+		EEM_Attendee::system_question_city     => 'ATT_city',
123
+		EEM_Attendee::system_question_state    => 'STA_ID',
124
+		EEM_Attendee::system_question_country  => 'CNT_ISO',
125
+		EEM_Attendee::system_question_zip      => 'ATT_zip',
126
+		EEM_Attendee::system_question_phone    => 'ATT_phone',
127
+	);
128
+
129
+
130
+
131
+	/**
132
+	 * EEM_Attendee constructor.
133
+	 *
134
+	 * @param null $timezone
135
+	 * @throws EE_Error
136
+	 */
137
+	protected function __construct($timezone = null)
138
+	{
139
+		$this->singular_item = esc_html__('Attendee', 'event_espresso');
140
+		$this->plural_item = esc_html__('Attendees', 'event_espresso');
141
+		$this->_tables = array(
142
+			'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
143
+			'Attendee_Meta' => new EE_Secondary_Table(
144
+				'esp_attendee_meta',
145
+				'ATTM_ID',
146
+				'ATT_ID'
147
+			),
148
+		);
149
+		$this->_fields = array(
150
+			'Attendee_CPT'  => array(
151
+				'ATT_ID'        => new EE_Primary_Key_Int_Field(
152
+					'ID',
153
+					esc_html__('Attendee ID', 'event_espresso')
154
+				),
155
+				'ATT_full_name' => new EE_Plain_Text_Field(
156
+					'post_title',
157
+					esc_html__('Attendee Full Name', 'event_espresso'),
158
+					false,
159
+					esc_html__('Unknown', 'event_espresso')
160
+				),
161
+				'ATT_bio'       => new EE_Post_Content_Field(
162
+					'post_content',
163
+					esc_html__('Attendee Biography', 'event_espresso'),
164
+					false,
165
+					esc_html__('No Biography Provided', 'event_espresso')
166
+				),
167
+				'ATT_slug'      => new EE_Slug_Field(
168
+					'post_name',
169
+					esc_html__('Attendee URL Slug', 'event_espresso'),
170
+					false
171
+				),
172
+				'ATT_created'   => new EE_Datetime_Field(
173
+					'post_date',
174
+					esc_html__('Time Attendee Created', 'event_espresso'),
175
+					false,
176
+					EE_Datetime_Field::now
177
+				),
178
+				'ATT_short_bio' => new EE_Simple_HTML_Field(
179
+					'post_excerpt',
180
+					esc_html__('Attendee Short Biography', 'event_espresso'),
181
+					true,
182
+					esc_html__('No Biography Provided', 'event_espresso')
183
+				),
184
+				'ATT_modified'  => new EE_Datetime_Field(
185
+					'post_modified',
186
+					esc_html__('Time Attendee Last Modified', 'event_espresso'),
187
+					false,
188
+					EE_Datetime_Field::now
189
+				),
190
+				'ATT_author'    => new EE_WP_User_Field(
191
+					'post_author',
192
+					esc_html__('Creator ID of the first Event attended', 'event_espresso'),
193
+					false
194
+				),
195
+				'ATT_parent'    => new EE_DB_Only_Int_Field(
196
+					'post_parent',
197
+					esc_html__('Parent Attendee (unused)', 'event_espresso'),
198
+					false,
199
+					0
200
+				),
201
+				'post_type'     => new EE_WP_Post_Type_Field('espresso_attendees'),
202
+				'status'        => new EE_WP_Post_Status_Field(
203
+					'post_status',
204
+					esc_html__('Attendee Status', 'event_espresso'),
205
+					false,
206
+					'publish'
207
+				),
208
+			),
209
+			'Attendee_Meta' => array(
210
+				'ATTM_ID'      => new EE_DB_Only_Int_Field(
211
+					'ATTM_ID',
212
+					esc_html__('Attendee Meta Row ID', 'event_espresso'),
213
+					false
214
+				),
215
+				'ATT_ID_fk'    => new EE_DB_Only_Int_Field(
216
+					'ATT_ID',
217
+					esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
218
+					false
219
+				),
220
+				'ATT_fname'    => new EE_Plain_Text_Field(
221
+					'ATT_fname',
222
+					esc_html__('First Name', 'event_espresso'),
223
+					true,
224
+					''
225
+				),
226
+				'ATT_lname'    => new EE_Plain_Text_Field(
227
+					'ATT_lname', esc_html__('Last Name', 'event_espresso'),
228
+					true,
229
+					''
230
+				),
231
+				'ATT_address'  => new EE_Plain_Text_Field(
232
+					'ATT_address',
233
+					esc_html__('Address Part 1', 'event_espresso'),
234
+					true,
235
+					''
236
+				),
237
+				'ATT_address2' => new EE_Plain_Text_Field(
238
+					'ATT_address2',
239
+					esc_html__('Address Part 2', 'event_espresso'),
240
+					true,
241
+					''
242
+				),
243
+				'ATT_city'     => new EE_Plain_Text_Field(
244
+					'ATT_city',
245
+					esc_html__('City', 'event_espresso'),
246
+					true,
247
+					''
248
+				),
249
+				'STA_ID'       => new EE_Foreign_Key_Int_Field(
250
+					'STA_ID',
251
+					esc_html__('State', 'event_espresso'),
252
+					true,
253
+					0,
254
+					'State'
255
+				),
256
+				'CNT_ISO'      => new EE_Foreign_Key_String_Field(
257
+					'CNT_ISO',
258
+					esc_html__('Country', 'event_espresso'),
259
+					true,
260
+					'',
261
+					'Country'
262
+				),
263
+				'ATT_zip'      => new EE_Plain_Text_Field(
264
+					'ATT_zip',
265
+					esc_html__('ZIP/Postal Code', 'event_espresso'),
266
+					true,
267
+					''
268
+				),
269
+				'ATT_email'    => new EE_Email_Field(
270
+					'ATT_email',
271
+					esc_html__('Email Address', 'event_espresso'),
272
+					true,
273
+					''
274
+				),
275
+				'ATT_phone'    => new EE_Plain_Text_Field(
276
+					'ATT_phone',
277
+					esc_html__('Phone', 'event_espresso'),
278
+					true,
279
+					''
280
+				),
281
+			),
282
+		);
283
+		$this->_model_relations = array(
284
+			'Registration'      => new EE_Has_Many_Relation(),
285
+			'State'             => new EE_Belongs_To_Relation(),
286
+			'Country'           => new EE_Belongs_To_Relation(),
287
+			'Event'             => new EE_HABTM_Relation('Registration', false),
288
+			'WP_User'           => new EE_Belongs_To_Relation(),
289
+			'Message'           => new EE_Has_Many_Any_Relation(false),
290
+			//allow deletion of attendees even if they have messages in the queue for them.
291
+			'Term_Relationship' => new EE_Has_Many_Relation(),
292
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
293
+		);
294
+		$this->_caps_slug = 'contacts';
295
+		parent::__construct($timezone);
296
+	}
297
+
298
+
299
+
300
+	/**
301
+	 * Gets the name of the field on the attendee model corresponding to the system question string
302
+	 * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
303
+	 *
304
+	 * @param string $system_question_string
305
+	 * @return string|null if not found
306
+	 */
307
+	public function get_attendee_field_for_system_question($system_question_string)
308
+	{
309
+		return isset($this->_system_question_to_attendee_field_name[$system_question_string])
310
+			? $this->_system_question_to_attendee_field_name[$system_question_string]
311
+			: null;
312
+	}
313
+
314
+
315
+
316
+	/**
317
+	 * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
318
+	 *
319
+	 * @return array
320
+	 */
321
+	public function system_question_to_attendee_field_mapping()
322
+	{
323
+		return $this->_system_question_to_attendee_field_name;
324
+	}
325
+
326
+
327
+
328
+	/**
329
+	 * Gets all the attendees for a transaction (by using the esp_registration as a join table)
330
+	 *
331
+	 * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
332
+	 * @return EE_Attendee[]|EE_Base_Class[]
333
+	 * @throws EE_Error
334
+	 */
335
+	public function get_attendees_for_transaction($transaction_id_or_obj)
336
+	{
337
+		return $this->get_all(
338
+			array(
339
+				array(
340
+					'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
341
+						? $transaction_id_or_obj->ID()
342
+						: $transaction_id_or_obj,
343
+				),
344
+			)
345
+		);
346
+	}
347
+
348
+
349
+
350
+	/**
351
+	 * retrieve  a single attendee from db via their ID
352
+	 *
353
+	 * @param $ATT_ID
354
+	 * @return mixed array on success, FALSE on fail
355
+	 * @deprecated
356
+	 */
357
+	public function get_attendee_by_ID($ATT_ID = false)
358
+	{
359
+		// retrieve a particular EE_Attendee
360
+		return $this->get_one_by_ID($ATT_ID);
361
+	}
362
+
363
+
364
+
365
+	/**
366
+	 * retrieve  a single attendee from db via their ID
367
+	 *
368
+	 * @param array $where_cols_n_values
369
+	 * @return mixed array on success, FALSE on fail
370
+	 * @throws EE_Error
371
+	 */
372
+	public function get_attendee($where_cols_n_values = array())
373
+	{
374
+		if (empty($where_cols_n_values)) {
375
+			return false;
376
+		}
377
+		$attendee = $this->get_all(array($where_cols_n_values));
378
+		if (! empty($attendee)) {
379
+			return array_shift($attendee);
380
+		}
381
+		return false;
382
+	}
383
+
384
+
385
+
386
+	/**
387
+	 * Search for an existing Attendee record in the DB
388
+	 *
389
+	 * @param array $where_cols_n_values
390
+	 * @return bool|mixed
391
+	 * @throws EE_Error
392
+	 */
393
+	public function find_existing_attendee($where_cols_n_values = null)
394
+	{
395
+		// search by combo of first and last names plus the email address
396
+		$attendee_data_keys = array(
397
+			'ATT_fname' => $this->_ATT_fname,
398
+			'ATT_lname' => $this->_ATT_lname,
399
+			'ATT_email' => $this->_ATT_email,
400
+		);
401
+		// no search params means attendee object already exists.
402
+		$where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
403
+			? $where_cols_n_values
404
+			: $attendee_data_keys;
405
+		$valid_data = true;
406
+		// check for required values
407
+		$valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
408
+			? $valid_data
409
+			: false;
410
+		$valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
411
+			? $valid_data
412
+			: false;
413
+		$valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
414
+			? $valid_data
415
+			: false;
416
+		if ($valid_data) {
417
+			$attendee = $this->get_attendee($where_cols_n_values);
418
+			if ($attendee instanceof EE_Attendee) {
419
+				return $attendee;
420
+			}
421
+		}
422
+		return false;
423
+	}
424
+
425
+
426
+
427
+	/**
428
+	 * Takes an incoming array of EE_Registration ids
429
+	 * and sends back a list of corresponding non duplicate EE_Attendee objects.
430
+	 *
431
+	 * @since  4.3.0
432
+	 * @param  array $ids array of EE_Registration ids
433
+	 * @return EE_Attendee[]|EE_Base_Class[]
434
+	 * @throws EE_Error
435
+	 */
436
+	public function get_array_of_contacts_from_reg_ids($ids)
437
+	{
438
+		$ids = (array)$ids;
439
+		$_where = array(
440
+			'Registration.REG_ID' => array('in', $ids),
441
+		);
442
+		return $this->get_all(array($_where));
443
+	}
444 444
 
445 445
 
446 446
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 
3 3
 defined('EVENT_ESPRESSO_VERSION') || exit('No direct script access allowed');
4 4
 
5
-require_once(EE_MODELS . 'EEM_Base.model.php');
5
+require_once(EE_MODELS.'EEM_Base.model.php');
6 6
 
7 7
 
8 8
 
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
             return false;
376 376
         }
377 377
         $attendee = $this->get_all(array($where_cols_n_values));
378
-        if (! empty($attendee)) {
378
+        if ( ! empty($attendee)) {
379 379
             return array_shift($attendee);
380 380
         }
381 381
         return false;
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
      */
436 436
     public function get_array_of_contacts_from_reg_ids($ids)
437 437
     {
438
-        $ids = (array)$ids;
438
+        $ids = (array) $ids;
439 439
         $_where = array(
440 440
             'Registration.REG_ID' => array('in', $ids),
441 441
         );
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +5821 added lines, -5821 removed lines patch added patch discarded remove patch
@@ -28,5829 +28,5829 @@
 block discarded – undo
28 28
 abstract class EEM_Base extends EE_Base implements EventEspresso\core\interfaces\ResettableInterface
29 29
 {
30 30
 
31
-    //admin posty
32
-    //basic -> grants access to mine -> if they don't have it, select none
33
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
-    //*_published -> grants access to published -> if they dont have it, select non-published
36
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
38
-    //frontend posty
39
-    //by default has access to published
40
-    //basic -> grants access to mine that aren't published, and all published
41
-    //*_others ->grants access to others that aren't private, all mine
42
-    //*_private -> grants full access
43
-    //frontend non-posty
44
-    //like admin posty
45
-    //category-y
46
-    //assign -> grants access to join-table
47
-    //(delete, edit)
48
-    //payment-method-y
49
-    //for each registered payment method,
50
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
-    /**
52
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
-     * They almost always WILL NOT, but it's not necessarily a requirement.
55
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
-     *
57
-     * @var boolean
58
-     */
59
-    private $_values_already_prepared_by_model_object = 0;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the data is just like form input that needs to have the model fields'
64
-     * prepare_for_set and prepare_for_use_in_db called on it
65
-     */
66
-    const not_prepared_by_model_object = 0;
67
-
68
-    /**
69
-     * when $_values_already_prepared_by_model_object equals this, we
70
-     * assume this value is coming from a model object and doesn't need to have
71
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
72
-     */
73
-    const prepared_by_model_object = 1;
74
-
75
-    /**
76
-     * when $_values_already_prepared_by_model_object equals this, we assume
77
-     * the values are already to be used in the database (ie no processing is done
78
-     * on them by the model's fields)
79
-     */
80
-    const prepared_for_use_in_db = 2;
81
-
82
-
83
-    protected $singular_item = 'Item';
84
-
85
-    protected $plural_item   = 'Items';
86
-
87
-    /**
88
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
-     */
90
-    protected $_tables;
91
-
92
-    /**
93
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
-     *
97
-     * @var \EE_Model_Field_Base[] $_fields
98
-     */
99
-    protected $_fields;
100
-
101
-    /**
102
-     * array of different kinds of relations
103
-     *
104
-     * @var \EE_Model_Relation_Base[] $_model_relations
105
-     */
106
-    protected $_model_relations;
107
-
108
-    /**
109
-     * @var \EE_Index[] $_indexes
110
-     */
111
-    protected $_indexes = array();
112
-
113
-    /**
114
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
115
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
-     * by setting the same columns as used in these queries in the query yourself.
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_default_where_conditions_strategy;
121
-
122
-    /**
123
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
-     * This is particularly useful when you want something between 'none' and 'default'
125
-     *
126
-     * @var EE_Default_Where_Conditions
127
-     */
128
-    protected $_minimum_where_conditions_strategy;
129
-
130
-    /**
131
-     * String describing how to find the "owner" of this model's objects.
132
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
-     * But when there isn't, this indicates which related model, or transiently-related model,
134
-     * has the foreign key to the wp_users table.
135
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
-     * related to events, and events have a foreign key to wp_users.
137
-     * On EEM_Transaction, this would be 'Transaction.Event'
138
-     *
139
-     * @var string
140
-     */
141
-    protected $_model_chain_to_wp_user = '';
142
-
143
-    /**
144
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
-     * don't need it (particularly CPT models)
146
-     *
147
-     * @var bool
148
-     */
149
-    protected $_ignore_where_strategy = false;
150
-
151
-    /**
152
-     * String used in caps relating to this model. Eg, if the caps relating to this
153
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
-     *
155
-     * @var string. If null it hasn't been initialized yet. If false then we
156
-     * have indicated capabilities don't apply to this
157
-     */
158
-    protected $_caps_slug = null;
159
-
160
-    /**
161
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
-     * and next-level keys are capability names, and each's value is a
163
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
-     * they specify which context to use (ie, frontend, backend, edit or delete)
165
-     * and then each capability in the corresponding sub-array that they're missing
166
-     * adds the where conditions onto the query.
167
-     *
168
-     * @var array
169
-     */
170
-    protected $_cap_restrictions = array(
171
-        self::caps_read       => array(),
172
-        self::caps_read_admin => array(),
173
-        self::caps_edit       => array(),
174
-        self::caps_delete     => array(),
175
-    );
176
-
177
-    /**
178
-     * Array defining which cap restriction generators to use to create default
179
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
180
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
-     * automatically set this to false (not just null).
183
-     *
184
-     * @var EE_Restriction_Generator_Base[]
185
-     */
186
-    protected $_cap_restriction_generators = array();
187
-
188
-    /**
189
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
-     */
191
-    const caps_read       = 'read';
192
-
193
-    const caps_read_admin = 'read_admin';
194
-
195
-    const caps_edit       = 'edit';
196
-
197
-    const caps_delete     = 'delete';
198
-
199
-    /**
200
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
-     * maps to 'read' because when looking for relevant permissions we're going to use
203
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
204
-     *
205
-     * @var array
206
-     */
207
-    protected $_cap_contexts_to_cap_action_map = array(
208
-        self::caps_read       => 'read',
209
-        self::caps_read_admin => 'read',
210
-        self::caps_edit       => 'edit',
211
-        self::caps_delete     => 'delete',
212
-    );
213
-
214
-    /**
215
-     * Timezone
216
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
-     * EE_Datetime_Field data type will have access to it.
220
-     *
221
-     * @var string
222
-     */
223
-    protected $_timezone;
224
-
225
-
226
-    /**
227
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
-     * multisite.
229
-     *
230
-     * @var int
231
-     */
232
-    protected static $_model_query_blog_id;
233
-
234
-    /**
235
-     * A copy of _fields, except the array keys are the model names pointed to by
236
-     * the field
237
-     *
238
-     * @var EE_Model_Field_Base[]
239
-     */
240
-    private $_cache_foreign_key_to_fields = array();
241
-
242
-    /**
243
-     * Cached list of all the fields on the model, indexed by their name
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cached_fields = null;
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, except those that are
251
-     * marked as only pertinent to the database
252
-     *
253
-     * @var EE_Model_Field_Base[]
254
-     */
255
-    private $_cached_fields_non_db_only = null;
256
-
257
-    /**
258
-     * A cached reference to the primary key for quick lookup
259
-     *
260
-     * @var EE_Model_Field_Base
261
-     */
262
-    private $_primary_key_field = null;
263
-
264
-    /**
265
-     * Flag indicating whether this model has a primary key or not
266
-     *
267
-     * @var boolean
268
-     */
269
-    protected $_has_primary_key_field = null;
270
-
271
-    /**
272
-     * Whether or not this model is based off a table in WP core only (CPTs should set
273
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
-     *
275
-     * @var boolean
276
-     */
277
-    protected $_wp_core_model = false;
278
-
279
-    /**
280
-     *    List of valid operators that can be used for querying.
281
-     * The keys are all operators we'll accept, the values are the real SQL
282
-     * operators used
283
-     *
284
-     * @var array
285
-     */
286
-    protected $_valid_operators = array(
287
-        '='           => '=',
288
-        '<='          => '<=',
289
-        '<'           => '<',
290
-        '>='          => '>=',
291
-        '>'           => '>',
292
-        '!='          => '!=',
293
-        'LIKE'        => 'LIKE',
294
-        'like'        => 'LIKE',
295
-        'NOT_LIKE'    => 'NOT LIKE',
296
-        'not_like'    => 'NOT LIKE',
297
-        'NOT LIKE'    => 'NOT LIKE',
298
-        'not like'    => 'NOT LIKE',
299
-        'IN'          => 'IN',
300
-        'in'          => 'IN',
301
-        'NOT_IN'      => 'NOT IN',
302
-        'not_in'      => 'NOT IN',
303
-        'NOT IN'      => 'NOT IN',
304
-        'not in'      => 'NOT IN',
305
-        'between'     => 'BETWEEN',
306
-        'BETWEEN'     => 'BETWEEN',
307
-        'IS_NOT_NULL' => 'IS NOT NULL',
308
-        'is_not_null' => 'IS NOT NULL',
309
-        'IS NOT NULL' => 'IS NOT NULL',
310
-        'is not null' => 'IS NOT NULL',
311
-        'IS_NULL'     => 'IS NULL',
312
-        'is_null'     => 'IS NULL',
313
-        'IS NULL'     => 'IS NULL',
314
-        'is null'     => 'IS NULL',
315
-        'REGEXP'      => 'REGEXP',
316
-        'regexp'      => 'REGEXP',
317
-        'NOT_REGEXP'  => 'NOT REGEXP',
318
-        'not_regexp'  => 'NOT REGEXP',
319
-        'NOT REGEXP'  => 'NOT REGEXP',
320
-        'not regexp'  => 'NOT REGEXP',
321
-    );
322
-
323
-    /**
324
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
-     *
326
-     * @var array
327
-     */
328
-    protected $_in_style_operators = array('IN', 'NOT IN');
329
-
330
-    /**
331
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
-     * '12-31-2012'"
333
-     *
334
-     * @var array
335
-     */
336
-    protected $_between_style_operators = array('BETWEEN');
337
-
338
-    /**
339
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
-     * on a join table.
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
-
346
-    /**
347
-     * Allowed values for $query_params['order'] for ordering in queries
348
-     *
349
-     * @var array
350
-     */
351
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
-
353
-    /**
354
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
356
-     *
357
-     * @var array
358
-     */
359
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
-
361
-    /**
362
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
364
-     *
365
-     * @var array
366
-     */
367
-    private $_allowed_query_params = array(
368
-        0,
369
-        'limit',
370
-        'order_by',
371
-        'group_by',
372
-        'having',
373
-        'force_join',
374
-        'order',
375
-        'on_join_limit',
376
-        'default_where_conditions',
377
-        'caps',
378
-    );
379
-
380
-    /**
381
-     * All the data types that can be used in $wpdb->prepare statements.
382
-     *
383
-     * @var array
384
-     */
385
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
-
387
-    /**
388
-     *    EE_Registry Object
389
-     *
390
-     * @var    object
391
-     * @access    protected
392
-     */
393
-    protected $EE = null;
394
-
395
-
396
-    /**
397
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
-     *
399
-     * @var int
400
-     */
401
-    protected $_show_next_x_db_queries = 0;
402
-
403
-    /**
404
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
-     *
407
-     * @var array
408
-     */
409
-    protected $_custom_selections = array();
410
-
411
-    /**
412
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
-     * caches every model object we've fetched from the DB on this request
414
-     *
415
-     * @var array
416
-     */
417
-    protected $_entity_map;
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws \EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Generates the cap restrictions for the given context, or if they were
654
-     * already generated just gets what's cached
655
-     *
656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
657
-     * @return EE_Default_Where_Conditions[]
658
-     */
659
-    protected function _generate_cap_restrictions($context)
660
-    {
661
-        if (isset($this->_cap_restriction_generators[$context])
662
-            && $this->_cap_restriction_generators[$context]
663
-               instanceof
664
-               EE_Restriction_Generator_Base
665
-        ) {
666
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
-        } else {
668
-            return array();
669
-        }
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Used to set the $_model_query_blog_id static property.
676
-     *
677
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
-     *                      value for get_current_blog_id() will be used.
679
-     */
680
-    public static function set_model_query_blog_id($blog_id = 0)
681
-    {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     * Returns whatever is set as the internal $model_query_blog_id.
689
-     *
690
-     * @return int
691
-     */
692
-    public static function get_model_query_blog_id()
693
-    {
694
-        return EEM_Base::$_model_query_blog_id;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *        This function is a singleton method used to instantiate the Espresso_model object
701
-     *
702
-     * @access public
703
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
-     *                         timezone in the 'timezone_string' wp option)
707
-     * @return static (as in the concrete child class)
708
-     */
709
-    public static function instance($timezone = null)
710
-    {
711
-        // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
713
-            // instantiate Espresso_model
714
-            static::$_instance = new static($timezone);
715
-        }
716
-        //we might have a timezone set, let set_timezone decide what to do with it
717
-        static::$_instance->set_timezone($timezone);
718
-        // Espresso_model object
719
-        return static::$_instance;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * resets the model and returns it
726
-     *
727
-     * @param null | string $timezone
728
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
-     * all its properties reset; if it wasn't instantiated, returns null)
730
-     */
731
-    public static function reset($timezone = null)
732
-    {
733
-        if (static::$_instance instanceof EEM_Base) {
734
-            //let's try to NOT swap out the current instance for a new one
735
-            //because if someone has a reference to it, we can't remove their reference
736
-            //so it's best to keep using the same reference, but change the original object
737
-            //reset all its properties to their original values as defined in the class
738
-            $r = new ReflectionClass(get_class(static::$_instance));
739
-            $static_properties = $r->getStaticProperties();
740
-            foreach ($r->getDefaultProperties() as $property => $value) {
741
-                //don't set instance to null like it was originally,
742
-                //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
744
-                    static::$_instance->{$property} = $value;
745
-                }
746
-            }
747
-            //and then directly call its constructor again, like we would if we
748
-            //were creating a new one
749
-            static::$_instance->__construct($timezone);
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
-     *
760
-     * @param  boolean $translated return localized strings or JUST the array.
761
-     * @return array
762
-     * @throws \EE_Error
763
-     */
764
-    public function status_array($translated = false)
765
-    {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
-            return array();
768
-        }
769
-        $model_name = $this->get_this_model_name();
770
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
-        $status_array = array();
773
-        foreach ($stati as $status) {
774
-            $status_array[$status->ID()] = $status->get('STS_code');
775
-        }
776
-        return $translated
777
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
-            : $status_array;
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
-     *
786
-     * @param array $query_params             {
787
-     * @var array $0 (where) array {
788
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
-     *                                        conditions based on related models (and even
792
-     *                                        models-related-to-related-models) prepend the model's name onto the field
793
-     *                                        name. Eg,
794
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
-     *                                        to Venues (even when each of those models actually consisted of two
802
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
803
-     *                                        just having
804
-     *                                        "Venue.VNU_ID", you could have
805
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
-     *                                        events are related to Registrations, which are related to Attendees). You
807
-     *                                        can take it even further with
808
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
-     *                                        (from the default of '='), change the value to an numerically-indexed
810
-     *                                        array, where the first item in the list is the operator. eg: array(
811
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
819
-     *                                        the value is a field, simply provide a third array item (true) to the
820
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
-     *                                        Note: you can also use related model field names like you would any other
823
-     *                                        field name. eg:
824
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
826
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
833
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
-     *                                        "stick" until you specify an AND. eg
835
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
840
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
-     *                                        too, eg:
843
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
848
-     *                                        the OFFSET, the 2nd is the LIMIT
849
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
-     *                                        following format array('on_join_limit'
852
-     *                                        => array( 'table_alias', array(1,2) ) ).
853
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
-     *                                        values are either 'ASC' or 'DESC'.
855
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
-     *                                        DESC..." respectively. Like the
858
-     *                                        'where' conditions, these fields can be on related models. Eg
859
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
861
-     *                                        Attendee, Price, Datetime, etc.)
862
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
864
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
-     *                                        order by the primary key. Eg,
867
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
-     *                                        //(will join with the Datetime model's table(s) and order by its field
869
-     *                                        DTT_EVT_start) or
870
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
-     *                                        'group_by'=>'VNU_ID', or
874
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
-     *                                        if no
876
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
877
-     *                                        model's primary key (or combined primary keys). This avoids some
878
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
879
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
-     *                                        results)
883
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
-     *                                        array where values are models to be joined in the query.Eg
885
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
887
-     *                                        probably only want to do this in hopes of increasing efficiency, as
888
-     *                                        related models which belongs to the current model
889
-     *                                        (ie, the current model has a foreign key to them, like how Registration
890
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
891
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
894
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
-     *                                        default where conditions set it to 'other_models_only'. If you only want
896
-     *                                        this model's default where conditions added to the query, use
897
-     *                                        'this_model_only'. If you want to use all default where conditions
898
-     *                                        (default), set to 'all'.
899
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
-     *                                        everything? Or should we only show the current user items they should be
902
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
-     *                                        }
905
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
-     *                                        array( array(
911
-     *                                        'OR'=>array(
912
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
-     *                                        )
915
-     *                                        ),
916
-     *                                        'limit'=>10,
917
-     *                                        'group_by'=>'TXN_ID'
918
-     *                                        ));
919
-     *                                        get all the answers to the question titled "shirt size" for event with id
920
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
-     *                                        'Question.QST_display_text'=>'shirt size',
922
-     *                                        'Registration.Event.EVT_ID'=>12
923
-     *                                        ),
924
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
925
-     *                                        ));
926
-     * @throws \EE_Error
927
-     */
928
-    public function get_all($query_params = array())
929
-    {
930
-        if (isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Modifies the query parameters so we only get back model objects
942
-     * that "belong" to the current user
943
-     *
944
-     * @param array $query_params @see EEM_Base::get_all()
945
-     * @return array like EEM_Base::get_all
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = array())
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Returns the name of the field's name that points to the WP_User table
960
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
-     * foreign key to the WP_User table)
962
-     *
963
-     * @return string|boolean string on success, boolean false when there is no
964
-     * foreign key to the WP_User table
965
-     */
966
-    public function wp_user_field_name()
967
-    {
968
-        try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
970
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
-                $last_model_name = end($models_to_follow_to_wp_users);
972
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
-            } else {
975
-                $model_with_fk_to_wp_users = $this;
976
-                $model_chain_to_wp_user = '';
977
-            }
978
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
-        } catch (EE_Error $e) {
981
-            return false;
982
-        }
983
-    }
984
-
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
-     * like how registrations don't have a foreign key to wp_users, but the
1007
-     * events they are for are), or is unrelated to wp users.
1008
-     * generally available
1009
-     *
1010
-     * @return boolean
1011
-     */
1012
-    public function is_owned()
1013
-    {
1014
-        if ($this->model_chain_to_wp_user()) {
1015
-            return true;
1016
-        } else {
1017
-            try {
1018
-                $this->get_foreign_key_to('WP_User');
1019
-                return true;
1020
-            } catch (EE_Error $e) {
1021
-                return false;
1022
-            }
1023
-        }
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws \EE_Error
1045
-     */
1046
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        // remember the custom selections, if any, and type cast as array
1049
-        // (unless $columns_to_select is an object, then just set as an empty array)
1050
-        // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions = $columns_to_select !== null
1054
-            ? $this->_construct_select_from_input($columns_to_select)
1055
-            : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1064
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
-     * take care of joins, field preparation etc.
1066
-     *
1067
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1071
-     *                                  override this and set the select to "*", or a specific column name, like
1072
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
-     *                                  the aliases used to refer to this selection, and values are to be
1075
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
-     * @throws \EE_Error
1079
-     */
1080
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
-    {
1082
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * For creating a custom select statement
1089
-     *
1090
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
-     *                                 SQL, and 1=>is the datatype
1093
-     * @throws EE_Error
1094
-     * @return string
1095
-     */
1096
-    private function _construct_select_from_input($columns_to_select)
1097
-    {
1098
-        if (is_array($columns_to_select)) {
1099
-            $select_sql_array = array();
1100
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
-                    throw new EE_Error(
1103
-                        sprintf(
1104
-                            __(
1105
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
-                                "event_espresso"
1107
-                            ),
1108
-                            $selection_and_datatype,
1109
-                            $alias
1110
-                        )
1111
-                    );
1112
-                }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
-                    throw new EE_Error(
1115
-                        sprintf(
1116
-                            __(
1117
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
-                                "event_espresso"
1119
-                            ),
1120
-                            $selection_and_datatype[1],
1121
-                            $selection_and_datatype[0],
1122
-                            $alias,
1123
-                            implode(",", $this->_valid_wpdb_data_types)
1124
-                        )
1125
-                    );
1126
-                }
1127
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
-            }
1129
-            $columns_to_select_string = implode(", ", $select_sql_array);
1130
-        } else {
1131
-            $columns_to_select_string = $columns_to_select;
1132
-        }
1133
-        return $columns_to_select_string;
1134
-    }
1135
-
1136
-
1137
-
1138
-    /**
1139
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
-     *
1141
-     * @return string
1142
-     * @throws \EE_Error
1143
-     */
1144
-    public function primary_key_name()
1145
-    {
1146
-        return $this->get_primary_key_field()->get_name();
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
-     * If there is no primary key on this model, $id is treated as primary key string
1154
-     *
1155
-     * @param mixed $id int or string, depending on the type of the model's primary key
1156
-     * @return EE_Base_Class
1157
-     */
1158
-    public function get_one_by_ID($id)
1159
-    {
1160
-        if ($this->get_from_entity_map($id)) {
1161
-            return $this->get_from_entity_map($id);
1162
-        }
1163
-        return $this->get_one(
1164
-            $this->alter_query_params_to_restrict_by_ID(
1165
-                $id,
1166
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
-            )
1168
-        );
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Alters query parameters to only get items with this ID are returned.
1175
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
-     * or could just be a simple primary key ID
1177
-     *
1178
-     * @param int   $id
1179
-     * @param array $query_params
1180
-     * @return array of normal query params, @see EEM_Base::get_all
1181
-     * @throws \EE_Error
1182
-     */
1183
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
-    {
1185
-        if (! isset($query_params[0])) {
1186
-            $query_params[0] = array();
1187
-        }
1188
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1189
-        if ($conditions_from_id === null) {
1190
-            $query_params[0][$this->primary_key_name()] = $id;
1191
-        } else {
1192
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1193
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
-        }
1195
-        return $query_params;
1196
-    }
1197
-
1198
-
1199
-
1200
-    /**
1201
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
-     * array. If no item is found, null is returned.
1203
-     *
1204
-     * @param array $query_params like EEM_Base's $query_params variable.
1205
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
-     * @throws \EE_Error
1207
-     */
1208
-    public function get_one($query_params = array())
1209
-    {
1210
-        if (! is_array($query_params)) {
1211
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
-                    gettype($query_params)), '4.6.0');
1214
-            $query_params = array();
1215
-        }
1216
-        $query_params['limit'] = 1;
1217
-        $items = $this->get_all($query_params);
1218
-        if (empty($items)) {
1219
-            return null;
1220
-        } else {
1221
-            return array_shift($items);
1222
-        }
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Returns the next x number of items in sequence from the given value as
1229
-     * found in the database matching the given query conditions.
1230
-     *
1231
-     * @param mixed $current_field_value    Value used for the reference point.
1232
-     * @param null  $field_to_order_by      What field is used for the
1233
-     *                                      reference point.
1234
-     * @param int   $limit                  How many to return.
1235
-     * @param array $query_params           Extra conditions on the query.
1236
-     * @param null  $columns_to_select      If left null, then an array of
1237
-     *                                      EE_Base_Class objects is returned,
1238
-     *                                      otherwise you can indicate just the
1239
-     *                                      columns you want returned.
1240
-     * @return EE_Base_Class[]|array
1241
-     * @throws \EE_Error
1242
-     */
1243
-    public function next_x(
1244
-        $current_field_value,
1245
-        $field_to_order_by = null,
1246
-        $limit = 1,
1247
-        $query_params = array(),
1248
-        $columns_to_select = null
1249
-    ) {
1250
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
-            $columns_to_select);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the previous x number of items in sequence from the given value
1258
-     * as found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws \EE_Error
1271
-     */
1272
-    public function previous_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = array(),
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
-            $columns_to_select);
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * Returns the next item in sequence from the given value as found in the
1287
-     * database matching the given query conditions.
1288
-     *
1289
-     * @param mixed $current_field_value    Value used for the reference point.
1290
-     * @param null  $field_to_order_by      What field is used for the
1291
-     *                                      reference point.
1292
-     * @param array $query_params           Extra conditions on the query.
1293
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
-     *                                      object is returned, otherwise you
1295
-     *                                      can indicate just the columns you
1296
-     *                                      want and a single array indexed by
1297
-     *                                      the columns will be returned.
1298
-     * @return EE_Base_Class|null|array()
1299
-     * @throws \EE_Error
1300
-     */
1301
-    public function next(
1302
-        $current_field_value,
1303
-        $field_to_order_by = null,
1304
-        $query_params = array(),
1305
-        $columns_to_select = null
1306
-    ) {
1307
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
-            $columns_to_select);
1309
-        return empty($results) ? null : reset($results);
1310
-    }
1311
-
1312
-
1313
-
1314
-    /**
1315
-     * Returns the previous item in sequence from the given value as found in
1316
-     * the database matching the given query conditions.
1317
-     *
1318
-     * @param mixed $current_field_value    Value used for the reference point.
1319
-     * @param null  $field_to_order_by      What field is used for the
1320
-     *                                      reference point.
1321
-     * @param array $query_params           Extra conditions on the query.
1322
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
-     *                                      object is returned, otherwise you
1324
-     *                                      can indicate just the columns you
1325
-     *                                      want and a single array indexed by
1326
-     *                                      the columns will be returned.
1327
-     * @return EE_Base_Class|null|array()
1328
-     * @throws EE_Error
1329
-     */
1330
-    public function previous(
1331
-        $current_field_value,
1332
-        $field_to_order_by = null,
1333
-        $query_params = array(),
1334
-        $columns_to_select = null
1335
-    ) {
1336
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
-            $columns_to_select);
1338
-        return empty($results) ? null : reset($results);
1339
-    }
1340
-
1341
-
1342
-
1343
-    /**
1344
-     * Returns the a consecutive number of items in sequence from the given
1345
-     * value as found in the database matching the given query conditions.
1346
-     *
1347
-     * @param mixed  $current_field_value   Value used for the reference point.
1348
-     * @param string $operand               What operand is used for the sequence.
1349
-     * @param string $field_to_order_by     What field is used for the reference point.
1350
-     * @param int    $limit                 How many to return.
1351
-     * @param array  $query_params          Extra conditions on the query.
1352
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
-     *                                      otherwise you can indicate just the columns you want returned.
1354
-     * @return EE_Base_Class[]|array
1355
-     * @throws EE_Error
1356
-     */
1357
-    protected function _get_consecutive(
1358
-        $current_field_value,
1359
-        $operand = '>',
1360
-        $field_to_order_by = null,
1361
-        $limit = 1,
1362
-        $query_params = array(),
1363
-        $columns_to_select = null
1364
-    ) {
1365
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
-        if (empty($field_to_order_by)) {
1367
-            if ($this->has_primary_key_field()) {
1368
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1369
-            } else {
1370
-                if (WP_DEBUG) {
1371
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1372
-                        'event_espresso'));
1373
-                }
1374
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
-                return array();
1376
-            }
1377
-        }
1378
-        if (! is_array($query_params)) {
1379
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
-                    gettype($query_params)), '4.6.0');
1382
-            $query_params = array();
1383
-        }
1384
-        //let's add the where query param for consecutive look up.
1385
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
-        $query_params['limit'] = $limit;
1387
-        //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
-        $query_params['order_by'] = $operand === '>'
1390
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
-        if (empty($columns_to_select)) {
1394
-            return $this->get_all($query_params);
1395
-        } else {
1396
-            //getting just the fields
1397
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
-        }
1399
-    }
1400
-
1401
-
1402
-
1403
-    /**
1404
-     * This sets the _timezone property after model object has been instantiated.
1405
-     *
1406
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
-     */
1408
-    public function set_timezone($timezone)
1409
-    {
1410
-        if ($timezone !== null) {
1411
-            $this->_timezone = $timezone;
1412
-        }
1413
-        //note we need to loop through relations and set the timezone on those objects as well.
1414
-        foreach ($this->_model_relations as $relation) {
1415
-            $relation->set_timezone($timezone);
1416
-        }
1417
-        //and finally we do the same for any datetime fields
1418
-        foreach ($this->_fields as $field) {
1419
-            if ($field instanceof EE_Datetime_Field) {
1420
-                $field->set_timezone($timezone);
1421
-            }
1422
-        }
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     * This just returns whatever is set for the current timezone.
1429
-     *
1430
-     * @access public
1431
-     * @return string
1432
-     */
1433
-    public function get_timezone()
1434
-    {
1435
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
-        if (empty($this->_timezone)) {
1437
-            foreach ($this->_fields as $field) {
1438
-                if ($field instanceof EE_Datetime_Field) {
1439
-                    $this->set_timezone($field->get_timezone());
1440
-                    break;
1441
-                }
1442
-            }
1443
-        }
1444
-        //if timezone STILL empty then return the default timezone for the site.
1445
-        if (empty($this->_timezone)) {
1446
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
-        }
1448
-        return $this->_timezone;
1449
-    }
1450
-
1451
-
1452
-
1453
-    /**
1454
-     * This returns the date formats set for the given field name and also ensures that
1455
-     * $this->_timezone property is set correctly.
1456
-     *
1457
-     * @since 4.6.x
1458
-     * @param string $field_name The name of the field the formats are being retrieved for.
1459
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
-     */
1463
-    public function get_formats_for($field_name, $pretty = false)
1464
-    {
1465
-        $field_settings = $this->field_settings_for($field_name);
1466
-        //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469
-                'event_espresso'), $field_name));
1470
-        }
1471
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
-        //the field.
1473
-        $this->_timezone = $field_settings->get_timezone();
1474
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
-    }
1476
-
1477
-
1478
-
1479
-    /**
1480
-     * This returns the current time in a format setup for a query on this model.
1481
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
-     * it will return:
1483
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
-     *  NOW
1485
-     *  - or a unix timestamp (equivalent to time())
1486
-     *
1487
-     * @since 4.6.x
1488
-     * @param string $field_name       The field the current time is needed for.
1489
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1490
-     *                                 formatted string matching the set format for the field in the set timezone will
1491
-     *                                 be returned.
1492
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1493
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1494
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495
-     *                                 exception is triggered.
1496
-     */
1497
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1498
-    {
1499
-        $formats = $this->get_formats_for($field_name);
1500
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1501
-        if ($timestamp) {
1502
-            return $DateTime->format('U');
1503
-        }
1504
-        //not returning timestamp, so return formatted string in timezone.
1505
-        switch ($what) {
1506
-            case 'time' :
1507
-                return $DateTime->format($formats[1]);
1508
-                break;
1509
-            case 'date' :
1510
-                return $DateTime->format($formats[0]);
1511
-                break;
1512
-            default :
1513
-                return $DateTime->format(implode(' ', $formats));
1514
-                break;
1515
-        }
1516
-    }
1517
-
1518
-
1519
-
1520
-    /**
1521
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1522
-     * for the model are.  Returns a DateTime object.
1523
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1524
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1525
-     * ignored.
1526
-     *
1527
-     * @param string $field_name      The field being setup.
1528
-     * @param string $timestring      The date time string being used.
1529
-     * @param string $incoming_format The format for the time string.
1530
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1531
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1532
-     *                                format is
1533
-     *                                'U', this is ignored.
1534
-     * @return DateTime
1535
-     * @throws \EE_Error
1536
-     */
1537
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1538
-    {
1539
-        //just using this to ensure the timezone is set correctly internally
1540
-        $this->get_formats_for($field_name);
1541
-        //load EEH_DTT_Helper
1542
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1543
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1544
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1545
-    }
1546
-
1547
-
1548
-
1549
-    /**
1550
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1551
-     *
1552
-     * @return EE_Table_Base[]
1553
-     */
1554
-    public function get_tables()
1555
-    {
1556
-        return $this->_tables;
1557
-    }
1558
-
1559
-
1560
-
1561
-    /**
1562
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1563
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1564
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1565
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1566
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1567
-     * model object with EVT_ID = 1
1568
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1569
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1570
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1571
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1572
-     * are not specified)
1573
-     *
1574
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1575
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1576
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1577
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1578
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1579
-     *                                         ID=34, we'd use this method as follows:
1580
-     *                                         EEM_Transaction::instance()->update(
1581
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1582
-     *                                         array(array('TXN_ID'=>34)));
1583
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1584
-     *                                         in client code into what's expected to be stored on each field. Eg,
1585
-     *                                         consider updating Question's QST_admin_label field is of type
1586
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1587
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1588
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1589
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1590
-     *                                         TRUE, it is assumed that you've already called
1591
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1592
-     *                                         malicious javascript. However, if
1593
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1594
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1595
-     *                                         and every other field, before insertion. We provide this parameter
1596
-     *                                         because model objects perform their prepare_for_set function on all
1597
-     *                                         their values, and so don't need to be called again (and in many cases,
1598
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1599
-     *                                         prepare_for_set method...)
1600
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1601
-     *                                         in this model's entity map according to $fields_n_values that match
1602
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1603
-     *                                         by setting this to FALSE, but be aware that model objects being used
1604
-     *                                         could get out-of-sync with the database
1605
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1606
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1607
-     *                                         bad)
1608
-     * @throws \EE_Error
1609
-     */
1610
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1611
-    {
1612
-        if (! is_array($query_params)) {
1613
-            EE_Error::doing_it_wrong('EEM_Base::update',
1614
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1615
-                    gettype($query_params)), '4.6.0');
1616
-            $query_params = array();
1617
-        }
1618
-        /**
1619
-         * Action called before a model update call has been made.
1620
-         *
1621
-         * @param EEM_Base $model
1622
-         * @param array    $fields_n_values the updated fields and their new values
1623
-         * @param array    $query_params    @see EEM_Base::get_all()
1624
-         */
1625
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1626
-        /**
1627
-         * Filters the fields about to be updated given the query parameters. You can provide the
1628
-         * $query_params to $this->get_all() to find exactly which records will be updated
1629
-         *
1630
-         * @param array    $fields_n_values fields and their new values
1631
-         * @param EEM_Base $model           the model being queried
1632
-         * @param array    $query_params    see EEM_Base::get_all()
1633
-         */
1634
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1635
-            $query_params);
1636
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1637
-        //to do that, for each table, verify that it's PK isn't null.
1638
-        $tables = $this->get_tables();
1639
-        //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
1640
-        //NOTE: we should make this code more efficient by NOT querying twice
1641
-        //before the real update, but that needs to first go through ALPHA testing
1642
-        //as it's dangerous. says Mike August 8 2014
1643
-        //we want to make sure the default_where strategy is ignored
1644
-        $this->_ignore_where_strategy = true;
1645
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1646
-        foreach ($wpdb_select_results as $wpdb_result) {
1647
-            // type cast stdClass as array
1648
-            $wpdb_result = (array)$wpdb_result;
1649
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1650
-            if ($this->has_primary_key_field()) {
1651
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1652
-            } else {
1653
-                //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)
1654
-                $main_table_pk_value = null;
1655
-            }
1656
-            //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
1657
-            //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
1658
-            if (count($tables) > 1) {
1659
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1660
-                //in that table, and so we'll want to insert one
1661
-                foreach ($tables as $table_obj) {
1662
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1663
-                    //if there is no private key for this table on the results, it means there's no entry
1664
-                    //in this table, right? so insert a row in the current table, using any fields available
1665
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1666
-                           && $wpdb_result[$this_table_pk_column])
1667
-                    ) {
1668
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1669
-                            $main_table_pk_value);
1670
-                        //if we died here, report the error
1671
-                        if (! $success) {
1672
-                            return false;
1673
-                        }
1674
-                    }
1675
-                }
1676
-            }
1677
-            //				//and now check that if we have cached any models by that ID on the model, that
1678
-            //				//they also get updated properly
1679
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1680
-            //				if( $model_object ){
1681
-            //					foreach( $fields_n_values as $field => $value ){
1682
-            //						$model_object->set($field, $value);
1683
-            //let's make sure default_where strategy is followed now
1684
-            $this->_ignore_where_strategy = false;
1685
-        }
1686
-        //if we want to keep model objects in sync, AND
1687
-        //if this wasn't called from a model object (to update itself)
1688
-        //then we want to make sure we keep all the existing
1689
-        //model objects in sync with the db
1690
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1691
-            if ($this->has_primary_key_field()) {
1692
-                $model_objs_affected_ids = $this->get_col($query_params);
1693
-            } else {
1694
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1695
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1696
-                $model_objs_affected_ids = array();
1697
-                foreach ($models_affected_key_columns as $row) {
1698
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1699
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1700
-                }
1701
-            }
1702
-            if (! $model_objs_affected_ids) {
1703
-                //wait wait wait- if nothing was affected let's stop here
1704
-                return 0;
1705
-            }
1706
-            foreach ($model_objs_affected_ids as $id) {
1707
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1708
-                if ($model_obj_in_entity_map) {
1709
-                    foreach ($fields_n_values as $field => $new_value) {
1710
-                        $model_obj_in_entity_map->set($field, $new_value);
1711
-                    }
1712
-                }
1713
-            }
1714
-            //if there is a primary key on this model, we can now do a slight optimization
1715
-            if ($this->has_primary_key_field()) {
1716
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1717
-                $query_params = array(
1718
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1719
-                    'limit'                    => count($model_objs_affected_ids),
1720
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1721
-                );
1722
-            }
1723
-        }
1724
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1725
-        $SQL = "UPDATE "
1726
-               . $model_query_info->get_full_join_sql()
1727
-               . " SET "
1728
-               . $this->_construct_update_sql($fields_n_values)
1729
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1730
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1731
-        /**
1732
-         * Action called after a model update call has been made.
1733
-         *
1734
-         * @param EEM_Base $model
1735
-         * @param array    $fields_n_values the updated fields and their new values
1736
-         * @param array    $query_params    @see EEM_Base::get_all()
1737
-         * @param int      $rows_affected
1738
-         */
1739
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1740
-        return $rows_affected;//how many supposedly got updated
1741
-    }
1742
-
1743
-
1744
-
1745
-    /**
1746
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1747
-     * are teh values of the field specified (or by default the primary key field)
1748
-     * that matched the query params. Note that you should pass the name of the
1749
-     * model FIELD, not the database table's column name.
1750
-     *
1751
-     * @param array  $query_params @see EEM_Base::get_all()
1752
-     * @param string $field_to_select
1753
-     * @return array just like $wpdb->get_col()
1754
-     * @throws \EE_Error
1755
-     */
1756
-    public function get_col($query_params = array(), $field_to_select = null)
1757
-    {
1758
-        if ($field_to_select) {
1759
-            $field = $this->field_settings_for($field_to_select);
1760
-        } elseif ($this->has_primary_key_field()) {
1761
-            $field = $this->get_primary_key_field();
1762
-        } else {
1763
-            //no primary key, just grab the first column
1764
-            $field = reset($this->field_settings());
1765
-        }
1766
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1767
-        $select_expressions = $field->get_qualified_column();
1768
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1769
-        return $this->_do_wpdb_query('get_col', array($SQL));
1770
-    }
1771
-
1772
-
1773
-
1774
-    /**
1775
-     * Returns a single column value for a single row from the database
1776
-     *
1777
-     * @param array  $query_params    @see EEM_Base::get_all()
1778
-     * @param string $field_to_select @see EEM_Base::get_col()
1779
-     * @return string
1780
-     * @throws \EE_Error
1781
-     */
1782
-    public function get_var($query_params = array(), $field_to_select = null)
1783
-    {
1784
-        $query_params['limit'] = 1;
1785
-        $col = $this->get_col($query_params, $field_to_select);
1786
-        if (! empty($col)) {
1787
-            return reset($col);
1788
-        } else {
1789
-            return null;
1790
-        }
1791
-    }
1792
-
1793
-
1794
-
1795
-    /**
1796
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1797
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1798
-     * injection, but currently no further filtering is done
1799
-     *
1800
-     * @global      $wpdb
1801
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1802
-     *                               be updated to in the DB
1803
-     * @return string of SQL
1804
-     * @throws \EE_Error
1805
-     */
1806
-    public function _construct_update_sql($fields_n_values)
1807
-    {
1808
-        /** @type WPDB $wpdb */
1809
-        global $wpdb;
1810
-        $cols_n_values = array();
1811
-        foreach ($fields_n_values as $field_name => $value) {
1812
-            $field_obj = $this->field_settings_for($field_name);
1813
-            //if the value is NULL, we want to assign the value to that.
1814
-            //wpdb->prepare doesn't really handle that properly
1815
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1816
-            $value_sql = $prepared_value === null ? 'NULL'
1817
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1818
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1819
-        }
1820
-        return implode(",", $cols_n_values);
1821
-    }
1822
-
1823
-
1824
-
1825
-    /**
1826
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1827
-     * Performs a HARD delete, meaning the database row should always be removed,
1828
-     * not just have a flag field on it switched
1829
-     * Wrapper for EEM_Base::delete_permanently()
1830
-     *
1831
-     * @param mixed $id
1832
-     * @return boolean whether the row got deleted or not
1833
-     * @throws \EE_Error
1834
-     */
1835
-    public function delete_permanently_by_ID($id)
1836
-    {
1837
-        return $this->delete_permanently(
1838
-            array(
1839
-                array($this->get_primary_key_field()->get_name() => $id),
1840
-                'limit' => 1,
1841
-            )
1842
-        );
1843
-    }
1844
-
1845
-
1846
-
1847
-    /**
1848
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
-     * Wrapper for EEM_Base::delete()
1850
-     *
1851
-     * @param mixed $id
1852
-     * @return boolean whether the row got deleted or not
1853
-     * @throws \EE_Error
1854
-     */
1855
-    public function delete_by_ID($id)
1856
-    {
1857
-        return $this->delete(
1858
-            array(
1859
-                array($this->get_primary_key_field()->get_name() => $id),
1860
-                'limit' => 1,
1861
-            )
1862
-        );
1863
-    }
1864
-
1865
-
1866
-
1867
-    /**
1868
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1869
-     * meaning if the model has a field that indicates its been "trashed" or
1870
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1871
-     *
1872
-     * @see EEM_Base::delete_permanently
1873
-     * @param array   $query_params
1874
-     * @param boolean $allow_blocking
1875
-     * @return int how many rows got deleted
1876
-     * @throws \EE_Error
1877
-     */
1878
-    public function delete($query_params, $allow_blocking = true)
1879
-    {
1880
-        return $this->delete_permanently($query_params, $allow_blocking);
1881
-    }
1882
-
1883
-
1884
-
1885
-    /**
1886
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1887
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1888
-     * as archived, not actually deleted
1889
-     *
1890
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1891
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1892
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1893
-     *                                deletes regardless of other objects which may depend on it. Its generally
1894
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1895
-     *                                DB
1896
-     * @return int how many rows got deleted
1897
-     * @throws \EE_Error
1898
-     */
1899
-    public function delete_permanently($query_params, $allow_blocking = true)
1900
-    {
1901
-        /**
1902
-         * Action called just before performing a real deletion query. You can use the
1903
-         * model and its $query_params to find exactly which items will be deleted
1904
-         *
1905
-         * @param EEM_Base $model
1906
-         * @param array    $query_params   @see EEM_Base::get_all()
1907
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1908
-         *                                 to block (prevent) this deletion
1909
-         */
1910
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1911
-        //some MySQL databases may be running safe mode, which may restrict
1912
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1913
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1914
-        //to delete them
1915
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1916
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1917
-        if ($deletion_where) {
1918
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1919
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1920
-            $table_aliases = array_keys($this->_tables);
1921
-            $SQL = "DELETE "
1922
-                   . implode(", ", $table_aliases)
1923
-                   . " FROM "
1924
-                   . $model_query_info->get_full_join_sql()
1925
-                   . " WHERE "
1926
-                   . $deletion_where;
1927
-            //		/echo "delete sql:$SQL";
1928
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1929
-        } else {
1930
-            $rows_deleted = 0;
1931
-        }
1932
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1933
-        if ($this->has_primary_key_field()) {
1934
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1935
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1936
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1937
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1938
-                }
1939
-            }
1940
-        }
1941
-        /**
1942
-         * Action called just after performing a real deletion query. Although at this point the
1943
-         * items should have been deleted
1944
-         *
1945
-         * @param EEM_Base $model
1946
-         * @param array    $query_params @see EEM_Base::get_all()
1947
-         * @param int      $rows_deleted
1948
-         */
1949
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1950
-        return $rows_deleted;//how many supposedly got deleted
1951
-    }
1952
-
1953
-
1954
-
1955
-    /**
1956
-     * Checks all the relations that throw error messages when there are blocking related objects
1957
-     * for related model objects. If there are any related model objects on those relations,
1958
-     * adds an EE_Error, and return true
1959
-     *
1960
-     * @param EE_Base_Class|int $this_model_obj_or_id
1961
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1962
-     *                                                 should be ignored when determining whether there are related
1963
-     *                                                 model objects which block this model object's deletion. Useful
1964
-     *                                                 if you know A is related to B and are considering deleting A,
1965
-     *                                                 but want to see if A has any other objects blocking its deletion
1966
-     *                                                 before removing the relation between A and B
1967
-     * @return boolean
1968
-     * @throws \EE_Error
1969
-     */
1970
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1971
-    {
1972
-        //first, if $ignore_this_model_obj was supplied, get its model
1973
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1974
-            $ignored_model = $ignore_this_model_obj->get_model();
1975
-        } else {
1976
-            $ignored_model = null;
1977
-        }
1978
-        //now check all the relations of $this_model_obj_or_id and see if there
1979
-        //are any related model objects blocking it?
1980
-        $is_blocked = false;
1981
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1982
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1983
-                //if $ignore_this_model_obj was supplied, then for the query
1984
-                //on that model needs to be told to ignore $ignore_this_model_obj
1985
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1986
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1987
-                        array(
1988
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1989
-                                '!=',
1990
-                                $ignore_this_model_obj->ID(),
1991
-                            ),
1992
-                        ),
1993
-                    ));
1994
-                } else {
1995
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1996
-                }
1997
-                if ($related_model_objects) {
1998
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1999
-                    $is_blocked = true;
2000
-                }
2001
-            }
2002
-        }
2003
-        return $is_blocked;
2004
-    }
2005
-
2006
-
2007
-
2008
-    /**
2009
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2010
-     * well.
2011
-     *
2012
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2013
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2014
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2015
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2016
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2017
-     *                                      easily corrupt your DB
2018
-     * @throws EE_Error
2019
-     * @return string    everything that comes after the WHERE statement.
2020
-     */
2021
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2022
-    {
2023
-        if ($this->has_primary_key_field()) {
2024
-            $primary_table = $this->_get_main_table();
2025
-            $other_tables = $this->_get_other_tables();
2026
-            $deletes = $query = array();
2027
-            foreach ($objects_for_deletion as $delete_object) {
2028
-                //before we mark this object for deletion,
2029
-                //make sure there's no related objects blocking its deletion (if we're checking)
2030
-                if (
2031
-                    $allow_blocking
2032
-                    && $this->delete_is_blocked_by_related_models(
2033
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2034
-                    )
2035
-                ) {
2036
-                    continue;
2037
-                }
2038
-                //primary table deletes
2039
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2040
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2041
-                }
2042
-                //other tables
2043
-                if (! empty($other_tables)) {
2044
-                    foreach ($other_tables as $ot) {
2045
-                        //first check if we've got the foreign key column here.
2046
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2047
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2048
-                        }
2049
-                        // wait! it's entirely possible that we'll have a the primary key
2050
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2051
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2052
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2053
-                        }
2054
-                        // finally, it is possible that the fk for this table is found
2055
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2056
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2057
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2058
-                        }
2059
-                    }
2060
-                }
2061
-            }
2062
-            //we should have deletes now, so let's just go through and setup the where statement
2063
-            foreach ($deletes as $column => $values) {
2064
-                //make sure we have unique $values;
2065
-                $values = array_unique($values);
2066
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
-            }
2068
-            return ! empty($query) ? implode(' AND ', $query) : '';
2069
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2070
-            $ways_to_identify_a_row = array();
2071
-            $fields = $this->get_combined_primary_key_fields();
2072
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2073
-            foreach ($objects_for_deletion as $delete_object) {
2074
-                $values_for_each_cpk_for_a_row = array();
2075
-                foreach ($fields as $cpk_field) {
2076
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2077
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2078
-                                                           . "="
2079
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2080
-                    }
2081
-                }
2082
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2083
-            }
2084
-            return implode(" OR ", $ways_to_identify_a_row);
2085
-        } else {
2086
-            //so there's no primary key and no combined key...
2087
-            //sorry, can't help you
2088
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2089
-                "event_espresso"), get_class($this)));
2090
-        }
2091
-    }
2092
-
2093
-
2094
-
2095
-    /**
2096
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2097
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2098
-     * column
2099
-     *
2100
-     * @param array  $query_params   like EEM_Base::get_all's
2101
-     * @param string $field_to_count field on model to count by (not column name)
2102
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2103
-     *                               that by the setting $distinct to TRUE;
2104
-     * @return int
2105
-     * @throws \EE_Error
2106
-     */
2107
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2108
-    {
2109
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2110
-        if ($field_to_count) {
2111
-            $field_obj = $this->field_settings_for($field_to_count);
2112
-            $column_to_count = $field_obj->get_qualified_column();
2113
-        } elseif ($this->has_primary_key_field()) {
2114
-            $pk_field_obj = $this->get_primary_key_field();
2115
-            $column_to_count = $pk_field_obj->get_qualified_column();
2116
-        } else {
2117
-            //there's no primary key
2118
-            //if we're counting distinct items, and there's no primary key,
2119
-            //we need to list out the columns for distinction;
2120
-            //otherwise we can just use star
2121
-            if ($distinct) {
2122
-                $columns_to_use = array();
2123
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2124
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2125
-                }
2126
-                $column_to_count = implode(',', $columns_to_use);
2127
-            } else {
2128
-                $column_to_count = '*';
2129
-            }
2130
-        }
2131
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2132
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2133
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2134
-    }
2135
-
2136
-
2137
-
2138
-    /**
2139
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2140
-     *
2141
-     * @param array  $query_params like EEM_Base::get_all
2142
-     * @param string $field_to_sum name of field (array key in $_fields array)
2143
-     * @return float
2144
-     * @throws \EE_Error
2145
-     */
2146
-    public function sum($query_params, $field_to_sum = null)
2147
-    {
2148
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2149
-        if ($field_to_sum) {
2150
-            $field_obj = $this->field_settings_for($field_to_sum);
2151
-        } else {
2152
-            $field_obj = $this->get_primary_key_field();
2153
-        }
2154
-        $column_to_count = $field_obj->get_qualified_column();
2155
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2157
-        $data_type = $field_obj->get_wpdb_data_type();
2158
-        if ($data_type === '%d' || $data_type === '%s') {
2159
-            return (float)$return_value;
2160
-        } else {//must be %f
2161
-            return (float)$return_value;
2162
-        }
2163
-    }
2164
-
2165
-
2166
-
2167
-    /**
2168
-     * Just calls the specified method on $wpdb with the given arguments
2169
-     * Consolidates a little extra error handling code
2170
-     *
2171
-     * @param string $wpdb_method
2172
-     * @param array  $arguments_to_provide
2173
-     * @throws EE_Error
2174
-     * @global wpdb  $wpdb
2175
-     * @return mixed
2176
-     */
2177
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2178
-    {
2179
-        //if we're in maintenance mode level 2, DON'T run any queries
2180
-        //because level 2 indicates the database needs updating and
2181
-        //is probably out of sync with the code
2182
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2183
-            throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2184
-                "event_espresso")));
2185
-        }
2186
-        /** @type WPDB $wpdb */
2187
-        global $wpdb;
2188
-        if (! method_exists($wpdb, $wpdb_method)) {
2189
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2190
-                'event_espresso'), $wpdb_method));
2191
-        }
2192
-        if (WP_DEBUG) {
2193
-            $old_show_errors_value = $wpdb->show_errors;
2194
-            $wpdb->show_errors(false);
2195
-        }
2196
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2197
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2198
-        if (WP_DEBUG) {
2199
-            $wpdb->show_errors($old_show_errors_value);
2200
-            if (! empty($wpdb->last_error)) {
2201
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2202
-            } elseif ($result === false) {
2203
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2204
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2205
-            }
2206
-        } elseif ($result === false) {
2207
-            EE_Error::add_error(
2208
-                sprintf(
2209
-                    __('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"',
2210
-                        'event_espresso'),
2211
-                    $wpdb_method,
2212
-                    var_export($arguments_to_provide, true),
2213
-                    $wpdb->last_error
2214
-                ),
2215
-                __FILE__,
2216
-                __FUNCTION__,
2217
-                __LINE__
2218
-            );
2219
-        }
2220
-        return $result;
2221
-    }
2222
-
2223
-
2224
-
2225
-    /**
2226
-     * Attempts to run the indicated WPDB method with the provided arguments,
2227
-     * and if there's an error tries to verify the DB is correct. Uses
2228
-     * the static property EEM_Base::$_db_verification_level to determine whether
2229
-     * we should try to fix the EE core db, the addons, or just give up
2230
-     *
2231
-     * @param string $wpdb_method
2232
-     * @param array  $arguments_to_provide
2233
-     * @return mixed
2234
-     */
2235
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2236
-    {
2237
-        /** @type WPDB $wpdb */
2238
-        global $wpdb;
2239
-        $wpdb->last_error = null;
2240
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2241
-        // was there an error running the query? but we don't care on new activations
2242
-        // (we're going to setup the DB anyway on new activations)
2243
-        if (($result === false || ! empty($wpdb->last_error))
2244
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2245
-        ) {
2246
-            switch (EEM_Base::$_db_verification_level) {
2247
-                case EEM_Base::db_verified_none :
2248
-                    // let's double-check core's DB
2249
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2250
-                    break;
2251
-                case EEM_Base::db_verified_core :
2252
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2253
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2254
-                    break;
2255
-                case EEM_Base::db_verified_addons :
2256
-                    // ummmm... you in trouble
2257
-                    return $result;
2258
-                    break;
2259
-            }
2260
-            if (! empty($error_message)) {
2261
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2262
-                trigger_error($error_message);
2263
-            }
2264
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2265
-        }
2266
-        return $result;
2267
-    }
2268
-
2269
-
2270
-
2271
-    /**
2272
-     * Verifies the EE core database is up-to-date and records that we've done it on
2273
-     * EEM_Base::$_db_verification_level
2274
-     *
2275
-     * @param string $wpdb_method
2276
-     * @param array  $arguments_to_provide
2277
-     * @return string
2278
-     */
2279
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2280
-    {
2281
-        /** @type WPDB $wpdb */
2282
-        global $wpdb;
2283
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2284
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2285
-        $error_message = sprintf(
2286
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2287
-                'event_espresso'),
2288
-            $wpdb->last_error,
2289
-            $wpdb_method,
2290
-            wp_json_encode($arguments_to_provide)
2291
-        );
2292
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2293
-        return $error_message;
2294
-    }
2295
-
2296
-
2297
-
2298
-    /**
2299
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2300
-     * EEM_Base::$_db_verification_level
2301
-     *
2302
-     * @param $wpdb_method
2303
-     * @param $arguments_to_provide
2304
-     * @return string
2305
-     */
2306
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2307
-    {
2308
-        /** @type WPDB $wpdb */
2309
-        global $wpdb;
2310
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2311
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2312
-        $error_message = sprintf(
2313
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2314
-                'event_espresso'),
2315
-            $wpdb->last_error,
2316
-            $wpdb_method,
2317
-            wp_json_encode($arguments_to_provide)
2318
-        );
2319
-        EE_System::instance()->initialize_addons();
2320
-        return $error_message;
2321
-    }
2322
-
2323
-
2324
-
2325
-    /**
2326
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2327
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2328
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2329
-     * ..."
2330
-     *
2331
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2332
-     * @return string
2333
-     */
2334
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2335
-    {
2336
-        return " FROM " . $model_query_info->get_full_join_sql() .
2337
-               $model_query_info->get_where_sql() .
2338
-               $model_query_info->get_group_by_sql() .
2339
-               $model_query_info->get_having_sql() .
2340
-               $model_query_info->get_order_by_sql() .
2341
-               $model_query_info->get_limit_sql();
2342
-    }
2343
-
2344
-
2345
-
2346
-    /**
2347
-     * Set to easily debug the next X queries ran from this model.
2348
-     *
2349
-     * @param int $count
2350
-     */
2351
-    public function show_next_x_db_queries($count = 1)
2352
-    {
2353
-        $this->_show_next_x_db_queries = $count;
2354
-    }
2355
-
2356
-
2357
-
2358
-    /**
2359
-     * @param $sql_query
2360
-     */
2361
-    public function show_db_query_if_previously_requested($sql_query)
2362
-    {
2363
-        if ($this->_show_next_x_db_queries > 0) {
2364
-            echo $sql_query;
2365
-            $this->_show_next_x_db_queries--;
2366
-        }
2367
-    }
2368
-
2369
-
2370
-
2371
-    /**
2372
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2373
-     * There are the 3 cases:
2374
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2375
-     * $otherModelObject has no ID, it is first saved.
2376
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2377
-     * has no ID, it is first saved.
2378
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2379
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2380
-     * join table
2381
-     *
2382
-     * @param        EE_Base_Class                     /int $thisModelObject
2383
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2384
-     * @param string $relationName                     , key in EEM_Base::_relations
2385
-     *                                                 an attendee to a group, you also want to specify which role they
2386
-     *                                                 will have in that group. So you would use this parameter to
2387
-     *                                                 specify array('role-column-name'=>'role-id')
2388
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2389
-     *                                                 to for relation to methods that allow you to further specify
2390
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2391
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2392
-     *                                                 because these will be inserted in any new rows created as well.
2393
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2394
-     * @throws \EE_Error
2395
-     */
2396
-    public function add_relationship_to(
2397
-        $id_or_obj,
2398
-        $other_model_id_or_obj,
2399
-        $relationName,
2400
-        $extra_join_model_fields_n_values = array()
2401
-    ) {
2402
-        $relation_obj = $this->related_settings_for($relationName);
2403
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2404
-    }
2405
-
2406
-
2407
-
2408
-    /**
2409
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2410
-     * There are the 3 cases:
2411
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2412
-     * error
2413
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2414
-     * an error
2415
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2416
-     *
2417
-     * @param        EE_Base_Class /int $id_or_obj
2418
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2419
-     * @param string $relationName key in EEM_Base::_relations
2420
-     * @return boolean of success
2421
-     * @throws \EE_Error
2422
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2423
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2424
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2425
-     *                             because these will be inserted in any new rows created as well.
2426
-     */
2427
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2428
-    {
2429
-        $relation_obj = $this->related_settings_for($relationName);
2430
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2431
-    }
2432
-
2433
-
2434
-
2435
-    /**
2436
-     * @param mixed           $id_or_obj
2437
-     * @param string          $relationName
2438
-     * @param array           $where_query_params
2439
-     * @param EE_Base_Class[] objects to which relations were removed
2440
-     * @return \EE_Base_Class[]
2441
-     * @throws \EE_Error
2442
-     */
2443
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2444
-    {
2445
-        $relation_obj = $this->related_settings_for($relationName);
2446
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2447
-    }
2448
-
2449
-
2450
-
2451
-    /**
2452
-     * Gets all the related items of the specified $model_name, using $query_params.
2453
-     * Note: by default, we remove the "default query params"
2454
-     * because we want to get even deleted items etc.
2455
-     *
2456
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2457
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2458
-     * @param array  $query_params like EEM_Base::get_all
2459
-     * @return EE_Base_Class[]
2460
-     * @throws \EE_Error
2461
-     */
2462
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2463
-    {
2464
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2465
-        $relation_settings = $this->related_settings_for($model_name);
2466
-        return $relation_settings->get_all_related($model_obj, $query_params);
2467
-    }
2468
-
2469
-
2470
-
2471
-    /**
2472
-     * Deletes all the model objects across the relation indicated by $model_name
2473
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2474
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2475
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2476
-     *
2477
-     * @param EE_Base_Class|int|string $id_or_obj
2478
-     * @param string                   $model_name
2479
-     * @param array                    $query_params
2480
-     * @return int how many deleted
2481
-     * @throws \EE_Error
2482
-     */
2483
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2484
-    {
2485
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2486
-        $relation_settings = $this->related_settings_for($model_name);
2487
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2488
-    }
2489
-
2490
-
2491
-
2492
-    /**
2493
-     * Hard deletes all the model objects across the relation indicated by $model_name
2494
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2495
-     * the model objects can't be hard deleted because of blocking related model objects,
2496
-     * just does a soft-delete on them instead.
2497
-     *
2498
-     * @param EE_Base_Class|int|string $id_or_obj
2499
-     * @param string                   $model_name
2500
-     * @param array                    $query_params
2501
-     * @return int how many deleted
2502
-     * @throws \EE_Error
2503
-     */
2504
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2505
-    {
2506
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2507
-        $relation_settings = $this->related_settings_for($model_name);
2508
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2509
-    }
2510
-
2511
-
2512
-
2513
-    /**
2514
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2515
-     * unless otherwise specified in the $query_params
2516
-     *
2517
-     * @param        int             /EE_Base_Class $id_or_obj
2518
-     * @param string $model_name     like 'Event', or 'Registration'
2519
-     * @param array  $query_params   like EEM_Base::get_all's
2520
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2521
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2522
-     *                               that by the setting $distinct to TRUE;
2523
-     * @return int
2524
-     * @throws \EE_Error
2525
-     */
2526
-    public function count_related(
2527
-        $id_or_obj,
2528
-        $model_name,
2529
-        $query_params = array(),
2530
-        $field_to_count = null,
2531
-        $distinct = false
2532
-    ) {
2533
-        $related_model = $this->get_related_model_obj($model_name);
2534
-        //we're just going to use the query params on the related model's normal get_all query,
2535
-        //except add a condition to say to match the current mod
2536
-        if (! isset($query_params['default_where_conditions'])) {
2537
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2538
-        }
2539
-        $this_model_name = $this->get_this_model_name();
2540
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2541
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2542
-        return $related_model->count($query_params, $field_to_count, $distinct);
2543
-    }
2544
-
2545
-
2546
-
2547
-    /**
2548
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2549
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2550
-     *
2551
-     * @param        int           /EE_Base_Class $id_or_obj
2552
-     * @param string $model_name   like 'Event', or 'Registration'
2553
-     * @param array  $query_params like EEM_Base::get_all's
2554
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2555
-     * @return float
2556
-     * @throws \EE_Error
2557
-     */
2558
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2559
-    {
2560
-        $related_model = $this->get_related_model_obj($model_name);
2561
-        if (! is_array($query_params)) {
2562
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2563
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2564
-                    gettype($query_params)), '4.6.0');
2565
-            $query_params = array();
2566
-        }
2567
-        //we're just going to use the query params on the related model's normal get_all query,
2568
-        //except add a condition to say to match the current mod
2569
-        if (! isset($query_params['default_where_conditions'])) {
2570
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2571
-        }
2572
-        $this_model_name = $this->get_this_model_name();
2573
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2574
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2575
-        return $related_model->sum($query_params, $field_to_sum);
2576
-    }
2577
-
2578
-
2579
-
2580
-    /**
2581
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2582
-     * $modelObject
2583
-     *
2584
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2585
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2586
-     * @param array               $query_params     like EEM_Base::get_all's
2587
-     * @return EE_Base_Class
2588
-     * @throws \EE_Error
2589
-     */
2590
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2591
-    {
2592
-        $query_params['limit'] = 1;
2593
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2594
-        if ($results) {
2595
-            return array_shift($results);
2596
-        } else {
2597
-            return null;
2598
-        }
2599
-    }
2600
-
2601
-
2602
-
2603
-    /**
2604
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2605
-     *
2606
-     * @return string
2607
-     */
2608
-    public function get_this_model_name()
2609
-    {
2610
-        return str_replace("EEM_", "", get_class($this));
2611
-    }
2612
-
2613
-
2614
-
2615
-    /**
2616
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2617
-     *
2618
-     * @return EE_Any_Foreign_Model_Name_Field
2619
-     * @throws EE_Error
2620
-     */
2621
-    public function get_field_containing_related_model_name()
2622
-    {
2623
-        foreach ($this->field_settings(true) as $field) {
2624
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2625
-                $field_with_model_name = $field;
2626
-            }
2627
-        }
2628
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2629
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2630
-                $this->get_this_model_name()));
2631
-        }
2632
-        return $field_with_model_name;
2633
-    }
2634
-
2635
-
2636
-
2637
-    /**
2638
-     * Inserts a new entry into the database, for each table.
2639
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2640
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2641
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2642
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2643
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2644
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2645
-     *
2646
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2647
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2648
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2649
-     *                              of EEM_Base)
2650
-     * @return int new primary key on main table that got inserted
2651
-     * @throws EE_Error
2652
-     */
2653
-    public function insert($field_n_values)
2654
-    {
2655
-        /**
2656
-         * Filters the fields and their values before inserting an item using the models
2657
-         *
2658
-         * @param array    $fields_n_values keys are the fields and values are their new values
2659
-         * @param EEM_Base $model           the model used
2660
-         */
2661
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2662
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2663
-            $main_table = $this->_get_main_table();
2664
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2665
-            if ($new_id !== false) {
2666
-                foreach ($this->_get_other_tables() as $other_table) {
2667
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2668
-                }
2669
-            }
2670
-            /**
2671
-             * Done just after attempting to insert a new model object
2672
-             *
2673
-             * @param EEM_Base   $model           used
2674
-             * @param array      $fields_n_values fields and their values
2675
-             * @param int|string the              ID of the newly-inserted model object
2676
-             */
2677
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2678
-            return $new_id;
2679
-        } else {
2680
-            return false;
2681
-        }
2682
-    }
2683
-
2684
-
2685
-
2686
-    /**
2687
-     * Checks that the result would satisfy the unique indexes on this model
2688
-     *
2689
-     * @param array  $field_n_values
2690
-     * @param string $action
2691
-     * @return boolean
2692
-     * @throws \EE_Error
2693
-     */
2694
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2695
-    {
2696
-        foreach ($this->unique_indexes() as $index_name => $index) {
2697
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2698
-            if ($this->exists(array($uniqueness_where_params))) {
2699
-                EE_Error::add_error(
2700
-                    sprintf(
2701
-                        __(
2702
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2703
-                            "event_espresso"
2704
-                        ),
2705
-                        $action,
2706
-                        $this->_get_class_name(),
2707
-                        $index_name,
2708
-                        implode(",", $index->field_names()),
2709
-                        http_build_query($uniqueness_where_params)
2710
-                    ),
2711
-                    __FILE__,
2712
-                    __FUNCTION__,
2713
-                    __LINE__
2714
-                );
2715
-                return false;
2716
-            }
2717
-        }
2718
-        return true;
2719
-    }
2720
-
2721
-
2722
-
2723
-    /**
2724
-     * Checks the database for an item that conflicts (ie, if this item were
2725
-     * saved to the DB would break some uniqueness requirement, like a primary key
2726
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2727
-     * can be either an EE_Base_Class or an array of fields n values
2728
-     *
2729
-     * @param EE_Base_Class|array $obj_or_fields_array
2730
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2731
-     *                                                 when looking for conflicts
2732
-     *                                                 (ie, if false, we ignore the model object's primary key
2733
-     *                                                 when finding "conflicts". If true, it's also considered).
2734
-     *                                                 Only works for INT primary key,
2735
-     *                                                 STRING primary keys cannot be ignored
2736
-     * @throws EE_Error
2737
-     * @return EE_Base_Class|array
2738
-     */
2739
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2740
-    {
2741
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2742
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2743
-        } elseif (is_array($obj_or_fields_array)) {
2744
-            $fields_n_values = $obj_or_fields_array;
2745
-        } else {
2746
-            throw new EE_Error(
2747
-                sprintf(
2748
-                    __(
2749
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2750
-                        "event_espresso"
2751
-                    ),
2752
-                    get_class($this),
2753
-                    $obj_or_fields_array
2754
-                )
2755
-            );
2756
-        }
2757
-        $query_params = array();
2758
-        if ($this->has_primary_key_field()
2759
-            && ($include_primary_key
2760
-                || $this->get_primary_key_field()
2761
-                   instanceof
2762
-                   EE_Primary_Key_String_Field)
2763
-            && isset($fields_n_values[$this->primary_key_name()])
2764
-        ) {
2765
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2766
-        }
2767
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2768
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2769
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2770
-        }
2771
-        //if there is nothing to base this search on, then we shouldn't find anything
2772
-        if (empty($query_params)) {
2773
-            return array();
2774
-        } else {
2775
-            return $this->get_one($query_params);
2776
-        }
2777
-    }
2778
-
2779
-
2780
-
2781
-    /**
2782
-     * Like count, but is optimized and returns a boolean instead of an int
2783
-     *
2784
-     * @param array $query_params
2785
-     * @return boolean
2786
-     * @throws \EE_Error
2787
-     */
2788
-    public function exists($query_params)
2789
-    {
2790
-        $query_params['limit'] = 1;
2791
-        return $this->count($query_params) > 0;
2792
-    }
2793
-
2794
-
2795
-
2796
-    /**
2797
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2798
-     *
2799
-     * @param int|string $id
2800
-     * @return boolean
2801
-     * @throws \EE_Error
2802
-     */
2803
-    public function exists_by_ID($id)
2804
-    {
2805
-        return $this->exists(
2806
-            array(
2807
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2808
-                array(
2809
-                    $this->primary_key_name() => $id,
2810
-                ),
2811
-            )
2812
-        );
2813
-    }
2814
-
2815
-
2816
-
2817
-    /**
2818
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2819
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2820
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2821
-     * on the main table)
2822
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2823
-     * cases where we want to call it directly rather than via insert().
2824
-     *
2825
-     * @access   protected
2826
-     * @param EE_Table_Base $table
2827
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2828
-     *                                       float
2829
-     * @param int           $new_id          for now we assume only int keys
2830
-     * @throws EE_Error
2831
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2832
-     * @return int ID of new row inserted, or FALSE on failure
2833
-     */
2834
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2835
-    {
2836
-        global $wpdb;
2837
-        $insertion_col_n_values = array();
2838
-        $format_for_insertion = array();
2839
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2840
-        foreach ($fields_on_table as $field_name => $field_obj) {
2841
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2842
-            if ($field_obj->is_auto_increment()) {
2843
-                continue;
2844
-            }
2845
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2846
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2847
-            if ($prepared_value !== null) {
2848
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2849
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2850
-            }
2851
-        }
2852
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2853
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2854
-            //so add the fk to the main table as a column
2855
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2856
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2857
-        }
2858
-        //insert the new entry
2859
-        $result = $this->_do_wpdb_query('insert',
2860
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2861
-        if ($result === false) {
2862
-            return false;
2863
-        }
2864
-        //ok, now what do we return for the ID of the newly-inserted thing?
2865
-        if ($this->has_primary_key_field()) {
2866
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2867
-                return $wpdb->insert_id;
2868
-            } else {
2869
-                //it's not an auto-increment primary key, so
2870
-                //it must have been supplied
2871
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2872
-            }
2873
-        } else {
2874
-            //we can't return a  primary key because there is none. instead return
2875
-            //a unique string indicating this model
2876
-            return $this->get_index_primary_key_string($fields_n_values);
2877
-        }
2878
-    }
2879
-
2880
-
2881
-
2882
-    /**
2883
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2884
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2885
-     * and there is no default, we pass it along. WPDB will take care of it)
2886
-     *
2887
-     * @param EE_Model_Field_Base $field_obj
2888
-     * @param array               $fields_n_values
2889
-     * @return mixed string|int|float depending on what the table column will be expecting
2890
-     * @throws \EE_Error
2891
-     */
2892
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2893
-    {
2894
-        //if this field doesn't allow nullable, don't allow it
2895
-        if (
2896
-            ! $field_obj->is_nullable()
2897
-            && (
2898
-                ! isset($fields_n_values[$field_obj->get_name()])
2899
-                || $fields_n_values[$field_obj->get_name()] === null
2900
-            )
2901
-        ) {
2902
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2903
-        }
2904
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2905
-            ? $fields_n_values[$field_obj->get_name()]
2906
-            : null;
2907
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2908
-    }
2909
-
2910
-
2911
-
2912
-    /**
2913
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2914
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2915
-     * the field's prepare_for_set() method.
2916
-     *
2917
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2918
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2919
-     *                                   top of file)
2920
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2921
-     *                                   $value is a custom selection
2922
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2923
-     */
2924
-    private function _prepare_value_for_use_in_db($value, $field)
2925
-    {
2926
-        if ($field && $field instanceof EE_Model_Field_Base) {
2927
-            switch ($this->_values_already_prepared_by_model_object) {
2928
-                /** @noinspection PhpMissingBreakStatementInspection */
2929
-                case self::not_prepared_by_model_object:
2930
-                    $value = $field->prepare_for_set($value);
2931
-                //purposefully left out "return"
2932
-                case self::prepared_by_model_object:
2933
-                    $value = $field->prepare_for_use_in_db($value);
2934
-                case self::prepared_for_use_in_db:
2935
-                    //leave the value alone
2936
-            }
2937
-            return $value;
2938
-        } else {
2939
-            return $value;
2940
-        }
2941
-    }
2942
-
2943
-
2944
-
2945
-    /**
2946
-     * Returns the main table on this model
2947
-     *
2948
-     * @return EE_Primary_Table
2949
-     * @throws EE_Error
2950
-     */
2951
-    protected function _get_main_table()
2952
-    {
2953
-        foreach ($this->_tables as $table) {
2954
-            if ($table instanceof EE_Primary_Table) {
2955
-                return $table;
2956
-            }
2957
-        }
2958
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2959
-            'event_espresso'), get_class($this)));
2960
-    }
2961
-
2962
-
2963
-
2964
-    /**
2965
-     * table
2966
-     * returns EE_Primary_Table table name
2967
-     *
2968
-     * @return string
2969
-     * @throws \EE_Error
2970
-     */
2971
-    public function table()
2972
-    {
2973
-        return $this->_get_main_table()->get_table_name();
2974
-    }
2975
-
2976
-
2977
-
2978
-    /**
2979
-     * table
2980
-     * returns first EE_Secondary_Table table name
2981
-     *
2982
-     * @return string
2983
-     */
2984
-    public function second_table()
2985
-    {
2986
-        // grab second table from tables array
2987
-        $second_table = end($this->_tables);
2988
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2989
-    }
2990
-
2991
-
2992
-
2993
-    /**
2994
-     * get_table_obj_by_alias
2995
-     * returns table name given it's alias
2996
-     *
2997
-     * @param string $table_alias
2998
-     * @return EE_Primary_Table | EE_Secondary_Table
2999
-     */
3000
-    public function get_table_obj_by_alias($table_alias = '')
3001
-    {
3002
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3003
-    }
3004
-
3005
-
3006
-
3007
-    /**
3008
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3009
-     *
3010
-     * @return EE_Secondary_Table[]
3011
-     */
3012
-    protected function _get_other_tables()
3013
-    {
3014
-        $other_tables = array();
3015
-        foreach ($this->_tables as $table_alias => $table) {
3016
-            if ($table instanceof EE_Secondary_Table) {
3017
-                $other_tables[$table_alias] = $table;
3018
-            }
3019
-        }
3020
-        return $other_tables;
3021
-    }
3022
-
3023
-
3024
-
3025
-    /**
3026
-     * Finds all the fields that correspond to the given table
3027
-     *
3028
-     * @param string $table_alias , array key in EEM_Base::_tables
3029
-     * @return EE_Model_Field_Base[]
3030
-     */
3031
-    public function _get_fields_for_table($table_alias)
3032
-    {
3033
-        return $this->_fields[$table_alias];
3034
-    }
3035
-
3036
-
3037
-
3038
-    /**
3039
-     * Recurses through all the where parameters, and finds all the related models we'll need
3040
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3041
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3042
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3043
-     * related Registration, Transaction, and Payment models.
3044
-     *
3045
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3046
-     * @return EE_Model_Query_Info_Carrier
3047
-     * @throws \EE_Error
3048
-     */
3049
-    public function _extract_related_models_from_query($query_params)
3050
-    {
3051
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3052
-        if (array_key_exists(0, $query_params)) {
3053
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3054
-        }
3055
-        if (array_key_exists('group_by', $query_params)) {
3056
-            if (is_array($query_params['group_by'])) {
3057
-                $this->_extract_related_models_from_sub_params_array_values(
3058
-                    $query_params['group_by'],
3059
-                    $query_info_carrier,
3060
-                    'group_by'
3061
-                );
3062
-            } elseif (! empty ($query_params['group_by'])) {
3063
-                $this->_extract_related_model_info_from_query_param(
3064
-                    $query_params['group_by'],
3065
-                    $query_info_carrier,
3066
-                    'group_by'
3067
-                );
3068
-            }
3069
-        }
3070
-        if (array_key_exists('having', $query_params)) {
3071
-            $this->_extract_related_models_from_sub_params_array_keys(
3072
-                $query_params[0],
3073
-                $query_info_carrier,
3074
-                'having'
3075
-            );
3076
-        }
3077
-        if (array_key_exists('order_by', $query_params)) {
3078
-            if (is_array($query_params['order_by'])) {
3079
-                $this->_extract_related_models_from_sub_params_array_keys(
3080
-                    $query_params['order_by'],
3081
-                    $query_info_carrier,
3082
-                    'order_by'
3083
-                );
3084
-            } elseif (! empty($query_params['order_by'])) {
3085
-                $this->_extract_related_model_info_from_query_param(
3086
-                    $query_params['order_by'],
3087
-                    $query_info_carrier,
3088
-                    'order_by'
3089
-                );
3090
-            }
3091
-        }
3092
-        if (array_key_exists('force_join', $query_params)) {
3093
-            $this->_extract_related_models_from_sub_params_array_values(
3094
-                $query_params['force_join'],
3095
-                $query_info_carrier,
3096
-                'force_join'
3097
-            );
3098
-        }
3099
-        return $query_info_carrier;
3100
-    }
3101
-
3102
-
3103
-
3104
-    /**
3105
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3106
-     *
3107
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3108
-     *                                                      $query_params['having']
3109
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3110
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3111
-     * @throws EE_Error
3112
-     * @return \EE_Model_Query_Info_Carrier
3113
-     */
3114
-    private function _extract_related_models_from_sub_params_array_keys(
3115
-        $sub_query_params,
3116
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3117
-        $query_param_type
3118
-    ) {
3119
-        if (! empty($sub_query_params)) {
3120
-            $sub_query_params = (array)$sub_query_params;
3121
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3122
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3123
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3124
-                    $query_param_type);
3125
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3126
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3127
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3128
-                //of array('Registration.TXN_ID'=>23)
3129
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3130
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3131
-                    if (! is_array($possibly_array_of_params)) {
3132
-                        throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3133
-                            "event_espresso"),
3134
-                            $param, $possibly_array_of_params));
3135
-                    } else {
3136
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3137
-                            $model_query_info_carrier, $query_param_type);
3138
-                    }
3139
-                } elseif ($query_param_type === 0 //ie WHERE
3140
-                          && is_array($possibly_array_of_params)
3141
-                          && isset($possibly_array_of_params[2])
3142
-                          && $possibly_array_of_params[2] == true
3143
-                ) {
3144
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3145
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3146
-                    //from which we should extract query parameters!
3147
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3148
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3149
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3150
-                    }
3151
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3152
-                        $model_query_info_carrier, $query_param_type);
3153
-                }
3154
-            }
3155
-        }
3156
-        return $model_query_info_carrier;
3157
-    }
3158
-
3159
-
3160
-
3161
-    /**
3162
-     * For extracting related models from forced_joins, where the array values contain the info about what
3163
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3164
-     *
3165
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3166
-     *                                                      $query_params['having']
3167
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3168
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3169
-     * @throws EE_Error
3170
-     * @return \EE_Model_Query_Info_Carrier
3171
-     */
3172
-    private function _extract_related_models_from_sub_params_array_values(
3173
-        $sub_query_params,
3174
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3175
-        $query_param_type
3176
-    ) {
3177
-        if (! empty($sub_query_params)) {
3178
-            if (! is_array($sub_query_params)) {
3179
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3180
-                    $sub_query_params));
3181
-            }
3182
-            foreach ($sub_query_params as $param) {
3183
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3184
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3185
-                    $query_param_type);
3186
-            }
3187
-        }
3188
-        return $model_query_info_carrier;
3189
-    }
3190
-
3191
-
3192
-
3193
-    /**
3194
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3195
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3196
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3197
-     * but use them in a different order. Eg, we need to know what models we are querying
3198
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3199
-     * other models before we can finalize the where clause SQL.
3200
-     *
3201
-     * @param array $query_params
3202
-     * @throws EE_Error
3203
-     * @return EE_Model_Query_Info_Carrier
3204
-     */
3205
-    public function _create_model_query_info_carrier($query_params)
3206
-    {
3207
-        if (! is_array($query_params)) {
3208
-            EE_Error::doing_it_wrong(
3209
-                'EEM_Base::_create_model_query_info_carrier',
3210
-                sprintf(
3211
-                    __(
3212
-                        '$query_params should be an array, you passed a variable of type %s',
3213
-                        'event_espresso'
3214
-                    ),
3215
-                    gettype($query_params)
3216
-                ),
3217
-                '4.6.0'
3218
-            );
3219
-            $query_params = array();
3220
-        }
3221
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3222
-        //first check if we should alter the query to account for caps or not
3223
-        //because the caps might require us to do extra joins
3224
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3225
-            $query_params[0] = $where_query_params = array_replace_recursive(
3226
-                $where_query_params,
3227
-                $this->caps_where_conditions(
3228
-                    $query_params['caps']
3229
-                )
3230
-            );
3231
-        }
3232
-        $query_object = $this->_extract_related_models_from_query($query_params);
3233
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3234
-        foreach ($where_query_params as $key => $value) {
3235
-            if (is_int($key)) {
3236
-                throw new EE_Error(
3237
-                    sprintf(
3238
-                        __(
3239
-                            "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.",
3240
-                            "event_espresso"
3241
-                        ),
3242
-                        $key,
3243
-                        var_export($value, true),
3244
-                        var_export($query_params, true),
3245
-                        get_class($this)
3246
-                    )
3247
-                );
3248
-            }
3249
-        }
3250
-        if (
3251
-            array_key_exists('default_where_conditions', $query_params)
3252
-            && ! empty($query_params['default_where_conditions'])
3253
-        ) {
3254
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3255
-        } else {
3256
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3257
-        }
3258
-        $where_query_params = array_merge(
3259
-            $this->_get_default_where_conditions_for_models_in_query(
3260
-                $query_object,
3261
-                $use_default_where_conditions,
3262
-                $where_query_params
3263
-            ),
3264
-            $where_query_params
3265
-        );
3266
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3267
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3268
-        // So we need to setup a subquery and use that for the main join.
3269
-        // Note for now this only works on the primary table for the model.
3270
-        // So for instance, you could set the limit array like this:
3271
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3272
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3273
-            $query_object->set_main_model_join_sql(
3274
-                $this->_construct_limit_join_select(
3275
-                    $query_params['on_join_limit'][0],
3276
-                    $query_params['on_join_limit'][1]
3277
-                )
3278
-            );
3279
-        }
3280
-        //set limit
3281
-        if (array_key_exists('limit', $query_params)) {
3282
-            if (is_array($query_params['limit'])) {
3283
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3284
-                    $e = sprintf(
3285
-                        __(
3286
-                            "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)",
3287
-                            "event_espresso"
3288
-                        ),
3289
-                        http_build_query($query_params['limit'])
3290
-                    );
3291
-                    throw new EE_Error($e . "|" . $e);
3292
-                }
3293
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3294
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3295
-            } elseif (! empty ($query_params['limit'])) {
3296
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3297
-            }
3298
-        }
3299
-        //set order by
3300
-        if (array_key_exists('order_by', $query_params)) {
3301
-            if (is_array($query_params['order_by'])) {
3302
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3303
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3304
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3305
-                if (array_key_exists('order', $query_params)) {
3306
-                    throw new EE_Error(
3307
-                        sprintf(
3308
-                            __(
3309
-                                "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 ",
3310
-                                "event_espresso"
3311
-                            ),
3312
-                            get_class($this),
3313
-                            implode(", ", array_keys($query_params['order_by'])),
3314
-                            implode(", ", $query_params['order_by']),
3315
-                            $query_params['order']
3316
-                        )
3317
-                    );
3318
-                }
3319
-                $this->_extract_related_models_from_sub_params_array_keys(
3320
-                    $query_params['order_by'],
3321
-                    $query_object,
3322
-                    'order_by'
3323
-                );
3324
-                //assume it's an array of fields to order by
3325
-                $order_array = array();
3326
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3327
-                    $order = $this->_extract_order($order);
3328
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3329
-                }
3330
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3331
-            } elseif (! empty ($query_params['order_by'])) {
3332
-                $this->_extract_related_model_info_from_query_param(
3333
-                    $query_params['order_by'],
3334
-                    $query_object,
3335
-                    'order',
3336
-                    $query_params['order_by']
3337
-                );
3338
-                $order = isset($query_params['order'])
3339
-                    ? $this->_extract_order($query_params['order'])
3340
-                    : 'DESC';
3341
-                $query_object->set_order_by_sql(
3342
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3343
-                );
3344
-            }
3345
-        }
3346
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3347
-        if (! array_key_exists('order_by', $query_params)
3348
-            && array_key_exists('order', $query_params)
3349
-            && ! empty($query_params['order'])
3350
-        ) {
3351
-            $pk_field = $this->get_primary_key_field();
3352
-            $order = $this->_extract_order($query_params['order']);
3353
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3354
-        }
3355
-        //set group by
3356
-        if (array_key_exists('group_by', $query_params)) {
3357
-            if (is_array($query_params['group_by'])) {
3358
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3359
-                $group_by_array = array();
3360
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3361
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3362
-                }
3363
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3364
-            } elseif (! empty ($query_params['group_by'])) {
3365
-                $query_object->set_group_by_sql(
3366
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3367
-                );
3368
-            }
3369
-        }
3370
-        //set having
3371
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3372
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3373
-        }
3374
-        //now, just verify they didn't pass anything wack
3375
-        foreach ($query_params as $query_key => $query_value) {
3376
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3377
-                throw new EE_Error(
3378
-                    sprintf(
3379
-                        __(
3380
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3381
-                            'event_espresso'
3382
-                        ),
3383
-                        $query_key,
3384
-                        get_class($this),
3385
-                        //						print_r( $this->_allowed_query_params, TRUE )
3386
-                        implode(',', $this->_allowed_query_params)
3387
-                    )
3388
-                );
3389
-            }
3390
-        }
3391
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3392
-        if (empty($main_model_join_sql)) {
3393
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3394
-        }
3395
-        return $query_object;
3396
-    }
3397
-
3398
-
3399
-
3400
-    /**
3401
-     * Gets the where conditions that should be imposed on the query based on the
3402
-     * context (eg reading frontend, backend, edit or delete).
3403
-     *
3404
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3405
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3406
-     * @throws \EE_Error
3407
-     */
3408
-    public function caps_where_conditions($context = self::caps_read)
3409
-    {
3410
-        EEM_Base::verify_is_valid_cap_context($context);
3411
-        $cap_where_conditions = array();
3412
-        $cap_restrictions = $this->caps_missing($context);
3413
-        /**
3414
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3415
-         */
3416
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3417
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3418
-                $restriction_if_no_cap->get_default_where_conditions());
3419
-        }
3420
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3421
-            $cap_restrictions);
3422
-    }
3423
-
3424
-
3425
-
3426
-    /**
3427
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3428
-     * otherwise throws an exception
3429
-     *
3430
-     * @param string $should_be_order_string
3431
-     * @return string either ASC, asc, DESC or desc
3432
-     * @throws EE_Error
3433
-     */
3434
-    private function _extract_order($should_be_order_string)
3435
-    {
3436
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3437
-            return $should_be_order_string;
3438
-        } else {
3439
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3440
-                "event_espresso"), get_class($this), $should_be_order_string));
3441
-        }
3442
-    }
3443
-
3444
-
3445
-
3446
-    /**
3447
-     * Looks at all the models which are included in this query, and asks each
3448
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3449
-     * so they can be merged
3450
-     *
3451
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3452
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3453
-     *                                                                  'none' means NO default where conditions will
3454
-     *                                                                  be used AT ALL during this query.
3455
-     *                                                                  'other_models_only' means default where
3456
-     *                                                                  conditions from other models will be used, but
3457
-     *                                                                  not for this primary model. 'all', the default,
3458
-     *                                                                  means default where conditions will apply as
3459
-     *                                                                  normal
3460
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3461
-     * @throws EE_Error
3462
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3463
-     */
3464
-    private function _get_default_where_conditions_for_models_in_query(
3465
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3466
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3467
-        $where_query_params = array()
3468
-    ) {
3469
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3470
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3471
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3472
-                "event_espresso"), $use_default_where_conditions,
3473
-                implode(", ", $allowed_used_default_where_conditions_values)));
3474
-        }
3475
-        $universal_query_params = array();
3476
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3477
-            $universal_query_params = $this->_get_default_where_conditions();
3478
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3479
-            $universal_query_params = $this->_get_minimum_where_conditions();
3480
-        }
3481
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3482
-            $related_model = $this->get_related_model_obj($model_name);
3483
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3484
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3485
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3486
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3487
-            } else {
3488
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3489
-                continue;
3490
-            }
3491
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3492
-                $related_model_universal_where_params,
3493
-                $where_query_params,
3494
-                $related_model,
3495
-                $model_relation_path
3496
-            );
3497
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3498
-                $universal_query_params,
3499
-                $overrides
3500
-            );
3501
-        }
3502
-        return $universal_query_params;
3503
-    }
3504
-
3505
-
3506
-
3507
-    /**
3508
-     * Determines whether or not we should use default where conditions for the model in question
3509
-     * (this model, or other related models).
3510
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3511
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3512
-     * We should use default where conditions on related models when they requested to use default where conditions
3513
-     * on all models, or specifically just on other related models
3514
-     * @param      $default_where_conditions_value
3515
-     * @param bool $for_this_model false means this is for OTHER related models
3516
-     * @return bool
3517
-     */
3518
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3519
-    {
3520
-        return (
3521
-                   $for_this_model
3522
-                   && in_array(
3523
-                       $default_where_conditions_value,
3524
-                       array(
3525
-                           EEM_Base::default_where_conditions_all,
3526
-                           EEM_Base::default_where_conditions_this_only,
3527
-                           EEM_Base::default_where_conditions_minimum_others,
3528
-                       ),
3529
-                       true
3530
-                   )
3531
-               )
3532
-               || (
3533
-                   ! $for_this_model
3534
-                   && in_array(
3535
-                       $default_where_conditions_value,
3536
-                       array(
3537
-                           EEM_Base::default_where_conditions_all,
3538
-                           EEM_Base::default_where_conditions_others_only,
3539
-                       ),
3540
-                       true
3541
-                   )
3542
-               );
3543
-    }
3544
-
3545
-    /**
3546
-     * Determines whether or not we should use default minimum conditions for the model in question
3547
-     * (this model, or other related models).
3548
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3549
-     * where conditions.
3550
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3551
-     * on this model or others
3552
-     * @param      $default_where_conditions_value
3553
-     * @param bool $for_this_model false means this is for OTHER related models
3554
-     * @return bool
3555
-     */
3556
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3557
-    {
3558
-        return (
3559
-                   $for_this_model
3560
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3561
-               )
3562
-               || (
3563
-                   ! $for_this_model
3564
-                   && in_array(
3565
-                       $default_where_conditions_value,
3566
-                       array(
3567
-                           EEM_Base::default_where_conditions_minimum_others,
3568
-                           EEM_Base::default_where_conditions_minimum_all,
3569
-                       ),
3570
-                       true
3571
-                   )
3572
-               );
3573
-    }
3574
-
3575
-
3576
-    /**
3577
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3578
-     * then we also add a special where condition which allows for that model's primary key
3579
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3580
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3581
-     *
3582
-     * @param array    $default_where_conditions
3583
-     * @param array    $provided_where_conditions
3584
-     * @param EEM_Base $model
3585
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3586
-     * @return array like EEM_Base::get_all's $query_params[0]
3587
-     * @throws \EE_Error
3588
-     */
3589
-    private function _override_defaults_or_make_null_friendly(
3590
-        $default_where_conditions,
3591
-        $provided_where_conditions,
3592
-        $model,
3593
-        $model_relation_path
3594
-    ) {
3595
-        $null_friendly_where_conditions = array();
3596
-        $none_overridden = true;
3597
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3598
-        foreach ($default_where_conditions as $key => $val) {
3599
-            if (isset($provided_where_conditions[$key])) {
3600
-                $none_overridden = false;
3601
-            } else {
3602
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3603
-            }
3604
-        }
3605
-        if ($none_overridden && $default_where_conditions) {
3606
-            if ($model->has_primary_key_field()) {
3607
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3608
-                                                                                . "."
3609
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3610
-            }/*else{
31
+	//admin posty
32
+	//basic -> grants access to mine -> if they don't have it, select none
33
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
+	//*_published -> grants access to published -> if they dont have it, select non-published
36
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
38
+	//frontend posty
39
+	//by default has access to published
40
+	//basic -> grants access to mine that aren't published, and all published
41
+	//*_others ->grants access to others that aren't private, all mine
42
+	//*_private -> grants full access
43
+	//frontend non-posty
44
+	//like admin posty
45
+	//category-y
46
+	//assign -> grants access to join-table
47
+	//(delete, edit)
48
+	//payment-method-y
49
+	//for each registered payment method,
50
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
+	/**
52
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
55
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
+	 *
57
+	 * @var boolean
58
+	 */
59
+	private $_values_already_prepared_by_model_object = 0;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the data is just like form input that needs to have the model fields'
64
+	 * prepare_for_set and prepare_for_use_in_db called on it
65
+	 */
66
+	const not_prepared_by_model_object = 0;
67
+
68
+	/**
69
+	 * when $_values_already_prepared_by_model_object equals this, we
70
+	 * assume this value is coming from a model object and doesn't need to have
71
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
72
+	 */
73
+	const prepared_by_model_object = 1;
74
+
75
+	/**
76
+	 * when $_values_already_prepared_by_model_object equals this, we assume
77
+	 * the values are already to be used in the database (ie no processing is done
78
+	 * on them by the model's fields)
79
+	 */
80
+	const prepared_for_use_in_db = 2;
81
+
82
+
83
+	protected $singular_item = 'Item';
84
+
85
+	protected $plural_item   = 'Items';
86
+
87
+	/**
88
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
+	 */
90
+	protected $_tables;
91
+
92
+	/**
93
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
+	 *
97
+	 * @var \EE_Model_Field_Base[] $_fields
98
+	 */
99
+	protected $_fields;
100
+
101
+	/**
102
+	 * array of different kinds of relations
103
+	 *
104
+	 * @var \EE_Model_Relation_Base[] $_model_relations
105
+	 */
106
+	protected $_model_relations;
107
+
108
+	/**
109
+	 * @var \EE_Index[] $_indexes
110
+	 */
111
+	protected $_indexes = array();
112
+
113
+	/**
114
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
115
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
+	 * by setting the same columns as used in these queries in the query yourself.
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_default_where_conditions_strategy;
121
+
122
+	/**
123
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
+	 * This is particularly useful when you want something between 'none' and 'default'
125
+	 *
126
+	 * @var EE_Default_Where_Conditions
127
+	 */
128
+	protected $_minimum_where_conditions_strategy;
129
+
130
+	/**
131
+	 * String describing how to find the "owner" of this model's objects.
132
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
+	 * But when there isn't, this indicates which related model, or transiently-related model,
134
+	 * has the foreign key to the wp_users table.
135
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
+	 * related to events, and events have a foreign key to wp_users.
137
+	 * On EEM_Transaction, this would be 'Transaction.Event'
138
+	 *
139
+	 * @var string
140
+	 */
141
+	protected $_model_chain_to_wp_user = '';
142
+
143
+	/**
144
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
+	 * don't need it (particularly CPT models)
146
+	 *
147
+	 * @var bool
148
+	 */
149
+	protected $_ignore_where_strategy = false;
150
+
151
+	/**
152
+	 * String used in caps relating to this model. Eg, if the caps relating to this
153
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
+	 *
155
+	 * @var string. If null it hasn't been initialized yet. If false then we
156
+	 * have indicated capabilities don't apply to this
157
+	 */
158
+	protected $_caps_slug = null;
159
+
160
+	/**
161
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
+	 * and next-level keys are capability names, and each's value is a
163
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
165
+	 * and then each capability in the corresponding sub-array that they're missing
166
+	 * adds the where conditions onto the query.
167
+	 *
168
+	 * @var array
169
+	 */
170
+	protected $_cap_restrictions = array(
171
+		self::caps_read       => array(),
172
+		self::caps_read_admin => array(),
173
+		self::caps_edit       => array(),
174
+		self::caps_delete     => array(),
175
+	);
176
+
177
+	/**
178
+	 * Array defining which cap restriction generators to use to create default
179
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
180
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
+	 * automatically set this to false (not just null).
183
+	 *
184
+	 * @var EE_Restriction_Generator_Base[]
185
+	 */
186
+	protected $_cap_restriction_generators = array();
187
+
188
+	/**
189
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
+	 */
191
+	const caps_read       = 'read';
192
+
193
+	const caps_read_admin = 'read_admin';
194
+
195
+	const caps_edit       = 'edit';
196
+
197
+	const caps_delete     = 'delete';
198
+
199
+	/**
200
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
+	 * maps to 'read' because when looking for relevant permissions we're going to use
203
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
204
+	 *
205
+	 * @var array
206
+	 */
207
+	protected $_cap_contexts_to_cap_action_map = array(
208
+		self::caps_read       => 'read',
209
+		self::caps_read_admin => 'read',
210
+		self::caps_edit       => 'edit',
211
+		self::caps_delete     => 'delete',
212
+	);
213
+
214
+	/**
215
+	 * Timezone
216
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
+	 * EE_Datetime_Field data type will have access to it.
220
+	 *
221
+	 * @var string
222
+	 */
223
+	protected $_timezone;
224
+
225
+
226
+	/**
227
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
+	 * multisite.
229
+	 *
230
+	 * @var int
231
+	 */
232
+	protected static $_model_query_blog_id;
233
+
234
+	/**
235
+	 * A copy of _fields, except the array keys are the model names pointed to by
236
+	 * the field
237
+	 *
238
+	 * @var EE_Model_Field_Base[]
239
+	 */
240
+	private $_cache_foreign_key_to_fields = array();
241
+
242
+	/**
243
+	 * Cached list of all the fields on the model, indexed by their name
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cached_fields = null;
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, except those that are
251
+	 * marked as only pertinent to the database
252
+	 *
253
+	 * @var EE_Model_Field_Base[]
254
+	 */
255
+	private $_cached_fields_non_db_only = null;
256
+
257
+	/**
258
+	 * A cached reference to the primary key for quick lookup
259
+	 *
260
+	 * @var EE_Model_Field_Base
261
+	 */
262
+	private $_primary_key_field = null;
263
+
264
+	/**
265
+	 * Flag indicating whether this model has a primary key or not
266
+	 *
267
+	 * @var boolean
268
+	 */
269
+	protected $_has_primary_key_field = null;
270
+
271
+	/**
272
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
273
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
+	 *
275
+	 * @var boolean
276
+	 */
277
+	protected $_wp_core_model = false;
278
+
279
+	/**
280
+	 *    List of valid operators that can be used for querying.
281
+	 * The keys are all operators we'll accept, the values are the real SQL
282
+	 * operators used
283
+	 *
284
+	 * @var array
285
+	 */
286
+	protected $_valid_operators = array(
287
+		'='           => '=',
288
+		'<='          => '<=',
289
+		'<'           => '<',
290
+		'>='          => '>=',
291
+		'>'           => '>',
292
+		'!='          => '!=',
293
+		'LIKE'        => 'LIKE',
294
+		'like'        => 'LIKE',
295
+		'NOT_LIKE'    => 'NOT LIKE',
296
+		'not_like'    => 'NOT LIKE',
297
+		'NOT LIKE'    => 'NOT LIKE',
298
+		'not like'    => 'NOT LIKE',
299
+		'IN'          => 'IN',
300
+		'in'          => 'IN',
301
+		'NOT_IN'      => 'NOT IN',
302
+		'not_in'      => 'NOT IN',
303
+		'NOT IN'      => 'NOT IN',
304
+		'not in'      => 'NOT IN',
305
+		'between'     => 'BETWEEN',
306
+		'BETWEEN'     => 'BETWEEN',
307
+		'IS_NOT_NULL' => 'IS NOT NULL',
308
+		'is_not_null' => 'IS NOT NULL',
309
+		'IS NOT NULL' => 'IS NOT NULL',
310
+		'is not null' => 'IS NOT NULL',
311
+		'IS_NULL'     => 'IS NULL',
312
+		'is_null'     => 'IS NULL',
313
+		'IS NULL'     => 'IS NULL',
314
+		'is null'     => 'IS NULL',
315
+		'REGEXP'      => 'REGEXP',
316
+		'regexp'      => 'REGEXP',
317
+		'NOT_REGEXP'  => 'NOT REGEXP',
318
+		'not_regexp'  => 'NOT REGEXP',
319
+		'NOT REGEXP'  => 'NOT REGEXP',
320
+		'not regexp'  => 'NOT REGEXP',
321
+	);
322
+
323
+	/**
324
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
+	 *
326
+	 * @var array
327
+	 */
328
+	protected $_in_style_operators = array('IN', 'NOT IN');
329
+
330
+	/**
331
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
+	 * '12-31-2012'"
333
+	 *
334
+	 * @var array
335
+	 */
336
+	protected $_between_style_operators = array('BETWEEN');
337
+
338
+	/**
339
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
+	 * on a join table.
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
+
346
+	/**
347
+	 * Allowed values for $query_params['order'] for ordering in queries
348
+	 *
349
+	 * @var array
350
+	 */
351
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
+
353
+	/**
354
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
356
+	 *
357
+	 * @var array
358
+	 */
359
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
+
361
+	/**
362
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
364
+	 *
365
+	 * @var array
366
+	 */
367
+	private $_allowed_query_params = array(
368
+		0,
369
+		'limit',
370
+		'order_by',
371
+		'group_by',
372
+		'having',
373
+		'force_join',
374
+		'order',
375
+		'on_join_limit',
376
+		'default_where_conditions',
377
+		'caps',
378
+	);
379
+
380
+	/**
381
+	 * All the data types that can be used in $wpdb->prepare statements.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
+
387
+	/**
388
+	 *    EE_Registry Object
389
+	 *
390
+	 * @var    object
391
+	 * @access    protected
392
+	 */
393
+	protected $EE = null;
394
+
395
+
396
+	/**
397
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
+	 *
399
+	 * @var int
400
+	 */
401
+	protected $_show_next_x_db_queries = 0;
402
+
403
+	/**
404
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
+	 *
407
+	 * @var array
408
+	 */
409
+	protected $_custom_selections = array();
410
+
411
+	/**
412
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
+	 * caches every model object we've fetched from the DB on this request
414
+	 *
415
+	 * @var array
416
+	 */
417
+	protected $_entity_map;
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws \EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Generates the cap restrictions for the given context, or if they were
654
+	 * already generated just gets what's cached
655
+	 *
656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
657
+	 * @return EE_Default_Where_Conditions[]
658
+	 */
659
+	protected function _generate_cap_restrictions($context)
660
+	{
661
+		if (isset($this->_cap_restriction_generators[$context])
662
+			&& $this->_cap_restriction_generators[$context]
663
+			   instanceof
664
+			   EE_Restriction_Generator_Base
665
+		) {
666
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
+		} else {
668
+			return array();
669
+		}
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Used to set the $_model_query_blog_id static property.
676
+	 *
677
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
+	 *                      value for get_current_blog_id() will be used.
679
+	 */
680
+	public static function set_model_query_blog_id($blog_id = 0)
681
+	{
682
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 * Returns whatever is set as the internal $model_query_blog_id.
689
+	 *
690
+	 * @return int
691
+	 */
692
+	public static function get_model_query_blog_id()
693
+	{
694
+		return EEM_Base::$_model_query_blog_id;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *        This function is a singleton method used to instantiate the Espresso_model object
701
+	 *
702
+	 * @access public
703
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
+	 *                         timezone in the 'timezone_string' wp option)
707
+	 * @return static (as in the concrete child class)
708
+	 */
709
+	public static function instance($timezone = null)
710
+	{
711
+		// check if instance of Espresso_model already exists
712
+		if (! static::$_instance instanceof static) {
713
+			// instantiate Espresso_model
714
+			static::$_instance = new static($timezone);
715
+		}
716
+		//we might have a timezone set, let set_timezone decide what to do with it
717
+		static::$_instance->set_timezone($timezone);
718
+		// Espresso_model object
719
+		return static::$_instance;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * resets the model and returns it
726
+	 *
727
+	 * @param null | string $timezone
728
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
+	 * all its properties reset; if it wasn't instantiated, returns null)
730
+	 */
731
+	public static function reset($timezone = null)
732
+	{
733
+		if (static::$_instance instanceof EEM_Base) {
734
+			//let's try to NOT swap out the current instance for a new one
735
+			//because if someone has a reference to it, we can't remove their reference
736
+			//so it's best to keep using the same reference, but change the original object
737
+			//reset all its properties to their original values as defined in the class
738
+			$r = new ReflectionClass(get_class(static::$_instance));
739
+			$static_properties = $r->getStaticProperties();
740
+			foreach ($r->getDefaultProperties() as $property => $value) {
741
+				//don't set instance to null like it was originally,
742
+				//but it's static anyways, and we're ignoring static properties (for now at least)
743
+				if (! isset($static_properties[$property])) {
744
+					static::$_instance->{$property} = $value;
745
+				}
746
+			}
747
+			//and then directly call its constructor again, like we would if we
748
+			//were creating a new one
749
+			static::$_instance->__construct($timezone);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
+	 *
760
+	 * @param  boolean $translated return localized strings or JUST the array.
761
+	 * @return array
762
+	 * @throws \EE_Error
763
+	 */
764
+	public function status_array($translated = false)
765
+	{
766
+		if (! array_key_exists('Status', $this->_model_relations)) {
767
+			return array();
768
+		}
769
+		$model_name = $this->get_this_model_name();
770
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
+		$status_array = array();
773
+		foreach ($stati as $status) {
774
+			$status_array[$status->ID()] = $status->get('STS_code');
775
+		}
776
+		return $translated
777
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
+			: $status_array;
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
+	 *
786
+	 * @param array $query_params             {
787
+	 * @var array $0 (where) array {
788
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
+	 *                                        conditions based on related models (and even
792
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
793
+	 *                                        name. Eg,
794
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
+	 *                                        to Venues (even when each of those models actually consisted of two
802
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
803
+	 *                                        just having
804
+	 *                                        "Venue.VNU_ID", you could have
805
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
+	 *                                        events are related to Registrations, which are related to Attendees). You
807
+	 *                                        can take it even further with
808
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
+	 *                                        (from the default of '='), change the value to an numerically-indexed
810
+	 *                                        array, where the first item in the list is the operator. eg: array(
811
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
819
+	 *                                        the value is a field, simply provide a third array item (true) to the
820
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
+	 *                                        Note: you can also use related model field names like you would any other
823
+	 *                                        field name. eg:
824
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
826
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
833
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
+	 *                                        "stick" until you specify an AND. eg
835
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
840
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
+	 *                                        too, eg:
843
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
848
+	 *                                        the OFFSET, the 2nd is the LIMIT
849
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
+	 *                                        following format array('on_join_limit'
852
+	 *                                        => array( 'table_alias', array(1,2) ) ).
853
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
+	 *                                        values are either 'ASC' or 'DESC'.
855
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
+	 *                                        DESC..." respectively. Like the
858
+	 *                                        'where' conditions, these fields can be on related models. Eg
859
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
861
+	 *                                        Attendee, Price, Datetime, etc.)
862
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
864
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
+	 *                                        order by the primary key. Eg,
867
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
869
+	 *                                        DTT_EVT_start) or
870
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
+	 *                                        'group_by'=>'VNU_ID', or
874
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
+	 *                                        if no
876
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
877
+	 *                                        model's primary key (or combined primary keys). This avoids some
878
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
879
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
+	 *                                        results)
883
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
+	 *                                        array where values are models to be joined in the query.Eg
885
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
887
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
888
+	 *                                        related models which belongs to the current model
889
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
890
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
891
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
894
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
896
+	 *                                        this model's default where conditions added to the query, use
897
+	 *                                        'this_model_only'. If you want to use all default where conditions
898
+	 *                                        (default), set to 'all'.
899
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
+	 *                                        everything? Or should we only show the current user items they should be
902
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
+	 *                                        }
905
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
+	 *                                        array( array(
911
+	 *                                        'OR'=>array(
912
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
+	 *                                        )
915
+	 *                                        ),
916
+	 *                                        'limit'=>10,
917
+	 *                                        'group_by'=>'TXN_ID'
918
+	 *                                        ));
919
+	 *                                        get all the answers to the question titled "shirt size" for event with id
920
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
+	 *                                        'Question.QST_display_text'=>'shirt size',
922
+	 *                                        'Registration.Event.EVT_ID'=>12
923
+	 *                                        ),
924
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
925
+	 *                                        ));
926
+	 * @throws \EE_Error
927
+	 */
928
+	public function get_all($query_params = array())
929
+	{
930
+		if (isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Modifies the query parameters so we only get back model objects
942
+	 * that "belong" to the current user
943
+	 *
944
+	 * @param array $query_params @see EEM_Base::get_all()
945
+	 * @return array like EEM_Base::get_all
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = array())
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Returns the name of the field's name that points to the WP_User table
960
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
+	 * foreign key to the WP_User table)
962
+	 *
963
+	 * @return string|boolean string on success, boolean false when there is no
964
+	 * foreign key to the WP_User table
965
+	 */
966
+	public function wp_user_field_name()
967
+	{
968
+		try {
969
+			if (! empty($this->_model_chain_to_wp_user)) {
970
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
+				$last_model_name = end($models_to_follow_to_wp_users);
972
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+			} else {
975
+				$model_with_fk_to_wp_users = $this;
976
+				$model_chain_to_wp_user = '';
977
+			}
978
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+		} catch (EE_Error $e) {
981
+			return false;
982
+		}
983
+	}
984
+
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
+	 * like how registrations don't have a foreign key to wp_users, but the
1007
+	 * events they are for are), or is unrelated to wp users.
1008
+	 * generally available
1009
+	 *
1010
+	 * @return boolean
1011
+	 */
1012
+	public function is_owned()
1013
+	{
1014
+		if ($this->model_chain_to_wp_user()) {
1015
+			return true;
1016
+		} else {
1017
+			try {
1018
+				$this->get_foreign_key_to('WP_User');
1019
+				return true;
1020
+			} catch (EE_Error $e) {
1021
+				return false;
1022
+			}
1023
+		}
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws \EE_Error
1045
+	 */
1046
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		// remember the custom selections, if any, and type cast as array
1049
+		// (unless $columns_to_select is an object, then just set as an empty array)
1050
+		// Note: (array) 'some string' === array( 'some string' )
1051
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions = $columns_to_select !== null
1054
+			? $this->_construct_select_from_input($columns_to_select)
1055
+			: $this->_construct_default_select_sql($model_query_info);
1056
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1064
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
+	 * take care of joins, field preparation etc.
1066
+	 *
1067
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1071
+	 *                                  override this and set the select to "*", or a specific column name, like
1072
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
+	 *                                  the aliases used to refer to this selection, and values are to be
1075
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
+	 * @throws \EE_Error
1079
+	 */
1080
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
+	{
1082
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * For creating a custom select statement
1089
+	 *
1090
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
+	 *                                 SQL, and 1=>is the datatype
1093
+	 * @throws EE_Error
1094
+	 * @return string
1095
+	 */
1096
+	private function _construct_select_from_input($columns_to_select)
1097
+	{
1098
+		if (is_array($columns_to_select)) {
1099
+			$select_sql_array = array();
1100
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+					throw new EE_Error(
1103
+						sprintf(
1104
+							__(
1105
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
+								"event_espresso"
1107
+							),
1108
+							$selection_and_datatype,
1109
+							$alias
1110
+						)
1111
+					);
1112
+				}
1113
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+					throw new EE_Error(
1115
+						sprintf(
1116
+							__(
1117
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
+								"event_espresso"
1119
+							),
1120
+							$selection_and_datatype[1],
1121
+							$selection_and_datatype[0],
1122
+							$alias,
1123
+							implode(",", $this->_valid_wpdb_data_types)
1124
+						)
1125
+					);
1126
+				}
1127
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
+			}
1129
+			$columns_to_select_string = implode(", ", $select_sql_array);
1130
+		} else {
1131
+			$columns_to_select_string = $columns_to_select;
1132
+		}
1133
+		return $columns_to_select_string;
1134
+	}
1135
+
1136
+
1137
+
1138
+	/**
1139
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
+	 *
1141
+	 * @return string
1142
+	 * @throws \EE_Error
1143
+	 */
1144
+	public function primary_key_name()
1145
+	{
1146
+		return $this->get_primary_key_field()->get_name();
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
+	 * If there is no primary key on this model, $id is treated as primary key string
1154
+	 *
1155
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1156
+	 * @return EE_Base_Class
1157
+	 */
1158
+	public function get_one_by_ID($id)
1159
+	{
1160
+		if ($this->get_from_entity_map($id)) {
1161
+			return $this->get_from_entity_map($id);
1162
+		}
1163
+		return $this->get_one(
1164
+			$this->alter_query_params_to_restrict_by_ID(
1165
+				$id,
1166
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
+			)
1168
+		);
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Alters query parameters to only get items with this ID are returned.
1175
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
+	 * or could just be a simple primary key ID
1177
+	 *
1178
+	 * @param int   $id
1179
+	 * @param array $query_params
1180
+	 * @return array of normal query params, @see EEM_Base::get_all
1181
+	 * @throws \EE_Error
1182
+	 */
1183
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
+	{
1185
+		if (! isset($query_params[0])) {
1186
+			$query_params[0] = array();
1187
+		}
1188
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1189
+		if ($conditions_from_id === null) {
1190
+			$query_params[0][$this->primary_key_name()] = $id;
1191
+		} else {
1192
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1193
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
+		}
1195
+		return $query_params;
1196
+	}
1197
+
1198
+
1199
+
1200
+	/**
1201
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
+	 * array. If no item is found, null is returned.
1203
+	 *
1204
+	 * @param array $query_params like EEM_Base's $query_params variable.
1205
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
+	 * @throws \EE_Error
1207
+	 */
1208
+	public function get_one($query_params = array())
1209
+	{
1210
+		if (! is_array($query_params)) {
1211
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
+					gettype($query_params)), '4.6.0');
1214
+			$query_params = array();
1215
+		}
1216
+		$query_params['limit'] = 1;
1217
+		$items = $this->get_all($query_params);
1218
+		if (empty($items)) {
1219
+			return null;
1220
+		} else {
1221
+			return array_shift($items);
1222
+		}
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Returns the next x number of items in sequence from the given value as
1229
+	 * found in the database matching the given query conditions.
1230
+	 *
1231
+	 * @param mixed $current_field_value    Value used for the reference point.
1232
+	 * @param null  $field_to_order_by      What field is used for the
1233
+	 *                                      reference point.
1234
+	 * @param int   $limit                  How many to return.
1235
+	 * @param array $query_params           Extra conditions on the query.
1236
+	 * @param null  $columns_to_select      If left null, then an array of
1237
+	 *                                      EE_Base_Class objects is returned,
1238
+	 *                                      otherwise you can indicate just the
1239
+	 *                                      columns you want returned.
1240
+	 * @return EE_Base_Class[]|array
1241
+	 * @throws \EE_Error
1242
+	 */
1243
+	public function next_x(
1244
+		$current_field_value,
1245
+		$field_to_order_by = null,
1246
+		$limit = 1,
1247
+		$query_params = array(),
1248
+		$columns_to_select = null
1249
+	) {
1250
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
+			$columns_to_select);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the previous x number of items in sequence from the given value
1258
+	 * as found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws \EE_Error
1271
+	 */
1272
+	public function previous_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = array(),
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
+			$columns_to_select);
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * Returns the next item in sequence from the given value as found in the
1287
+	 * database matching the given query conditions.
1288
+	 *
1289
+	 * @param mixed $current_field_value    Value used for the reference point.
1290
+	 * @param null  $field_to_order_by      What field is used for the
1291
+	 *                                      reference point.
1292
+	 * @param array $query_params           Extra conditions on the query.
1293
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
+	 *                                      object is returned, otherwise you
1295
+	 *                                      can indicate just the columns you
1296
+	 *                                      want and a single array indexed by
1297
+	 *                                      the columns will be returned.
1298
+	 * @return EE_Base_Class|null|array()
1299
+	 * @throws \EE_Error
1300
+	 */
1301
+	public function next(
1302
+		$current_field_value,
1303
+		$field_to_order_by = null,
1304
+		$query_params = array(),
1305
+		$columns_to_select = null
1306
+	) {
1307
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
+			$columns_to_select);
1309
+		return empty($results) ? null : reset($results);
1310
+	}
1311
+
1312
+
1313
+
1314
+	/**
1315
+	 * Returns the previous item in sequence from the given value as found in
1316
+	 * the database matching the given query conditions.
1317
+	 *
1318
+	 * @param mixed $current_field_value    Value used for the reference point.
1319
+	 * @param null  $field_to_order_by      What field is used for the
1320
+	 *                                      reference point.
1321
+	 * @param array $query_params           Extra conditions on the query.
1322
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
+	 *                                      object is returned, otherwise you
1324
+	 *                                      can indicate just the columns you
1325
+	 *                                      want and a single array indexed by
1326
+	 *                                      the columns will be returned.
1327
+	 * @return EE_Base_Class|null|array()
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	public function previous(
1331
+		$current_field_value,
1332
+		$field_to_order_by = null,
1333
+		$query_params = array(),
1334
+		$columns_to_select = null
1335
+	) {
1336
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
+			$columns_to_select);
1338
+		return empty($results) ? null : reset($results);
1339
+	}
1340
+
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the a consecutive number of items in sequence from the given
1345
+	 * value as found in the database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed  $current_field_value   Value used for the reference point.
1348
+	 * @param string $operand               What operand is used for the sequence.
1349
+	 * @param string $field_to_order_by     What field is used for the reference point.
1350
+	 * @param int    $limit                 How many to return.
1351
+	 * @param array  $query_params          Extra conditions on the query.
1352
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
+	 *                                      otherwise you can indicate just the columns you want returned.
1354
+	 * @return EE_Base_Class[]|array
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	protected function _get_consecutive(
1358
+		$current_field_value,
1359
+		$operand = '>',
1360
+		$field_to_order_by = null,
1361
+		$limit = 1,
1362
+		$query_params = array(),
1363
+		$columns_to_select = null
1364
+	) {
1365
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
+		if (empty($field_to_order_by)) {
1367
+			if ($this->has_primary_key_field()) {
1368
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1369
+			} else {
1370
+				if (WP_DEBUG) {
1371
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1372
+						'event_espresso'));
1373
+				}
1374
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
+				return array();
1376
+			}
1377
+		}
1378
+		if (! is_array($query_params)) {
1379
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
+					gettype($query_params)), '4.6.0');
1382
+			$query_params = array();
1383
+		}
1384
+		//let's add the where query param for consecutive look up.
1385
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
+		$query_params['limit'] = $limit;
1387
+		//set direction
1388
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+		$query_params['order_by'] = $operand === '>'
1390
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
+		if (empty($columns_to_select)) {
1394
+			return $this->get_all($query_params);
1395
+		} else {
1396
+			//getting just the fields
1397
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
+		}
1399
+	}
1400
+
1401
+
1402
+
1403
+	/**
1404
+	 * This sets the _timezone property after model object has been instantiated.
1405
+	 *
1406
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+	 */
1408
+	public function set_timezone($timezone)
1409
+	{
1410
+		if ($timezone !== null) {
1411
+			$this->_timezone = $timezone;
1412
+		}
1413
+		//note we need to loop through relations and set the timezone on those objects as well.
1414
+		foreach ($this->_model_relations as $relation) {
1415
+			$relation->set_timezone($timezone);
1416
+		}
1417
+		//and finally we do the same for any datetime fields
1418
+		foreach ($this->_fields as $field) {
1419
+			if ($field instanceof EE_Datetime_Field) {
1420
+				$field->set_timezone($timezone);
1421
+			}
1422
+		}
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 * This just returns whatever is set for the current timezone.
1429
+	 *
1430
+	 * @access public
1431
+	 * @return string
1432
+	 */
1433
+	public function get_timezone()
1434
+	{
1435
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
+		if (empty($this->_timezone)) {
1437
+			foreach ($this->_fields as $field) {
1438
+				if ($field instanceof EE_Datetime_Field) {
1439
+					$this->set_timezone($field->get_timezone());
1440
+					break;
1441
+				}
1442
+			}
1443
+		}
1444
+		//if timezone STILL empty then return the default timezone for the site.
1445
+		if (empty($this->_timezone)) {
1446
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
+		}
1448
+		return $this->_timezone;
1449
+	}
1450
+
1451
+
1452
+
1453
+	/**
1454
+	 * This returns the date formats set for the given field name and also ensures that
1455
+	 * $this->_timezone property is set correctly.
1456
+	 *
1457
+	 * @since 4.6.x
1458
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1459
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
+	 * @return array formats in an array with the date format first, and the time format last.
1462
+	 */
1463
+	public function get_formats_for($field_name, $pretty = false)
1464
+	{
1465
+		$field_settings = $this->field_settings_for($field_name);
1466
+		//if not a valid EE_Datetime_Field then throw error
1467
+		if (! $field_settings instanceof EE_Datetime_Field) {
1468
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469
+				'event_espresso'), $field_name));
1470
+		}
1471
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
+		//the field.
1473
+		$this->_timezone = $field_settings->get_timezone();
1474
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
+	}
1476
+
1477
+
1478
+
1479
+	/**
1480
+	 * This returns the current time in a format setup for a query on this model.
1481
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
+	 * it will return:
1483
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
+	 *  NOW
1485
+	 *  - or a unix timestamp (equivalent to time())
1486
+	 *
1487
+	 * @since 4.6.x
1488
+	 * @param string $field_name       The field the current time is needed for.
1489
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1490
+	 *                                 formatted string matching the set format for the field in the set timezone will
1491
+	 *                                 be returned.
1492
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1493
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1494
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495
+	 *                                 exception is triggered.
1496
+	 */
1497
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1498
+	{
1499
+		$formats = $this->get_formats_for($field_name);
1500
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1501
+		if ($timestamp) {
1502
+			return $DateTime->format('U');
1503
+		}
1504
+		//not returning timestamp, so return formatted string in timezone.
1505
+		switch ($what) {
1506
+			case 'time' :
1507
+				return $DateTime->format($formats[1]);
1508
+				break;
1509
+			case 'date' :
1510
+				return $DateTime->format($formats[0]);
1511
+				break;
1512
+			default :
1513
+				return $DateTime->format(implode(' ', $formats));
1514
+				break;
1515
+		}
1516
+	}
1517
+
1518
+
1519
+
1520
+	/**
1521
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1522
+	 * for the model are.  Returns a DateTime object.
1523
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1524
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1525
+	 * ignored.
1526
+	 *
1527
+	 * @param string $field_name      The field being setup.
1528
+	 * @param string $timestring      The date time string being used.
1529
+	 * @param string $incoming_format The format for the time string.
1530
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1531
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1532
+	 *                                format is
1533
+	 *                                'U', this is ignored.
1534
+	 * @return DateTime
1535
+	 * @throws \EE_Error
1536
+	 */
1537
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1538
+	{
1539
+		//just using this to ensure the timezone is set correctly internally
1540
+		$this->get_formats_for($field_name);
1541
+		//load EEH_DTT_Helper
1542
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1543
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1544
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1545
+	}
1546
+
1547
+
1548
+
1549
+	/**
1550
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1551
+	 *
1552
+	 * @return EE_Table_Base[]
1553
+	 */
1554
+	public function get_tables()
1555
+	{
1556
+		return $this->_tables;
1557
+	}
1558
+
1559
+
1560
+
1561
+	/**
1562
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1563
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1564
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1565
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1566
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1567
+	 * model object with EVT_ID = 1
1568
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1569
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1570
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1571
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1572
+	 * are not specified)
1573
+	 *
1574
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1575
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1576
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1577
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1578
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1579
+	 *                                         ID=34, we'd use this method as follows:
1580
+	 *                                         EEM_Transaction::instance()->update(
1581
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1582
+	 *                                         array(array('TXN_ID'=>34)));
1583
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1584
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1585
+	 *                                         consider updating Question's QST_admin_label field is of type
1586
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1587
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1588
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1589
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1590
+	 *                                         TRUE, it is assumed that you've already called
1591
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1592
+	 *                                         malicious javascript. However, if
1593
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1594
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1595
+	 *                                         and every other field, before insertion. We provide this parameter
1596
+	 *                                         because model objects perform their prepare_for_set function on all
1597
+	 *                                         their values, and so don't need to be called again (and in many cases,
1598
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1599
+	 *                                         prepare_for_set method...)
1600
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1601
+	 *                                         in this model's entity map according to $fields_n_values that match
1602
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1603
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1604
+	 *                                         could get out-of-sync with the database
1605
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1606
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1607
+	 *                                         bad)
1608
+	 * @throws \EE_Error
1609
+	 */
1610
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1611
+	{
1612
+		if (! is_array($query_params)) {
1613
+			EE_Error::doing_it_wrong('EEM_Base::update',
1614
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1615
+					gettype($query_params)), '4.6.0');
1616
+			$query_params = array();
1617
+		}
1618
+		/**
1619
+		 * Action called before a model update call has been made.
1620
+		 *
1621
+		 * @param EEM_Base $model
1622
+		 * @param array    $fields_n_values the updated fields and their new values
1623
+		 * @param array    $query_params    @see EEM_Base::get_all()
1624
+		 */
1625
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1626
+		/**
1627
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1628
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1629
+		 *
1630
+		 * @param array    $fields_n_values fields and their new values
1631
+		 * @param EEM_Base $model           the model being queried
1632
+		 * @param array    $query_params    see EEM_Base::get_all()
1633
+		 */
1634
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1635
+			$query_params);
1636
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1637
+		//to do that, for each table, verify that it's PK isn't null.
1638
+		$tables = $this->get_tables();
1639
+		//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
1640
+		//NOTE: we should make this code more efficient by NOT querying twice
1641
+		//before the real update, but that needs to first go through ALPHA testing
1642
+		//as it's dangerous. says Mike August 8 2014
1643
+		//we want to make sure the default_where strategy is ignored
1644
+		$this->_ignore_where_strategy = true;
1645
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1646
+		foreach ($wpdb_select_results as $wpdb_result) {
1647
+			// type cast stdClass as array
1648
+			$wpdb_result = (array)$wpdb_result;
1649
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1650
+			if ($this->has_primary_key_field()) {
1651
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1652
+			} else {
1653
+				//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)
1654
+				$main_table_pk_value = null;
1655
+			}
1656
+			//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
1657
+			//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
1658
+			if (count($tables) > 1) {
1659
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1660
+				//in that table, and so we'll want to insert one
1661
+				foreach ($tables as $table_obj) {
1662
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1663
+					//if there is no private key for this table on the results, it means there's no entry
1664
+					//in this table, right? so insert a row in the current table, using any fields available
1665
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1666
+						   && $wpdb_result[$this_table_pk_column])
1667
+					) {
1668
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1669
+							$main_table_pk_value);
1670
+						//if we died here, report the error
1671
+						if (! $success) {
1672
+							return false;
1673
+						}
1674
+					}
1675
+				}
1676
+			}
1677
+			//				//and now check that if we have cached any models by that ID on the model, that
1678
+			//				//they also get updated properly
1679
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1680
+			//				if( $model_object ){
1681
+			//					foreach( $fields_n_values as $field => $value ){
1682
+			//						$model_object->set($field, $value);
1683
+			//let's make sure default_where strategy is followed now
1684
+			$this->_ignore_where_strategy = false;
1685
+		}
1686
+		//if we want to keep model objects in sync, AND
1687
+		//if this wasn't called from a model object (to update itself)
1688
+		//then we want to make sure we keep all the existing
1689
+		//model objects in sync with the db
1690
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1691
+			if ($this->has_primary_key_field()) {
1692
+				$model_objs_affected_ids = $this->get_col($query_params);
1693
+			} else {
1694
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1695
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1696
+				$model_objs_affected_ids = array();
1697
+				foreach ($models_affected_key_columns as $row) {
1698
+					$combined_index_key = $this->get_index_primary_key_string($row);
1699
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1700
+				}
1701
+			}
1702
+			if (! $model_objs_affected_ids) {
1703
+				//wait wait wait- if nothing was affected let's stop here
1704
+				return 0;
1705
+			}
1706
+			foreach ($model_objs_affected_ids as $id) {
1707
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1708
+				if ($model_obj_in_entity_map) {
1709
+					foreach ($fields_n_values as $field => $new_value) {
1710
+						$model_obj_in_entity_map->set($field, $new_value);
1711
+					}
1712
+				}
1713
+			}
1714
+			//if there is a primary key on this model, we can now do a slight optimization
1715
+			if ($this->has_primary_key_field()) {
1716
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1717
+				$query_params = array(
1718
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1719
+					'limit'                    => count($model_objs_affected_ids),
1720
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1721
+				);
1722
+			}
1723
+		}
1724
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1725
+		$SQL = "UPDATE "
1726
+			   . $model_query_info->get_full_join_sql()
1727
+			   . " SET "
1728
+			   . $this->_construct_update_sql($fields_n_values)
1729
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1730
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1731
+		/**
1732
+		 * Action called after a model update call has been made.
1733
+		 *
1734
+		 * @param EEM_Base $model
1735
+		 * @param array    $fields_n_values the updated fields and their new values
1736
+		 * @param array    $query_params    @see EEM_Base::get_all()
1737
+		 * @param int      $rows_affected
1738
+		 */
1739
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1740
+		return $rows_affected;//how many supposedly got updated
1741
+	}
1742
+
1743
+
1744
+
1745
+	/**
1746
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1747
+	 * are teh values of the field specified (or by default the primary key field)
1748
+	 * that matched the query params. Note that you should pass the name of the
1749
+	 * model FIELD, not the database table's column name.
1750
+	 *
1751
+	 * @param array  $query_params @see EEM_Base::get_all()
1752
+	 * @param string $field_to_select
1753
+	 * @return array just like $wpdb->get_col()
1754
+	 * @throws \EE_Error
1755
+	 */
1756
+	public function get_col($query_params = array(), $field_to_select = null)
1757
+	{
1758
+		if ($field_to_select) {
1759
+			$field = $this->field_settings_for($field_to_select);
1760
+		} elseif ($this->has_primary_key_field()) {
1761
+			$field = $this->get_primary_key_field();
1762
+		} else {
1763
+			//no primary key, just grab the first column
1764
+			$field = reset($this->field_settings());
1765
+		}
1766
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1767
+		$select_expressions = $field->get_qualified_column();
1768
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1769
+		return $this->_do_wpdb_query('get_col', array($SQL));
1770
+	}
1771
+
1772
+
1773
+
1774
+	/**
1775
+	 * Returns a single column value for a single row from the database
1776
+	 *
1777
+	 * @param array  $query_params    @see EEM_Base::get_all()
1778
+	 * @param string $field_to_select @see EEM_Base::get_col()
1779
+	 * @return string
1780
+	 * @throws \EE_Error
1781
+	 */
1782
+	public function get_var($query_params = array(), $field_to_select = null)
1783
+	{
1784
+		$query_params['limit'] = 1;
1785
+		$col = $this->get_col($query_params, $field_to_select);
1786
+		if (! empty($col)) {
1787
+			return reset($col);
1788
+		} else {
1789
+			return null;
1790
+		}
1791
+	}
1792
+
1793
+
1794
+
1795
+	/**
1796
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1797
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1798
+	 * injection, but currently no further filtering is done
1799
+	 *
1800
+	 * @global      $wpdb
1801
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1802
+	 *                               be updated to in the DB
1803
+	 * @return string of SQL
1804
+	 * @throws \EE_Error
1805
+	 */
1806
+	public function _construct_update_sql($fields_n_values)
1807
+	{
1808
+		/** @type WPDB $wpdb */
1809
+		global $wpdb;
1810
+		$cols_n_values = array();
1811
+		foreach ($fields_n_values as $field_name => $value) {
1812
+			$field_obj = $this->field_settings_for($field_name);
1813
+			//if the value is NULL, we want to assign the value to that.
1814
+			//wpdb->prepare doesn't really handle that properly
1815
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1816
+			$value_sql = $prepared_value === null ? 'NULL'
1817
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1818
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1819
+		}
1820
+		return implode(",", $cols_n_values);
1821
+	}
1822
+
1823
+
1824
+
1825
+	/**
1826
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1827
+	 * Performs a HARD delete, meaning the database row should always be removed,
1828
+	 * not just have a flag field on it switched
1829
+	 * Wrapper for EEM_Base::delete_permanently()
1830
+	 *
1831
+	 * @param mixed $id
1832
+	 * @return boolean whether the row got deleted or not
1833
+	 * @throws \EE_Error
1834
+	 */
1835
+	public function delete_permanently_by_ID($id)
1836
+	{
1837
+		return $this->delete_permanently(
1838
+			array(
1839
+				array($this->get_primary_key_field()->get_name() => $id),
1840
+				'limit' => 1,
1841
+			)
1842
+		);
1843
+	}
1844
+
1845
+
1846
+
1847
+	/**
1848
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
+	 * Wrapper for EEM_Base::delete()
1850
+	 *
1851
+	 * @param mixed $id
1852
+	 * @return boolean whether the row got deleted or not
1853
+	 * @throws \EE_Error
1854
+	 */
1855
+	public function delete_by_ID($id)
1856
+	{
1857
+		return $this->delete(
1858
+			array(
1859
+				array($this->get_primary_key_field()->get_name() => $id),
1860
+				'limit' => 1,
1861
+			)
1862
+		);
1863
+	}
1864
+
1865
+
1866
+
1867
+	/**
1868
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1869
+	 * meaning if the model has a field that indicates its been "trashed" or
1870
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1871
+	 *
1872
+	 * @see EEM_Base::delete_permanently
1873
+	 * @param array   $query_params
1874
+	 * @param boolean $allow_blocking
1875
+	 * @return int how many rows got deleted
1876
+	 * @throws \EE_Error
1877
+	 */
1878
+	public function delete($query_params, $allow_blocking = true)
1879
+	{
1880
+		return $this->delete_permanently($query_params, $allow_blocking);
1881
+	}
1882
+
1883
+
1884
+
1885
+	/**
1886
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1887
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1888
+	 * as archived, not actually deleted
1889
+	 *
1890
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1891
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1892
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1893
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1894
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1895
+	 *                                DB
1896
+	 * @return int how many rows got deleted
1897
+	 * @throws \EE_Error
1898
+	 */
1899
+	public function delete_permanently($query_params, $allow_blocking = true)
1900
+	{
1901
+		/**
1902
+		 * Action called just before performing a real deletion query. You can use the
1903
+		 * model and its $query_params to find exactly which items will be deleted
1904
+		 *
1905
+		 * @param EEM_Base $model
1906
+		 * @param array    $query_params   @see EEM_Base::get_all()
1907
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1908
+		 *                                 to block (prevent) this deletion
1909
+		 */
1910
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1911
+		//some MySQL databases may be running safe mode, which may restrict
1912
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1913
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1914
+		//to delete them
1915
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1916
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1917
+		if ($deletion_where) {
1918
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1919
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1920
+			$table_aliases = array_keys($this->_tables);
1921
+			$SQL = "DELETE "
1922
+				   . implode(", ", $table_aliases)
1923
+				   . " FROM "
1924
+				   . $model_query_info->get_full_join_sql()
1925
+				   . " WHERE "
1926
+				   . $deletion_where;
1927
+			//		/echo "delete sql:$SQL";
1928
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1929
+		} else {
1930
+			$rows_deleted = 0;
1931
+		}
1932
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1933
+		if ($this->has_primary_key_field()) {
1934
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1935
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1936
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1937
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1938
+				}
1939
+			}
1940
+		}
1941
+		/**
1942
+		 * Action called just after performing a real deletion query. Although at this point the
1943
+		 * items should have been deleted
1944
+		 *
1945
+		 * @param EEM_Base $model
1946
+		 * @param array    $query_params @see EEM_Base::get_all()
1947
+		 * @param int      $rows_deleted
1948
+		 */
1949
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1950
+		return $rows_deleted;//how many supposedly got deleted
1951
+	}
1952
+
1953
+
1954
+
1955
+	/**
1956
+	 * Checks all the relations that throw error messages when there are blocking related objects
1957
+	 * for related model objects. If there are any related model objects on those relations,
1958
+	 * adds an EE_Error, and return true
1959
+	 *
1960
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1961
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1962
+	 *                                                 should be ignored when determining whether there are related
1963
+	 *                                                 model objects which block this model object's deletion. Useful
1964
+	 *                                                 if you know A is related to B and are considering deleting A,
1965
+	 *                                                 but want to see if A has any other objects blocking its deletion
1966
+	 *                                                 before removing the relation between A and B
1967
+	 * @return boolean
1968
+	 * @throws \EE_Error
1969
+	 */
1970
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1971
+	{
1972
+		//first, if $ignore_this_model_obj was supplied, get its model
1973
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1974
+			$ignored_model = $ignore_this_model_obj->get_model();
1975
+		} else {
1976
+			$ignored_model = null;
1977
+		}
1978
+		//now check all the relations of $this_model_obj_or_id and see if there
1979
+		//are any related model objects blocking it?
1980
+		$is_blocked = false;
1981
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1982
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1983
+				//if $ignore_this_model_obj was supplied, then for the query
1984
+				//on that model needs to be told to ignore $ignore_this_model_obj
1985
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1986
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1987
+						array(
1988
+							$ignored_model->get_primary_key_field()->get_name() => array(
1989
+								'!=',
1990
+								$ignore_this_model_obj->ID(),
1991
+							),
1992
+						),
1993
+					));
1994
+				} else {
1995
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1996
+				}
1997
+				if ($related_model_objects) {
1998
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1999
+					$is_blocked = true;
2000
+				}
2001
+			}
2002
+		}
2003
+		return $is_blocked;
2004
+	}
2005
+
2006
+
2007
+
2008
+	/**
2009
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2010
+	 * well.
2011
+	 *
2012
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2013
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2014
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2015
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2016
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2017
+	 *                                      easily corrupt your DB
2018
+	 * @throws EE_Error
2019
+	 * @return string    everything that comes after the WHERE statement.
2020
+	 */
2021
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2022
+	{
2023
+		if ($this->has_primary_key_field()) {
2024
+			$primary_table = $this->_get_main_table();
2025
+			$other_tables = $this->_get_other_tables();
2026
+			$deletes = $query = array();
2027
+			foreach ($objects_for_deletion as $delete_object) {
2028
+				//before we mark this object for deletion,
2029
+				//make sure there's no related objects blocking its deletion (if we're checking)
2030
+				if (
2031
+					$allow_blocking
2032
+					&& $this->delete_is_blocked_by_related_models(
2033
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2034
+					)
2035
+				) {
2036
+					continue;
2037
+				}
2038
+				//primary table deletes
2039
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2040
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2041
+				}
2042
+				//other tables
2043
+				if (! empty($other_tables)) {
2044
+					foreach ($other_tables as $ot) {
2045
+						//first check if we've got the foreign key column here.
2046
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2047
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2048
+						}
2049
+						// wait! it's entirely possible that we'll have a the primary key
2050
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2051
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2052
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2053
+						}
2054
+						// finally, it is possible that the fk for this table is found
2055
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2056
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2057
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2058
+						}
2059
+					}
2060
+				}
2061
+			}
2062
+			//we should have deletes now, so let's just go through and setup the where statement
2063
+			foreach ($deletes as $column => $values) {
2064
+				//make sure we have unique $values;
2065
+				$values = array_unique($values);
2066
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
+			}
2068
+			return ! empty($query) ? implode(' AND ', $query) : '';
2069
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2070
+			$ways_to_identify_a_row = array();
2071
+			$fields = $this->get_combined_primary_key_fields();
2072
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2073
+			foreach ($objects_for_deletion as $delete_object) {
2074
+				$values_for_each_cpk_for_a_row = array();
2075
+				foreach ($fields as $cpk_field) {
2076
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2077
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2078
+														   . "="
2079
+														   . $delete_object[$cpk_field->get_qualified_column()];
2080
+					}
2081
+				}
2082
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2083
+			}
2084
+			return implode(" OR ", $ways_to_identify_a_row);
2085
+		} else {
2086
+			//so there's no primary key and no combined key...
2087
+			//sorry, can't help you
2088
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2089
+				"event_espresso"), get_class($this)));
2090
+		}
2091
+	}
2092
+
2093
+
2094
+
2095
+	/**
2096
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2097
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2098
+	 * column
2099
+	 *
2100
+	 * @param array  $query_params   like EEM_Base::get_all's
2101
+	 * @param string $field_to_count field on model to count by (not column name)
2102
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2103
+	 *                               that by the setting $distinct to TRUE;
2104
+	 * @return int
2105
+	 * @throws \EE_Error
2106
+	 */
2107
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2108
+	{
2109
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2110
+		if ($field_to_count) {
2111
+			$field_obj = $this->field_settings_for($field_to_count);
2112
+			$column_to_count = $field_obj->get_qualified_column();
2113
+		} elseif ($this->has_primary_key_field()) {
2114
+			$pk_field_obj = $this->get_primary_key_field();
2115
+			$column_to_count = $pk_field_obj->get_qualified_column();
2116
+		} else {
2117
+			//there's no primary key
2118
+			//if we're counting distinct items, and there's no primary key,
2119
+			//we need to list out the columns for distinction;
2120
+			//otherwise we can just use star
2121
+			if ($distinct) {
2122
+				$columns_to_use = array();
2123
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2124
+					$columns_to_use[] = $field_obj->get_qualified_column();
2125
+				}
2126
+				$column_to_count = implode(',', $columns_to_use);
2127
+			} else {
2128
+				$column_to_count = '*';
2129
+			}
2130
+		}
2131
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2132
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2133
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2134
+	}
2135
+
2136
+
2137
+
2138
+	/**
2139
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2140
+	 *
2141
+	 * @param array  $query_params like EEM_Base::get_all
2142
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2143
+	 * @return float
2144
+	 * @throws \EE_Error
2145
+	 */
2146
+	public function sum($query_params, $field_to_sum = null)
2147
+	{
2148
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2149
+		if ($field_to_sum) {
2150
+			$field_obj = $this->field_settings_for($field_to_sum);
2151
+		} else {
2152
+			$field_obj = $this->get_primary_key_field();
2153
+		}
2154
+		$column_to_count = $field_obj->get_qualified_column();
2155
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2157
+		$data_type = $field_obj->get_wpdb_data_type();
2158
+		if ($data_type === '%d' || $data_type === '%s') {
2159
+			return (float)$return_value;
2160
+		} else {//must be %f
2161
+			return (float)$return_value;
2162
+		}
2163
+	}
2164
+
2165
+
2166
+
2167
+	/**
2168
+	 * Just calls the specified method on $wpdb with the given arguments
2169
+	 * Consolidates a little extra error handling code
2170
+	 *
2171
+	 * @param string $wpdb_method
2172
+	 * @param array  $arguments_to_provide
2173
+	 * @throws EE_Error
2174
+	 * @global wpdb  $wpdb
2175
+	 * @return mixed
2176
+	 */
2177
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2178
+	{
2179
+		//if we're in maintenance mode level 2, DON'T run any queries
2180
+		//because level 2 indicates the database needs updating and
2181
+		//is probably out of sync with the code
2182
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2183
+			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2184
+				"event_espresso")));
2185
+		}
2186
+		/** @type WPDB $wpdb */
2187
+		global $wpdb;
2188
+		if (! method_exists($wpdb, $wpdb_method)) {
2189
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2190
+				'event_espresso'), $wpdb_method));
2191
+		}
2192
+		if (WP_DEBUG) {
2193
+			$old_show_errors_value = $wpdb->show_errors;
2194
+			$wpdb->show_errors(false);
2195
+		}
2196
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2197
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2198
+		if (WP_DEBUG) {
2199
+			$wpdb->show_errors($old_show_errors_value);
2200
+			if (! empty($wpdb->last_error)) {
2201
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2202
+			} elseif ($result === false) {
2203
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2204
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2205
+			}
2206
+		} elseif ($result === false) {
2207
+			EE_Error::add_error(
2208
+				sprintf(
2209
+					__('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"',
2210
+						'event_espresso'),
2211
+					$wpdb_method,
2212
+					var_export($arguments_to_provide, true),
2213
+					$wpdb->last_error
2214
+				),
2215
+				__FILE__,
2216
+				__FUNCTION__,
2217
+				__LINE__
2218
+			);
2219
+		}
2220
+		return $result;
2221
+	}
2222
+
2223
+
2224
+
2225
+	/**
2226
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2227
+	 * and if there's an error tries to verify the DB is correct. Uses
2228
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2229
+	 * we should try to fix the EE core db, the addons, or just give up
2230
+	 *
2231
+	 * @param string $wpdb_method
2232
+	 * @param array  $arguments_to_provide
2233
+	 * @return mixed
2234
+	 */
2235
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2236
+	{
2237
+		/** @type WPDB $wpdb */
2238
+		global $wpdb;
2239
+		$wpdb->last_error = null;
2240
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2241
+		// was there an error running the query? but we don't care on new activations
2242
+		// (we're going to setup the DB anyway on new activations)
2243
+		if (($result === false || ! empty($wpdb->last_error))
2244
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2245
+		) {
2246
+			switch (EEM_Base::$_db_verification_level) {
2247
+				case EEM_Base::db_verified_none :
2248
+					// let's double-check core's DB
2249
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2250
+					break;
2251
+				case EEM_Base::db_verified_core :
2252
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2253
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2254
+					break;
2255
+				case EEM_Base::db_verified_addons :
2256
+					// ummmm... you in trouble
2257
+					return $result;
2258
+					break;
2259
+			}
2260
+			if (! empty($error_message)) {
2261
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2262
+				trigger_error($error_message);
2263
+			}
2264
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2265
+		}
2266
+		return $result;
2267
+	}
2268
+
2269
+
2270
+
2271
+	/**
2272
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2273
+	 * EEM_Base::$_db_verification_level
2274
+	 *
2275
+	 * @param string $wpdb_method
2276
+	 * @param array  $arguments_to_provide
2277
+	 * @return string
2278
+	 */
2279
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2280
+	{
2281
+		/** @type WPDB $wpdb */
2282
+		global $wpdb;
2283
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2284
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2285
+		$error_message = sprintf(
2286
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2287
+				'event_espresso'),
2288
+			$wpdb->last_error,
2289
+			$wpdb_method,
2290
+			wp_json_encode($arguments_to_provide)
2291
+		);
2292
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2293
+		return $error_message;
2294
+	}
2295
+
2296
+
2297
+
2298
+	/**
2299
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2300
+	 * EEM_Base::$_db_verification_level
2301
+	 *
2302
+	 * @param $wpdb_method
2303
+	 * @param $arguments_to_provide
2304
+	 * @return string
2305
+	 */
2306
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2307
+	{
2308
+		/** @type WPDB $wpdb */
2309
+		global $wpdb;
2310
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2311
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2312
+		$error_message = sprintf(
2313
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2314
+				'event_espresso'),
2315
+			$wpdb->last_error,
2316
+			$wpdb_method,
2317
+			wp_json_encode($arguments_to_provide)
2318
+		);
2319
+		EE_System::instance()->initialize_addons();
2320
+		return $error_message;
2321
+	}
2322
+
2323
+
2324
+
2325
+	/**
2326
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2327
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2328
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2329
+	 * ..."
2330
+	 *
2331
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2332
+	 * @return string
2333
+	 */
2334
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2335
+	{
2336
+		return " FROM " . $model_query_info->get_full_join_sql() .
2337
+			   $model_query_info->get_where_sql() .
2338
+			   $model_query_info->get_group_by_sql() .
2339
+			   $model_query_info->get_having_sql() .
2340
+			   $model_query_info->get_order_by_sql() .
2341
+			   $model_query_info->get_limit_sql();
2342
+	}
2343
+
2344
+
2345
+
2346
+	/**
2347
+	 * Set to easily debug the next X queries ran from this model.
2348
+	 *
2349
+	 * @param int $count
2350
+	 */
2351
+	public function show_next_x_db_queries($count = 1)
2352
+	{
2353
+		$this->_show_next_x_db_queries = $count;
2354
+	}
2355
+
2356
+
2357
+
2358
+	/**
2359
+	 * @param $sql_query
2360
+	 */
2361
+	public function show_db_query_if_previously_requested($sql_query)
2362
+	{
2363
+		if ($this->_show_next_x_db_queries > 0) {
2364
+			echo $sql_query;
2365
+			$this->_show_next_x_db_queries--;
2366
+		}
2367
+	}
2368
+
2369
+
2370
+
2371
+	/**
2372
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2373
+	 * There are the 3 cases:
2374
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2375
+	 * $otherModelObject has no ID, it is first saved.
2376
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2377
+	 * has no ID, it is first saved.
2378
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2379
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2380
+	 * join table
2381
+	 *
2382
+	 * @param        EE_Base_Class                     /int $thisModelObject
2383
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2384
+	 * @param string $relationName                     , key in EEM_Base::_relations
2385
+	 *                                                 an attendee to a group, you also want to specify which role they
2386
+	 *                                                 will have in that group. So you would use this parameter to
2387
+	 *                                                 specify array('role-column-name'=>'role-id')
2388
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2389
+	 *                                                 to for relation to methods that allow you to further specify
2390
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2391
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2392
+	 *                                                 because these will be inserted in any new rows created as well.
2393
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2394
+	 * @throws \EE_Error
2395
+	 */
2396
+	public function add_relationship_to(
2397
+		$id_or_obj,
2398
+		$other_model_id_or_obj,
2399
+		$relationName,
2400
+		$extra_join_model_fields_n_values = array()
2401
+	) {
2402
+		$relation_obj = $this->related_settings_for($relationName);
2403
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2404
+	}
2405
+
2406
+
2407
+
2408
+	/**
2409
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2410
+	 * There are the 3 cases:
2411
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2412
+	 * error
2413
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2414
+	 * an error
2415
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2416
+	 *
2417
+	 * @param        EE_Base_Class /int $id_or_obj
2418
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2419
+	 * @param string $relationName key in EEM_Base::_relations
2420
+	 * @return boolean of success
2421
+	 * @throws \EE_Error
2422
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2423
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2424
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2425
+	 *                             because these will be inserted in any new rows created as well.
2426
+	 */
2427
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2428
+	{
2429
+		$relation_obj = $this->related_settings_for($relationName);
2430
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2431
+	}
2432
+
2433
+
2434
+
2435
+	/**
2436
+	 * @param mixed           $id_or_obj
2437
+	 * @param string          $relationName
2438
+	 * @param array           $where_query_params
2439
+	 * @param EE_Base_Class[] objects to which relations were removed
2440
+	 * @return \EE_Base_Class[]
2441
+	 * @throws \EE_Error
2442
+	 */
2443
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2444
+	{
2445
+		$relation_obj = $this->related_settings_for($relationName);
2446
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2447
+	}
2448
+
2449
+
2450
+
2451
+	/**
2452
+	 * Gets all the related items of the specified $model_name, using $query_params.
2453
+	 * Note: by default, we remove the "default query params"
2454
+	 * because we want to get even deleted items etc.
2455
+	 *
2456
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2457
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2458
+	 * @param array  $query_params like EEM_Base::get_all
2459
+	 * @return EE_Base_Class[]
2460
+	 * @throws \EE_Error
2461
+	 */
2462
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2463
+	{
2464
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2465
+		$relation_settings = $this->related_settings_for($model_name);
2466
+		return $relation_settings->get_all_related($model_obj, $query_params);
2467
+	}
2468
+
2469
+
2470
+
2471
+	/**
2472
+	 * Deletes all the model objects across the relation indicated by $model_name
2473
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2474
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2475
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2476
+	 *
2477
+	 * @param EE_Base_Class|int|string $id_or_obj
2478
+	 * @param string                   $model_name
2479
+	 * @param array                    $query_params
2480
+	 * @return int how many deleted
2481
+	 * @throws \EE_Error
2482
+	 */
2483
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2484
+	{
2485
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2486
+		$relation_settings = $this->related_settings_for($model_name);
2487
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2488
+	}
2489
+
2490
+
2491
+
2492
+	/**
2493
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2494
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2495
+	 * the model objects can't be hard deleted because of blocking related model objects,
2496
+	 * just does a soft-delete on them instead.
2497
+	 *
2498
+	 * @param EE_Base_Class|int|string $id_or_obj
2499
+	 * @param string                   $model_name
2500
+	 * @param array                    $query_params
2501
+	 * @return int how many deleted
2502
+	 * @throws \EE_Error
2503
+	 */
2504
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2505
+	{
2506
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2507
+		$relation_settings = $this->related_settings_for($model_name);
2508
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2509
+	}
2510
+
2511
+
2512
+
2513
+	/**
2514
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2515
+	 * unless otherwise specified in the $query_params
2516
+	 *
2517
+	 * @param        int             /EE_Base_Class $id_or_obj
2518
+	 * @param string $model_name     like 'Event', or 'Registration'
2519
+	 * @param array  $query_params   like EEM_Base::get_all's
2520
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2521
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2522
+	 *                               that by the setting $distinct to TRUE;
2523
+	 * @return int
2524
+	 * @throws \EE_Error
2525
+	 */
2526
+	public function count_related(
2527
+		$id_or_obj,
2528
+		$model_name,
2529
+		$query_params = array(),
2530
+		$field_to_count = null,
2531
+		$distinct = false
2532
+	) {
2533
+		$related_model = $this->get_related_model_obj($model_name);
2534
+		//we're just going to use the query params on the related model's normal get_all query,
2535
+		//except add a condition to say to match the current mod
2536
+		if (! isset($query_params['default_where_conditions'])) {
2537
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2538
+		}
2539
+		$this_model_name = $this->get_this_model_name();
2540
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2541
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2542
+		return $related_model->count($query_params, $field_to_count, $distinct);
2543
+	}
2544
+
2545
+
2546
+
2547
+	/**
2548
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2549
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2550
+	 *
2551
+	 * @param        int           /EE_Base_Class $id_or_obj
2552
+	 * @param string $model_name   like 'Event', or 'Registration'
2553
+	 * @param array  $query_params like EEM_Base::get_all's
2554
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2555
+	 * @return float
2556
+	 * @throws \EE_Error
2557
+	 */
2558
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2559
+	{
2560
+		$related_model = $this->get_related_model_obj($model_name);
2561
+		if (! is_array($query_params)) {
2562
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2563
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2564
+					gettype($query_params)), '4.6.0');
2565
+			$query_params = array();
2566
+		}
2567
+		//we're just going to use the query params on the related model's normal get_all query,
2568
+		//except add a condition to say to match the current mod
2569
+		if (! isset($query_params['default_where_conditions'])) {
2570
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2571
+		}
2572
+		$this_model_name = $this->get_this_model_name();
2573
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2574
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2575
+		return $related_model->sum($query_params, $field_to_sum);
2576
+	}
2577
+
2578
+
2579
+
2580
+	/**
2581
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2582
+	 * $modelObject
2583
+	 *
2584
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2585
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2586
+	 * @param array               $query_params     like EEM_Base::get_all's
2587
+	 * @return EE_Base_Class
2588
+	 * @throws \EE_Error
2589
+	 */
2590
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2591
+	{
2592
+		$query_params['limit'] = 1;
2593
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2594
+		if ($results) {
2595
+			return array_shift($results);
2596
+		} else {
2597
+			return null;
2598
+		}
2599
+	}
2600
+
2601
+
2602
+
2603
+	/**
2604
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2605
+	 *
2606
+	 * @return string
2607
+	 */
2608
+	public function get_this_model_name()
2609
+	{
2610
+		return str_replace("EEM_", "", get_class($this));
2611
+	}
2612
+
2613
+
2614
+
2615
+	/**
2616
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2617
+	 *
2618
+	 * @return EE_Any_Foreign_Model_Name_Field
2619
+	 * @throws EE_Error
2620
+	 */
2621
+	public function get_field_containing_related_model_name()
2622
+	{
2623
+		foreach ($this->field_settings(true) as $field) {
2624
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2625
+				$field_with_model_name = $field;
2626
+			}
2627
+		}
2628
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2629
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2630
+				$this->get_this_model_name()));
2631
+		}
2632
+		return $field_with_model_name;
2633
+	}
2634
+
2635
+
2636
+
2637
+	/**
2638
+	 * Inserts a new entry into the database, for each table.
2639
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2640
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2641
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2642
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2643
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2644
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2645
+	 *
2646
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2647
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2648
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2649
+	 *                              of EEM_Base)
2650
+	 * @return int new primary key on main table that got inserted
2651
+	 * @throws EE_Error
2652
+	 */
2653
+	public function insert($field_n_values)
2654
+	{
2655
+		/**
2656
+		 * Filters the fields and their values before inserting an item using the models
2657
+		 *
2658
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2659
+		 * @param EEM_Base $model           the model used
2660
+		 */
2661
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2662
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2663
+			$main_table = $this->_get_main_table();
2664
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2665
+			if ($new_id !== false) {
2666
+				foreach ($this->_get_other_tables() as $other_table) {
2667
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2668
+				}
2669
+			}
2670
+			/**
2671
+			 * Done just after attempting to insert a new model object
2672
+			 *
2673
+			 * @param EEM_Base   $model           used
2674
+			 * @param array      $fields_n_values fields and their values
2675
+			 * @param int|string the              ID of the newly-inserted model object
2676
+			 */
2677
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2678
+			return $new_id;
2679
+		} else {
2680
+			return false;
2681
+		}
2682
+	}
2683
+
2684
+
2685
+
2686
+	/**
2687
+	 * Checks that the result would satisfy the unique indexes on this model
2688
+	 *
2689
+	 * @param array  $field_n_values
2690
+	 * @param string $action
2691
+	 * @return boolean
2692
+	 * @throws \EE_Error
2693
+	 */
2694
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2695
+	{
2696
+		foreach ($this->unique_indexes() as $index_name => $index) {
2697
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2698
+			if ($this->exists(array($uniqueness_where_params))) {
2699
+				EE_Error::add_error(
2700
+					sprintf(
2701
+						__(
2702
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2703
+							"event_espresso"
2704
+						),
2705
+						$action,
2706
+						$this->_get_class_name(),
2707
+						$index_name,
2708
+						implode(",", $index->field_names()),
2709
+						http_build_query($uniqueness_where_params)
2710
+					),
2711
+					__FILE__,
2712
+					__FUNCTION__,
2713
+					__LINE__
2714
+				);
2715
+				return false;
2716
+			}
2717
+		}
2718
+		return true;
2719
+	}
2720
+
2721
+
2722
+
2723
+	/**
2724
+	 * Checks the database for an item that conflicts (ie, if this item were
2725
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2726
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2727
+	 * can be either an EE_Base_Class or an array of fields n values
2728
+	 *
2729
+	 * @param EE_Base_Class|array $obj_or_fields_array
2730
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2731
+	 *                                                 when looking for conflicts
2732
+	 *                                                 (ie, if false, we ignore the model object's primary key
2733
+	 *                                                 when finding "conflicts". If true, it's also considered).
2734
+	 *                                                 Only works for INT primary key,
2735
+	 *                                                 STRING primary keys cannot be ignored
2736
+	 * @throws EE_Error
2737
+	 * @return EE_Base_Class|array
2738
+	 */
2739
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2740
+	{
2741
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2742
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2743
+		} elseif (is_array($obj_or_fields_array)) {
2744
+			$fields_n_values = $obj_or_fields_array;
2745
+		} else {
2746
+			throw new EE_Error(
2747
+				sprintf(
2748
+					__(
2749
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2750
+						"event_espresso"
2751
+					),
2752
+					get_class($this),
2753
+					$obj_or_fields_array
2754
+				)
2755
+			);
2756
+		}
2757
+		$query_params = array();
2758
+		if ($this->has_primary_key_field()
2759
+			&& ($include_primary_key
2760
+				|| $this->get_primary_key_field()
2761
+				   instanceof
2762
+				   EE_Primary_Key_String_Field)
2763
+			&& isset($fields_n_values[$this->primary_key_name()])
2764
+		) {
2765
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2766
+		}
2767
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2768
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2769
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2770
+		}
2771
+		//if there is nothing to base this search on, then we shouldn't find anything
2772
+		if (empty($query_params)) {
2773
+			return array();
2774
+		} else {
2775
+			return $this->get_one($query_params);
2776
+		}
2777
+	}
2778
+
2779
+
2780
+
2781
+	/**
2782
+	 * Like count, but is optimized and returns a boolean instead of an int
2783
+	 *
2784
+	 * @param array $query_params
2785
+	 * @return boolean
2786
+	 * @throws \EE_Error
2787
+	 */
2788
+	public function exists($query_params)
2789
+	{
2790
+		$query_params['limit'] = 1;
2791
+		return $this->count($query_params) > 0;
2792
+	}
2793
+
2794
+
2795
+
2796
+	/**
2797
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2798
+	 *
2799
+	 * @param int|string $id
2800
+	 * @return boolean
2801
+	 * @throws \EE_Error
2802
+	 */
2803
+	public function exists_by_ID($id)
2804
+	{
2805
+		return $this->exists(
2806
+			array(
2807
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2808
+				array(
2809
+					$this->primary_key_name() => $id,
2810
+				),
2811
+			)
2812
+		);
2813
+	}
2814
+
2815
+
2816
+
2817
+	/**
2818
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2819
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2820
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2821
+	 * on the main table)
2822
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2823
+	 * cases where we want to call it directly rather than via insert().
2824
+	 *
2825
+	 * @access   protected
2826
+	 * @param EE_Table_Base $table
2827
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2828
+	 *                                       float
2829
+	 * @param int           $new_id          for now we assume only int keys
2830
+	 * @throws EE_Error
2831
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2832
+	 * @return int ID of new row inserted, or FALSE on failure
2833
+	 */
2834
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2835
+	{
2836
+		global $wpdb;
2837
+		$insertion_col_n_values = array();
2838
+		$format_for_insertion = array();
2839
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2840
+		foreach ($fields_on_table as $field_name => $field_obj) {
2841
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2842
+			if ($field_obj->is_auto_increment()) {
2843
+				continue;
2844
+			}
2845
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2846
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2847
+			if ($prepared_value !== null) {
2848
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2849
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2850
+			}
2851
+		}
2852
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2853
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2854
+			//so add the fk to the main table as a column
2855
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2856
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2857
+		}
2858
+		//insert the new entry
2859
+		$result = $this->_do_wpdb_query('insert',
2860
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2861
+		if ($result === false) {
2862
+			return false;
2863
+		}
2864
+		//ok, now what do we return for the ID of the newly-inserted thing?
2865
+		if ($this->has_primary_key_field()) {
2866
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2867
+				return $wpdb->insert_id;
2868
+			} else {
2869
+				//it's not an auto-increment primary key, so
2870
+				//it must have been supplied
2871
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2872
+			}
2873
+		} else {
2874
+			//we can't return a  primary key because there is none. instead return
2875
+			//a unique string indicating this model
2876
+			return $this->get_index_primary_key_string($fields_n_values);
2877
+		}
2878
+	}
2879
+
2880
+
2881
+
2882
+	/**
2883
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2884
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2885
+	 * and there is no default, we pass it along. WPDB will take care of it)
2886
+	 *
2887
+	 * @param EE_Model_Field_Base $field_obj
2888
+	 * @param array               $fields_n_values
2889
+	 * @return mixed string|int|float depending on what the table column will be expecting
2890
+	 * @throws \EE_Error
2891
+	 */
2892
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2893
+	{
2894
+		//if this field doesn't allow nullable, don't allow it
2895
+		if (
2896
+			! $field_obj->is_nullable()
2897
+			&& (
2898
+				! isset($fields_n_values[$field_obj->get_name()])
2899
+				|| $fields_n_values[$field_obj->get_name()] === null
2900
+			)
2901
+		) {
2902
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2903
+		}
2904
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2905
+			? $fields_n_values[$field_obj->get_name()]
2906
+			: null;
2907
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2908
+	}
2909
+
2910
+
2911
+
2912
+	/**
2913
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2914
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2915
+	 * the field's prepare_for_set() method.
2916
+	 *
2917
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2918
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2919
+	 *                                   top of file)
2920
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2921
+	 *                                   $value is a custom selection
2922
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2923
+	 */
2924
+	private function _prepare_value_for_use_in_db($value, $field)
2925
+	{
2926
+		if ($field && $field instanceof EE_Model_Field_Base) {
2927
+			switch ($this->_values_already_prepared_by_model_object) {
2928
+				/** @noinspection PhpMissingBreakStatementInspection */
2929
+				case self::not_prepared_by_model_object:
2930
+					$value = $field->prepare_for_set($value);
2931
+				//purposefully left out "return"
2932
+				case self::prepared_by_model_object:
2933
+					$value = $field->prepare_for_use_in_db($value);
2934
+				case self::prepared_for_use_in_db:
2935
+					//leave the value alone
2936
+			}
2937
+			return $value;
2938
+		} else {
2939
+			return $value;
2940
+		}
2941
+	}
2942
+
2943
+
2944
+
2945
+	/**
2946
+	 * Returns the main table on this model
2947
+	 *
2948
+	 * @return EE_Primary_Table
2949
+	 * @throws EE_Error
2950
+	 */
2951
+	protected function _get_main_table()
2952
+	{
2953
+		foreach ($this->_tables as $table) {
2954
+			if ($table instanceof EE_Primary_Table) {
2955
+				return $table;
2956
+			}
2957
+		}
2958
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2959
+			'event_espresso'), get_class($this)));
2960
+	}
2961
+
2962
+
2963
+
2964
+	/**
2965
+	 * table
2966
+	 * returns EE_Primary_Table table name
2967
+	 *
2968
+	 * @return string
2969
+	 * @throws \EE_Error
2970
+	 */
2971
+	public function table()
2972
+	{
2973
+		return $this->_get_main_table()->get_table_name();
2974
+	}
2975
+
2976
+
2977
+
2978
+	/**
2979
+	 * table
2980
+	 * returns first EE_Secondary_Table table name
2981
+	 *
2982
+	 * @return string
2983
+	 */
2984
+	public function second_table()
2985
+	{
2986
+		// grab second table from tables array
2987
+		$second_table = end($this->_tables);
2988
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2989
+	}
2990
+
2991
+
2992
+
2993
+	/**
2994
+	 * get_table_obj_by_alias
2995
+	 * returns table name given it's alias
2996
+	 *
2997
+	 * @param string $table_alias
2998
+	 * @return EE_Primary_Table | EE_Secondary_Table
2999
+	 */
3000
+	public function get_table_obj_by_alias($table_alias = '')
3001
+	{
3002
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3003
+	}
3004
+
3005
+
3006
+
3007
+	/**
3008
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3009
+	 *
3010
+	 * @return EE_Secondary_Table[]
3011
+	 */
3012
+	protected function _get_other_tables()
3013
+	{
3014
+		$other_tables = array();
3015
+		foreach ($this->_tables as $table_alias => $table) {
3016
+			if ($table instanceof EE_Secondary_Table) {
3017
+				$other_tables[$table_alias] = $table;
3018
+			}
3019
+		}
3020
+		return $other_tables;
3021
+	}
3022
+
3023
+
3024
+
3025
+	/**
3026
+	 * Finds all the fields that correspond to the given table
3027
+	 *
3028
+	 * @param string $table_alias , array key in EEM_Base::_tables
3029
+	 * @return EE_Model_Field_Base[]
3030
+	 */
3031
+	public function _get_fields_for_table($table_alias)
3032
+	{
3033
+		return $this->_fields[$table_alias];
3034
+	}
3035
+
3036
+
3037
+
3038
+	/**
3039
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3040
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3041
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3042
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3043
+	 * related Registration, Transaction, and Payment models.
3044
+	 *
3045
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3046
+	 * @return EE_Model_Query_Info_Carrier
3047
+	 * @throws \EE_Error
3048
+	 */
3049
+	public function _extract_related_models_from_query($query_params)
3050
+	{
3051
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3052
+		if (array_key_exists(0, $query_params)) {
3053
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3054
+		}
3055
+		if (array_key_exists('group_by', $query_params)) {
3056
+			if (is_array($query_params['group_by'])) {
3057
+				$this->_extract_related_models_from_sub_params_array_values(
3058
+					$query_params['group_by'],
3059
+					$query_info_carrier,
3060
+					'group_by'
3061
+				);
3062
+			} elseif (! empty ($query_params['group_by'])) {
3063
+				$this->_extract_related_model_info_from_query_param(
3064
+					$query_params['group_by'],
3065
+					$query_info_carrier,
3066
+					'group_by'
3067
+				);
3068
+			}
3069
+		}
3070
+		if (array_key_exists('having', $query_params)) {
3071
+			$this->_extract_related_models_from_sub_params_array_keys(
3072
+				$query_params[0],
3073
+				$query_info_carrier,
3074
+				'having'
3075
+			);
3076
+		}
3077
+		if (array_key_exists('order_by', $query_params)) {
3078
+			if (is_array($query_params['order_by'])) {
3079
+				$this->_extract_related_models_from_sub_params_array_keys(
3080
+					$query_params['order_by'],
3081
+					$query_info_carrier,
3082
+					'order_by'
3083
+				);
3084
+			} elseif (! empty($query_params['order_by'])) {
3085
+				$this->_extract_related_model_info_from_query_param(
3086
+					$query_params['order_by'],
3087
+					$query_info_carrier,
3088
+					'order_by'
3089
+				);
3090
+			}
3091
+		}
3092
+		if (array_key_exists('force_join', $query_params)) {
3093
+			$this->_extract_related_models_from_sub_params_array_values(
3094
+				$query_params['force_join'],
3095
+				$query_info_carrier,
3096
+				'force_join'
3097
+			);
3098
+		}
3099
+		return $query_info_carrier;
3100
+	}
3101
+
3102
+
3103
+
3104
+	/**
3105
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3106
+	 *
3107
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3108
+	 *                                                      $query_params['having']
3109
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3110
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3111
+	 * @throws EE_Error
3112
+	 * @return \EE_Model_Query_Info_Carrier
3113
+	 */
3114
+	private function _extract_related_models_from_sub_params_array_keys(
3115
+		$sub_query_params,
3116
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3117
+		$query_param_type
3118
+	) {
3119
+		if (! empty($sub_query_params)) {
3120
+			$sub_query_params = (array)$sub_query_params;
3121
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3122
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3123
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3124
+					$query_param_type);
3125
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3126
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3127
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3128
+				//of array('Registration.TXN_ID'=>23)
3129
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3130
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3131
+					if (! is_array($possibly_array_of_params)) {
3132
+						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3133
+							"event_espresso"),
3134
+							$param, $possibly_array_of_params));
3135
+					} else {
3136
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3137
+							$model_query_info_carrier, $query_param_type);
3138
+					}
3139
+				} elseif ($query_param_type === 0 //ie WHERE
3140
+						  && is_array($possibly_array_of_params)
3141
+						  && isset($possibly_array_of_params[2])
3142
+						  && $possibly_array_of_params[2] == true
3143
+				) {
3144
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3145
+					//indicating that $possible_array_of_params[1] is actually a field name,
3146
+					//from which we should extract query parameters!
3147
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3148
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3149
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3150
+					}
3151
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3152
+						$model_query_info_carrier, $query_param_type);
3153
+				}
3154
+			}
3155
+		}
3156
+		return $model_query_info_carrier;
3157
+	}
3158
+
3159
+
3160
+
3161
+	/**
3162
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3163
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3164
+	 *
3165
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3166
+	 *                                                      $query_params['having']
3167
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3168
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3169
+	 * @throws EE_Error
3170
+	 * @return \EE_Model_Query_Info_Carrier
3171
+	 */
3172
+	private function _extract_related_models_from_sub_params_array_values(
3173
+		$sub_query_params,
3174
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3175
+		$query_param_type
3176
+	) {
3177
+		if (! empty($sub_query_params)) {
3178
+			if (! is_array($sub_query_params)) {
3179
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3180
+					$sub_query_params));
3181
+			}
3182
+			foreach ($sub_query_params as $param) {
3183
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3184
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3185
+					$query_param_type);
3186
+			}
3187
+		}
3188
+		return $model_query_info_carrier;
3189
+	}
3190
+
3191
+
3192
+
3193
+	/**
3194
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3195
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3196
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3197
+	 * but use them in a different order. Eg, we need to know what models we are querying
3198
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3199
+	 * other models before we can finalize the where clause SQL.
3200
+	 *
3201
+	 * @param array $query_params
3202
+	 * @throws EE_Error
3203
+	 * @return EE_Model_Query_Info_Carrier
3204
+	 */
3205
+	public function _create_model_query_info_carrier($query_params)
3206
+	{
3207
+		if (! is_array($query_params)) {
3208
+			EE_Error::doing_it_wrong(
3209
+				'EEM_Base::_create_model_query_info_carrier',
3210
+				sprintf(
3211
+					__(
3212
+						'$query_params should be an array, you passed a variable of type %s',
3213
+						'event_espresso'
3214
+					),
3215
+					gettype($query_params)
3216
+				),
3217
+				'4.6.0'
3218
+			);
3219
+			$query_params = array();
3220
+		}
3221
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3222
+		//first check if we should alter the query to account for caps or not
3223
+		//because the caps might require us to do extra joins
3224
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3225
+			$query_params[0] = $where_query_params = array_replace_recursive(
3226
+				$where_query_params,
3227
+				$this->caps_where_conditions(
3228
+					$query_params['caps']
3229
+				)
3230
+			);
3231
+		}
3232
+		$query_object = $this->_extract_related_models_from_query($query_params);
3233
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3234
+		foreach ($where_query_params as $key => $value) {
3235
+			if (is_int($key)) {
3236
+				throw new EE_Error(
3237
+					sprintf(
3238
+						__(
3239
+							"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.",
3240
+							"event_espresso"
3241
+						),
3242
+						$key,
3243
+						var_export($value, true),
3244
+						var_export($query_params, true),
3245
+						get_class($this)
3246
+					)
3247
+				);
3248
+			}
3249
+		}
3250
+		if (
3251
+			array_key_exists('default_where_conditions', $query_params)
3252
+			&& ! empty($query_params['default_where_conditions'])
3253
+		) {
3254
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3255
+		} else {
3256
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3257
+		}
3258
+		$where_query_params = array_merge(
3259
+			$this->_get_default_where_conditions_for_models_in_query(
3260
+				$query_object,
3261
+				$use_default_where_conditions,
3262
+				$where_query_params
3263
+			),
3264
+			$where_query_params
3265
+		);
3266
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3267
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3268
+		// So we need to setup a subquery and use that for the main join.
3269
+		// Note for now this only works on the primary table for the model.
3270
+		// So for instance, you could set the limit array like this:
3271
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3272
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3273
+			$query_object->set_main_model_join_sql(
3274
+				$this->_construct_limit_join_select(
3275
+					$query_params['on_join_limit'][0],
3276
+					$query_params['on_join_limit'][1]
3277
+				)
3278
+			);
3279
+		}
3280
+		//set limit
3281
+		if (array_key_exists('limit', $query_params)) {
3282
+			if (is_array($query_params['limit'])) {
3283
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3284
+					$e = sprintf(
3285
+						__(
3286
+							"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)",
3287
+							"event_espresso"
3288
+						),
3289
+						http_build_query($query_params['limit'])
3290
+					);
3291
+					throw new EE_Error($e . "|" . $e);
3292
+				}
3293
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3294
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3295
+			} elseif (! empty ($query_params['limit'])) {
3296
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3297
+			}
3298
+		}
3299
+		//set order by
3300
+		if (array_key_exists('order_by', $query_params)) {
3301
+			if (is_array($query_params['order_by'])) {
3302
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3303
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3304
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3305
+				if (array_key_exists('order', $query_params)) {
3306
+					throw new EE_Error(
3307
+						sprintf(
3308
+							__(
3309
+								"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 ",
3310
+								"event_espresso"
3311
+							),
3312
+							get_class($this),
3313
+							implode(", ", array_keys($query_params['order_by'])),
3314
+							implode(", ", $query_params['order_by']),
3315
+							$query_params['order']
3316
+						)
3317
+					);
3318
+				}
3319
+				$this->_extract_related_models_from_sub_params_array_keys(
3320
+					$query_params['order_by'],
3321
+					$query_object,
3322
+					'order_by'
3323
+				);
3324
+				//assume it's an array of fields to order by
3325
+				$order_array = array();
3326
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3327
+					$order = $this->_extract_order($order);
3328
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3329
+				}
3330
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3331
+			} elseif (! empty ($query_params['order_by'])) {
3332
+				$this->_extract_related_model_info_from_query_param(
3333
+					$query_params['order_by'],
3334
+					$query_object,
3335
+					'order',
3336
+					$query_params['order_by']
3337
+				);
3338
+				$order = isset($query_params['order'])
3339
+					? $this->_extract_order($query_params['order'])
3340
+					: 'DESC';
3341
+				$query_object->set_order_by_sql(
3342
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3343
+				);
3344
+			}
3345
+		}
3346
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3347
+		if (! array_key_exists('order_by', $query_params)
3348
+			&& array_key_exists('order', $query_params)
3349
+			&& ! empty($query_params['order'])
3350
+		) {
3351
+			$pk_field = $this->get_primary_key_field();
3352
+			$order = $this->_extract_order($query_params['order']);
3353
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3354
+		}
3355
+		//set group by
3356
+		if (array_key_exists('group_by', $query_params)) {
3357
+			if (is_array($query_params['group_by'])) {
3358
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3359
+				$group_by_array = array();
3360
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3361
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3362
+				}
3363
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3364
+			} elseif (! empty ($query_params['group_by'])) {
3365
+				$query_object->set_group_by_sql(
3366
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3367
+				);
3368
+			}
3369
+		}
3370
+		//set having
3371
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3372
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3373
+		}
3374
+		//now, just verify they didn't pass anything wack
3375
+		foreach ($query_params as $query_key => $query_value) {
3376
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3377
+				throw new EE_Error(
3378
+					sprintf(
3379
+						__(
3380
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3381
+							'event_espresso'
3382
+						),
3383
+						$query_key,
3384
+						get_class($this),
3385
+						//						print_r( $this->_allowed_query_params, TRUE )
3386
+						implode(',', $this->_allowed_query_params)
3387
+					)
3388
+				);
3389
+			}
3390
+		}
3391
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3392
+		if (empty($main_model_join_sql)) {
3393
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3394
+		}
3395
+		return $query_object;
3396
+	}
3397
+
3398
+
3399
+
3400
+	/**
3401
+	 * Gets the where conditions that should be imposed on the query based on the
3402
+	 * context (eg reading frontend, backend, edit or delete).
3403
+	 *
3404
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3405
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3406
+	 * @throws \EE_Error
3407
+	 */
3408
+	public function caps_where_conditions($context = self::caps_read)
3409
+	{
3410
+		EEM_Base::verify_is_valid_cap_context($context);
3411
+		$cap_where_conditions = array();
3412
+		$cap_restrictions = $this->caps_missing($context);
3413
+		/**
3414
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3415
+		 */
3416
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3417
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3418
+				$restriction_if_no_cap->get_default_where_conditions());
3419
+		}
3420
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3421
+			$cap_restrictions);
3422
+	}
3423
+
3424
+
3425
+
3426
+	/**
3427
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3428
+	 * otherwise throws an exception
3429
+	 *
3430
+	 * @param string $should_be_order_string
3431
+	 * @return string either ASC, asc, DESC or desc
3432
+	 * @throws EE_Error
3433
+	 */
3434
+	private function _extract_order($should_be_order_string)
3435
+	{
3436
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3437
+			return $should_be_order_string;
3438
+		} else {
3439
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3440
+				"event_espresso"), get_class($this), $should_be_order_string));
3441
+		}
3442
+	}
3443
+
3444
+
3445
+
3446
+	/**
3447
+	 * Looks at all the models which are included in this query, and asks each
3448
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3449
+	 * so they can be merged
3450
+	 *
3451
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3452
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3453
+	 *                                                                  'none' means NO default where conditions will
3454
+	 *                                                                  be used AT ALL during this query.
3455
+	 *                                                                  'other_models_only' means default where
3456
+	 *                                                                  conditions from other models will be used, but
3457
+	 *                                                                  not for this primary model. 'all', the default,
3458
+	 *                                                                  means default where conditions will apply as
3459
+	 *                                                                  normal
3460
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3461
+	 * @throws EE_Error
3462
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3463
+	 */
3464
+	private function _get_default_where_conditions_for_models_in_query(
3465
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3466
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3467
+		$where_query_params = array()
3468
+	) {
3469
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3470
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3471
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3472
+				"event_espresso"), $use_default_where_conditions,
3473
+				implode(", ", $allowed_used_default_where_conditions_values)));
3474
+		}
3475
+		$universal_query_params = array();
3476
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3477
+			$universal_query_params = $this->_get_default_where_conditions();
3478
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3479
+			$universal_query_params = $this->_get_minimum_where_conditions();
3480
+		}
3481
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3482
+			$related_model = $this->get_related_model_obj($model_name);
3483
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3484
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3485
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3486
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3487
+			} else {
3488
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3489
+				continue;
3490
+			}
3491
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3492
+				$related_model_universal_where_params,
3493
+				$where_query_params,
3494
+				$related_model,
3495
+				$model_relation_path
3496
+			);
3497
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3498
+				$universal_query_params,
3499
+				$overrides
3500
+			);
3501
+		}
3502
+		return $universal_query_params;
3503
+	}
3504
+
3505
+
3506
+
3507
+	/**
3508
+	 * Determines whether or not we should use default where conditions for the model in question
3509
+	 * (this model, or other related models).
3510
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3511
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3512
+	 * We should use default where conditions on related models when they requested to use default where conditions
3513
+	 * on all models, or specifically just on other related models
3514
+	 * @param      $default_where_conditions_value
3515
+	 * @param bool $for_this_model false means this is for OTHER related models
3516
+	 * @return bool
3517
+	 */
3518
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3519
+	{
3520
+		return (
3521
+				   $for_this_model
3522
+				   && in_array(
3523
+					   $default_where_conditions_value,
3524
+					   array(
3525
+						   EEM_Base::default_where_conditions_all,
3526
+						   EEM_Base::default_where_conditions_this_only,
3527
+						   EEM_Base::default_where_conditions_minimum_others,
3528
+					   ),
3529
+					   true
3530
+				   )
3531
+			   )
3532
+			   || (
3533
+				   ! $for_this_model
3534
+				   && in_array(
3535
+					   $default_where_conditions_value,
3536
+					   array(
3537
+						   EEM_Base::default_where_conditions_all,
3538
+						   EEM_Base::default_where_conditions_others_only,
3539
+					   ),
3540
+					   true
3541
+				   )
3542
+			   );
3543
+	}
3544
+
3545
+	/**
3546
+	 * Determines whether or not we should use default minimum conditions for the model in question
3547
+	 * (this model, or other related models).
3548
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3549
+	 * where conditions.
3550
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3551
+	 * on this model or others
3552
+	 * @param      $default_where_conditions_value
3553
+	 * @param bool $for_this_model false means this is for OTHER related models
3554
+	 * @return bool
3555
+	 */
3556
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3557
+	{
3558
+		return (
3559
+				   $for_this_model
3560
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3561
+			   )
3562
+			   || (
3563
+				   ! $for_this_model
3564
+				   && in_array(
3565
+					   $default_where_conditions_value,
3566
+					   array(
3567
+						   EEM_Base::default_where_conditions_minimum_others,
3568
+						   EEM_Base::default_where_conditions_minimum_all,
3569
+					   ),
3570
+					   true
3571
+				   )
3572
+			   );
3573
+	}
3574
+
3575
+
3576
+	/**
3577
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3578
+	 * then we also add a special where condition which allows for that model's primary key
3579
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3580
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3581
+	 *
3582
+	 * @param array    $default_where_conditions
3583
+	 * @param array    $provided_where_conditions
3584
+	 * @param EEM_Base $model
3585
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3586
+	 * @return array like EEM_Base::get_all's $query_params[0]
3587
+	 * @throws \EE_Error
3588
+	 */
3589
+	private function _override_defaults_or_make_null_friendly(
3590
+		$default_where_conditions,
3591
+		$provided_where_conditions,
3592
+		$model,
3593
+		$model_relation_path
3594
+	) {
3595
+		$null_friendly_where_conditions = array();
3596
+		$none_overridden = true;
3597
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3598
+		foreach ($default_where_conditions as $key => $val) {
3599
+			if (isset($provided_where_conditions[$key])) {
3600
+				$none_overridden = false;
3601
+			} else {
3602
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3603
+			}
3604
+		}
3605
+		if ($none_overridden && $default_where_conditions) {
3606
+			if ($model->has_primary_key_field()) {
3607
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3608
+																				. "."
3609
+																				. $model->primary_key_name()] = array('IS NULL');
3610
+			}/*else{
3611 3611
 				//@todo NO PK, use other defaults
3612 3612
 			}*/
3613
-        }
3614
-        return $null_friendly_where_conditions;
3615
-    }
3616
-
3617
-
3618
-
3619
-    /**
3620
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3621
-     * default where conditions on all get_all, update, and delete queries done by this model.
3622
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3623
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3624
-     *
3625
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3626
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3627
-     */
3628
-    private function _get_default_where_conditions($model_relation_path = null)
3629
-    {
3630
-        if ($this->_ignore_where_strategy) {
3631
-            return array();
3632
-        }
3633
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3634
-    }
3635
-
3636
-
3637
-
3638
-    /**
3639
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3640
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3641
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3642
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3643
-     * Similar to _get_default_where_conditions
3644
-     *
3645
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3646
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3647
-     */
3648
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3649
-    {
3650
-        if ($this->_ignore_where_strategy) {
3651
-            return array();
3652
-        }
3653
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3654
-    }
3655
-
3656
-
3657
-
3658
-    /**
3659
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3660
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3661
-     *
3662
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3663
-     * @return string
3664
-     * @throws \EE_Error
3665
-     */
3666
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3667
-    {
3668
-        $selects = $this->_get_columns_to_select_for_this_model();
3669
-        foreach (
3670
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3671
-            $name_of_other_model_included
3672
-        ) {
3673
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3674
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3675
-            foreach ($other_model_selects as $key => $value) {
3676
-                $selects[] = $value;
3677
-            }
3678
-        }
3679
-        return implode(", ", $selects);
3680
-    }
3681
-
3682
-
3683
-
3684
-    /**
3685
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3686
-     * So that's going to be the columns for all the fields on the model
3687
-     *
3688
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3689
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3690
-     */
3691
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3692
-    {
3693
-        $fields = $this->field_settings();
3694
-        $selects = array();
3695
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3696
-            $this->get_this_model_name());
3697
-        foreach ($fields as $field_obj) {
3698
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3699
-                         . $field_obj->get_table_alias()
3700
-                         . "."
3701
-                         . $field_obj->get_table_column()
3702
-                         . " AS '"
3703
-                         . $table_alias_with_model_relation_chain_prefix
3704
-                         . $field_obj->get_table_alias()
3705
-                         . "."
3706
-                         . $field_obj->get_table_column()
3707
-                         . "'";
3708
-        }
3709
-        //make sure we are also getting the PKs of each table
3710
-        $tables = $this->get_tables();
3711
-        if (count($tables) > 1) {
3712
-            foreach ($tables as $table_obj) {
3713
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3714
-                                       . $table_obj->get_fully_qualified_pk_column();
3715
-                if (! in_array($qualified_pk_column, $selects)) {
3716
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3717
-                }
3718
-            }
3719
-        }
3720
-        return $selects;
3721
-    }
3722
-
3723
-
3724
-
3725
-    /**
3726
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3727
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3728
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3729
-     * SQL for joining, and the data types
3730
-     *
3731
-     * @param null|string                 $original_query_param
3732
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3733
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3734
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3735
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3736
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3737
-     *                                                          or 'Registration's
3738
-     * @param string                      $original_query_param what it originally was (eg
3739
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3740
-     *                                                          matches $query_param
3741
-     * @throws EE_Error
3742
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3743
-     */
3744
-    private function _extract_related_model_info_from_query_param(
3745
-        $query_param,
3746
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3747
-        $query_param_type,
3748
-        $original_query_param = null
3749
-    ) {
3750
-        if ($original_query_param === null) {
3751
-            $original_query_param = $query_param;
3752
-        }
3753
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3754
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3755
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3756
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3757
-        //check to see if we have a field on this model
3758
-        $this_model_fields = $this->field_settings(true);
3759
-        if (array_key_exists($query_param, $this_model_fields)) {
3760
-            if ($allow_fields) {
3761
-                return;
3762
-            } else {
3763
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3764
-                    "event_espresso"),
3765
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3766
-            }
3767
-        } //check if this is a special logic query param
3768
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3769
-            if ($allow_logic_query_params) {
3770
-                return;
3771
-            } else {
3772
-                throw new EE_Error(
3773
-                    sprintf(
3774
-                        __('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',
3775
-                            'event_espresso'),
3776
-                        implode('", "', $this->_logic_query_param_keys),
3777
-                        $query_param,
3778
-                        get_class($this),
3779
-                        '<br />',
3780
-                        "\t"
3781
-                        . ' $passed_in_query_info = <pre>'
3782
-                        . print_r($passed_in_query_info, true)
3783
-                        . '</pre>'
3784
-                        . "\n\t"
3785
-                        . ' $query_param_type = '
3786
-                        . $query_param_type
3787
-                        . "\n\t"
3788
-                        . ' $original_query_param = '
3789
-                        . $original_query_param
3790
-                    )
3791
-                );
3792
-            }
3793
-        } //check if it's a custom selection
3794
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3795
-            return;
3796
-        }
3797
-        //check if has a model name at the beginning
3798
-        //and
3799
-        //check if it's a field on a related model
3800
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3801
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3802
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3803
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3804
-                if ($query_param === '') {
3805
-                    //nothing left to $query_param
3806
-                    //we should actually end in a field name, not a model like this!
3807
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3808
-                        "event_espresso"),
3809
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3810
-                } else {
3811
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3812
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3813
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3814
-                    return;
3815
-                }
3816
-            } elseif ($query_param === $valid_related_model_name) {
3817
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3818
-                return;
3819
-            }
3820
-        }
3821
-        //ok so $query_param didn't start with a model name
3822
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3823
-        //it's wack, that's what it is
3824
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3825
-            "event_espresso"),
3826
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3827
-    }
3828
-
3829
-
3830
-
3831
-    /**
3832
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3833
-     * and store it on $passed_in_query_info
3834
-     *
3835
-     * @param string                      $model_name
3836
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3837
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3838
-     *                                                          model and $model_name. Eg, if we are querying Event,
3839
-     *                                                          and are adding a join to 'Payment' with the original
3840
-     *                                                          query param key
3841
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3842
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3843
-     *                                                          Payment wants to add default query params so that it
3844
-     *                                                          will know what models to prepend onto its default query
3845
-     *                                                          params or in case it wants to rename tables (in case
3846
-     *                                                          there are multiple joins to the same table)
3847
-     * @return void
3848
-     * @throws \EE_Error
3849
-     */
3850
-    private function _add_join_to_model(
3851
-        $model_name,
3852
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3853
-        $original_query_param
3854
-    ) {
3855
-        $relation_obj = $this->related_settings_for($model_name);
3856
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3857
-        //check if the relation is HABTM, because then we're essentially doing two joins
3858
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3859
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3860
-            $join_model_obj = $relation_obj->get_join_model();
3861
-            //replace the model specified with the join model for this relation chain, whi
3862
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3863
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3864
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3865
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3866
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3867
-            $passed_in_query_info->merge($new_query_info);
3868
-        }
3869
-        //now just join to the other table pointed to by the relation object, and add its data types
3870
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3871
-            array($model_relation_chain => $model_name),
3872
-            $relation_obj->get_join_statement($model_relation_chain));
3873
-        $passed_in_query_info->merge($new_query_info);
3874
-    }
3875
-
3876
-
3877
-
3878
-    /**
3879
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3880
-     *
3881
-     * @param array $where_params like EEM_Base::get_all
3882
-     * @return string of SQL
3883
-     * @throws \EE_Error
3884
-     */
3885
-    private function _construct_where_clause($where_params)
3886
-    {
3887
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3888
-        if ($SQL) {
3889
-            return " WHERE " . $SQL;
3890
-        } else {
3891
-            return '';
3892
-        }
3893
-    }
3894
-
3895
-
3896
-
3897
-    /**
3898
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3899
-     * and should be passed HAVING parameters, not WHERE parameters
3900
-     *
3901
-     * @param array $having_params
3902
-     * @return string
3903
-     * @throws \EE_Error
3904
-     */
3905
-    private function _construct_having_clause($having_params)
3906
-    {
3907
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3908
-        if ($SQL) {
3909
-            return " HAVING " . $SQL;
3910
-        } else {
3911
-            return '';
3912
-        }
3913
-    }
3914
-
3915
-
3916
-
3917
-    /**
3918
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3919
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3920
-     * EEM_Attendee.
3921
-     *
3922
-     * @param string $field_name
3923
-     * @param string $model_name
3924
-     * @return EE_Model_Field_Base
3925
-     * @throws EE_Error
3926
-     */
3927
-    protected function _get_field_on_model($field_name, $model_name)
3928
-    {
3929
-        $model_class = 'EEM_' . $model_name;
3930
-        $model_filepath = $model_class . ".model.php";
3931
-        if (is_readable($model_filepath)) {
3932
-            require_once($model_filepath);
3933
-            $model_instance = call_user_func($model_name . "::instance");
3934
-            /* @var $model_instance EEM_Base */
3935
-            return $model_instance->field_settings_for($field_name);
3936
-        } else {
3937
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3938
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3939
-        }
3940
-    }
3941
-
3942
-
3943
-
3944
-    /**
3945
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3946
-     * Event_Meta.meta_value = 'foo'))"
3947
-     *
3948
-     * @param array  $where_params see EEM_Base::get_all for documentation
3949
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3950
-     * @throws EE_Error
3951
-     * @return string of SQL
3952
-     */
3953
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3954
-    {
3955
-        $where_clauses = array();
3956
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3957
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3958
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3959
-                switch ($query_param) {
3960
-                    case 'not':
3961
-                    case 'NOT':
3962
-                        $where_clauses[] = "! ("
3963
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3964
-                                $glue)
3965
-                                           . ")";
3966
-                        break;
3967
-                    case 'and':
3968
-                    case 'AND':
3969
-                        $where_clauses[] = " ("
3970
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3971
-                                ' AND ')
3972
-                                           . ")";
3973
-                        break;
3974
-                    case 'or':
3975
-                    case 'OR':
3976
-                        $where_clauses[] = " ("
3977
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3978
-                                ' OR ')
3979
-                                           . ")";
3980
-                        break;
3981
-                }
3982
-            } else {
3983
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3984
-                //if it's not a normal field, maybe it's a custom selection?
3985
-                if (! $field_obj) {
3986
-                    if (isset($this->_custom_selections[$query_param][1])) {
3987
-                        $field_obj = $this->_custom_selections[$query_param][1];
3988
-                    } else {
3989
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3990
-                            "event_espresso"), $query_param));
3991
-                    }
3992
-                }
3993
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3994
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3995
-            }
3996
-        }
3997
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3998
-    }
3999
-
4000
-
4001
-
4002
-    /**
4003
-     * Takes the input parameter and extract the table name (alias) and column name
4004
-     *
4005
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4006
-     * @throws EE_Error
4007
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4008
-     */
4009
-    private function _deduce_column_name_from_query_param($query_param)
4010
-    {
4011
-        $field = $this->_deduce_field_from_query_param($query_param);
4012
-        if ($field) {
4013
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4014
-                $query_param);
4015
-            return $table_alias_prefix . $field->get_qualified_column();
4016
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4017
-            //maybe it's custom selection item?
4018
-            //if so, just use it as the "column name"
4019
-            return $query_param;
4020
-        } else {
4021
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4022
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4023
-        }
4024
-    }
4025
-
4026
-
4027
-
4028
-    /**
4029
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4030
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4031
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4032
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4033
-     *
4034
-     * @param string $condition_query_param_key
4035
-     * @return string
4036
-     */
4037
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4038
-    {
4039
-        $pos_of_star = strpos($condition_query_param_key, '*');
4040
-        if ($pos_of_star === false) {
4041
-            return $condition_query_param_key;
4042
-        } else {
4043
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4044
-            return $condition_query_param_sans_star;
4045
-        }
4046
-    }
4047
-
4048
-
4049
-
4050
-    /**
4051
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4052
-     *
4053
-     * @param                            mixed      array | string    $op_and_value
4054
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4055
-     * @throws EE_Error
4056
-     * @return string
4057
-     */
4058
-    private function _construct_op_and_value($op_and_value, $field_obj)
4059
-    {
4060
-        if (is_array($op_and_value)) {
4061
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4062
-            if (! $operator) {
4063
-                $php_array_like_string = array();
4064
-                foreach ($op_and_value as $key => $value) {
4065
-                    $php_array_like_string[] = "$key=>$value";
4066
-                }
4067
-                throw new EE_Error(
4068
-                    sprintf(
4069
-                        __(
4070
-                            "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))",
4071
-                            "event_espresso"
4072
-                        ),
4073
-                        implode(",", $php_array_like_string)
4074
-                    )
4075
-                );
4076
-            }
4077
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4078
-        } else {
4079
-            $operator = '=';
4080
-            $value = $op_and_value;
4081
-        }
4082
-        //check to see if the value is actually another field
4083
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4084
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4085
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4086
-            //in this case, the value should be an array, or at least a comma-separated list
4087
-            //it will need to handle a little differently
4088
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4089
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4090
-            return $operator . SP . $cleaned_value;
4091
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4092
-            //the value should be an array with count of two.
4093
-            if (count($value) !== 2) {
4094
-                throw new EE_Error(
4095
-                    sprintf(
4096
-                        __(
4097
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4098
-                            'event_espresso'
4099
-                        ),
4100
-                        "BETWEEN"
4101
-                    )
4102
-                );
4103
-            }
4104
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4105
-            return $operator . SP . $cleaned_value;
4106
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4107
-            if ($value !== null) {
4108
-                throw new EE_Error(
4109
-                    sprintf(
4110
-                        __(
4111
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4112
-                            "event_espresso"
4113
-                        ),
4114
-                        $value,
4115
-                        $operator
4116
-                    )
4117
-                );
4118
-            }
4119
-            return $operator;
4120
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4121
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4122
-            //remove other junk. So just treat it as a string.
4123
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4124
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4125
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4126
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4127
-            throw new EE_Error(
4128
-                sprintf(
4129
-                    __(
4130
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4131
-                        'event_espresso'
4132
-                    ),
4133
-                    $operator,
4134
-                    $operator
4135
-                )
4136
-            );
4137
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4138
-            throw new EE_Error(
4139
-                sprintf(
4140
-                    __(
4141
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4142
-                        'event_espresso'
4143
-                    ),
4144
-                    $operator,
4145
-                    $operator
4146
-                )
4147
-            );
4148
-        } else {
4149
-            throw new EE_Error(
4150
-                sprintf(
4151
-                    __(
4152
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4153
-                        "event_espresso"
4154
-                    ),
4155
-                    http_build_query($op_and_value)
4156
-                )
4157
-            );
4158
-        }
4159
-    }
4160
-
4161
-
4162
-
4163
-    /**
4164
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4165
-     *
4166
-     * @param array                      $values
4167
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4168
-     *                                              '%s'
4169
-     * @return string
4170
-     * @throws \EE_Error
4171
-     */
4172
-    public function _construct_between_value($values, $field_obj)
4173
-    {
4174
-        $cleaned_values = array();
4175
-        foreach ($values as $value) {
4176
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4177
-        }
4178
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4179
-    }
4180
-
4181
-
4182
-
4183
-    /**
4184
-     * Takes an array or a comma-separated list of $values and cleans them
4185
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4186
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4187
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4188
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4189
-     *
4190
-     * @param mixed                      $values    array or comma-separated string
4191
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4192
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4193
-     * @throws \EE_Error
4194
-     */
4195
-    public function _construct_in_value($values, $field_obj)
4196
-    {
4197
-        //check if the value is a CSV list
4198
-        if (is_string($values)) {
4199
-            //in which case, turn it into an array
4200
-            $values = explode(",", $values);
4201
-        }
4202
-        $cleaned_values = array();
4203
-        foreach ($values as $value) {
4204
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4205
-        }
4206
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4207
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4208
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4209
-        if (empty($cleaned_values)) {
4210
-            $all_fields = $this->field_settings();
4211
-            $a_field = array_shift($all_fields);
4212
-            $main_table = $this->_get_main_table();
4213
-            $cleaned_values[] = "SELECT "
4214
-                                . $a_field->get_table_column()
4215
-                                . " FROM "
4216
-                                . $main_table->get_table_name()
4217
-                                . " WHERE FALSE";
4218
-        }
4219
-        return "(" . implode(",", $cleaned_values) . ")";
4220
-    }
4221
-
4222
-
4223
-
4224
-    /**
4225
-     * @param mixed                      $value
4226
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4227
-     * @throws EE_Error
4228
-     * @return false|null|string
4229
-     */
4230
-    private function _wpdb_prepare_using_field($value, $field_obj)
4231
-    {
4232
-        /** @type WPDB $wpdb */
4233
-        global $wpdb;
4234
-        if ($field_obj instanceof EE_Model_Field_Base) {
4235
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4236
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4237
-        } else {//$field_obj should really just be a data type
4238
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4239
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4240
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4241
-            }
4242
-            return $wpdb->prepare($field_obj, $value);
4243
-        }
4244
-    }
4245
-
4246
-
4247
-
4248
-    /**
4249
-     * Takes the input parameter and finds the model field that it indicates.
4250
-     *
4251
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4252
-     * @throws EE_Error
4253
-     * @return EE_Model_Field_Base
4254
-     */
4255
-    protected function _deduce_field_from_query_param($query_param_name)
4256
-    {
4257
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4258
-        //which will help us find the database table and column
4259
-        $query_param_parts = explode(".", $query_param_name);
4260
-        if (empty($query_param_parts)) {
4261
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4262
-                'event_espresso'), $query_param_name));
4263
-        }
4264
-        $number_of_parts = count($query_param_parts);
4265
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4266
-        if ($number_of_parts === 1) {
4267
-            $field_name = $last_query_param_part;
4268
-            $model_obj = $this;
4269
-        } else {// $number_of_parts >= 2
4270
-            //the last part is the column name, and there are only 2parts. therefore...
4271
-            $field_name = $last_query_param_part;
4272
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4273
-        }
4274
-        try {
4275
-            return $model_obj->field_settings_for($field_name);
4276
-        } catch (EE_Error $e) {
4277
-            return null;
4278
-        }
4279
-    }
4280
-
4281
-
4282
-
4283
-    /**
4284
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4285
-     * alias and column which corresponds to it
4286
-     *
4287
-     * @param string $field_name
4288
-     * @throws EE_Error
4289
-     * @return string
4290
-     */
4291
-    public function _get_qualified_column_for_field($field_name)
4292
-    {
4293
-        $all_fields = $this->field_settings();
4294
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4295
-        if ($field) {
4296
-            return $field->get_qualified_column();
4297
-        } else {
4298
-            throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4299
-                'event_espresso'), $field_name, get_class($this)));
4300
-        }
4301
-    }
4302
-
4303
-
4304
-
4305
-    /**
4306
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4307
-     * Example usage:
4308
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4309
-     *      array(),
4310
-     *      ARRAY_A,
4311
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4312
-     *  );
4313
-     * is equivalent to
4314
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4315
-     * and
4316
-     *  EEM_Event::instance()->get_all_wpdb_results(
4317
-     *      array(
4318
-     *          array(
4319
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4320
-     *          ),
4321
-     *          ARRAY_A,
4322
-     *          implode(
4323
-     *              ', ',
4324
-     *              array_merge(
4325
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4326
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4327
-     *              )
4328
-     *          )
4329
-     *      )
4330
-     *  );
4331
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4332
-     *
4333
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4334
-     *                                            and the one whose fields you are selecting for example: when querying
4335
-     *                                            tickets model and selecting fields from the tickets model you would
4336
-     *                                            leave this parameter empty, because no models are needed to join
4337
-     *                                            between the queried model and the selected one. Likewise when
4338
-     *                                            querying the datetime model and selecting fields from the tickets
4339
-     *                                            model, it would also be left empty, because there is a direct
4340
-     *                                            relation from datetimes to tickets, so no model is needed to join
4341
-     *                                            them together. However, when querying from the event model and
4342
-     *                                            selecting fields from the ticket model, you should provide the string
4343
-     *                                            'Datetime', indicating that the event model must first join to the
4344
-     *                                            datetime model in order to find its relation to ticket model.
4345
-     *                                            Also, when querying from the venue model and selecting fields from
4346
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4347
-     *                                            indicating you need to join the venue model to the event model,
4348
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4349
-     *                                            This string is used to deduce the prefix that gets added onto the
4350
-     *                                            models' tables qualified columns
4351
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4352
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4353
-     *                                            qualified column names
4354
-     * @return array|string
4355
-     */
4356
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4357
-    {
4358
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4359
-        $qualified_columns = array();
4360
-        foreach ($this->field_settings() as $field_name => $field) {
4361
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4362
-        }
4363
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4364
-    }
4365
-
4366
-
4367
-
4368
-    /**
4369
-     * constructs the select use on special limit joins
4370
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4371
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4372
-     * (as that is typically where the limits would be set).
4373
-     *
4374
-     * @param  string       $table_alias The table the select is being built for
4375
-     * @param  mixed|string $limit       The limit for this select
4376
-     * @return string                The final select join element for the query.
4377
-     */
4378
-    public function _construct_limit_join_select($table_alias, $limit)
4379
-    {
4380
-        $SQL = '';
4381
-        foreach ($this->_tables as $table_obj) {
4382
-            if ($table_obj instanceof EE_Primary_Table) {
4383
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4384
-                    ? $table_obj->get_select_join_limit($limit)
4385
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4386
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4387
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4388
-                    ? $table_obj->get_select_join_limit_join($limit)
4389
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4390
-            }
4391
-        }
4392
-        return $SQL;
4393
-    }
4394
-
4395
-
4396
-
4397
-    /**
4398
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4399
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4400
-     *
4401
-     * @return string SQL
4402
-     * @throws \EE_Error
4403
-     */
4404
-    public function _construct_internal_join()
4405
-    {
4406
-        $SQL = $this->_get_main_table()->get_table_sql();
4407
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4408
-        return $SQL;
4409
-    }
4410
-
4411
-
4412
-
4413
-    /**
4414
-     * Constructs the SQL for joining all the tables on this model.
4415
-     * Normally $alias should be the primary table's alias, but in cases where
4416
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4417
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4418
-     * alias, this will construct SQL like:
4419
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4420
-     * With $alias being a secondary table's alias, this will construct SQL like:
4421
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4422
-     *
4423
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4424
-     * @return string
4425
-     */
4426
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4427
-    {
4428
-        $SQL = '';
4429
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4430
-        foreach ($this->_tables as $table_obj) {
4431
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4432
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4433
-                    //so we're joining to this table, meaning the table is already in
4434
-                    //the FROM statement, BUT the primary table isn't. So we want
4435
-                    //to add the inverse join sql
4436
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4437
-                } else {
4438
-                    //just add a regular JOIN to this table from the primary table
4439
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4440
-                }
4441
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4442
-        }
4443
-        return $SQL;
4444
-    }
4445
-
4446
-
4447
-
4448
-    /**
4449
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4450
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4451
-     * their data type (eg, '%s', '%d', etc)
4452
-     *
4453
-     * @return array
4454
-     */
4455
-    public function _get_data_types()
4456
-    {
4457
-        $data_types = array();
4458
-        foreach ($this->field_settings() as $field_obj) {
4459
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4460
-            /** @var $field_obj EE_Model_Field_Base */
4461
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4462
-        }
4463
-        return $data_types;
4464
-    }
4465
-
4466
-
4467
-
4468
-    /**
4469
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4470
-     *
4471
-     * @param string $model_name
4472
-     * @throws EE_Error
4473
-     * @return EEM_Base
4474
-     */
4475
-    public function get_related_model_obj($model_name)
4476
-    {
4477
-        $model_classname = "EEM_" . $model_name;
4478
-        if (! class_exists($model_classname)) {
4479
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4480
-                'event_espresso'), $model_name, $model_classname));
4481
-        }
4482
-        return call_user_func($model_classname . "::instance");
4483
-    }
4484
-
4485
-
4486
-
4487
-    /**
4488
-     * Returns the array of EE_ModelRelations for this model.
4489
-     *
4490
-     * @return EE_Model_Relation_Base[]
4491
-     */
4492
-    public function relation_settings()
4493
-    {
4494
-        return $this->_model_relations;
4495
-    }
4496
-
4497
-
4498
-
4499
-    /**
4500
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4501
-     * because without THOSE models, this model probably doesn't have much purpose.
4502
-     * (Eg, without an event, datetimes have little purpose.)
4503
-     *
4504
-     * @return EE_Belongs_To_Relation[]
4505
-     */
4506
-    public function belongs_to_relations()
4507
-    {
4508
-        $belongs_to_relations = array();
4509
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4510
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4511
-                $belongs_to_relations[$model_name] = $relation_obj;
4512
-            }
4513
-        }
4514
-        return $belongs_to_relations;
4515
-    }
4516
-
4517
-
4518
-
4519
-    /**
4520
-     * Returns the specified EE_Model_Relation, or throws an exception
4521
-     *
4522
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4523
-     * @throws EE_Error
4524
-     * @return EE_Model_Relation_Base
4525
-     */
4526
-    public function related_settings_for($relation_name)
4527
-    {
4528
-        $relatedModels = $this->relation_settings();
4529
-        if (! array_key_exists($relation_name, $relatedModels)) {
4530
-            throw new EE_Error(
4531
-                sprintf(
4532
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4533
-                        'event_espresso'),
4534
-                    $relation_name,
4535
-                    $this->_get_class_name(),
4536
-                    implode(', ', array_keys($relatedModels))
4537
-                )
4538
-            );
4539
-        }
4540
-        return $relatedModels[$relation_name];
4541
-    }
4542
-
4543
-
4544
-
4545
-    /**
4546
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4547
-     * fields
4548
-     *
4549
-     * @param string $fieldName
4550
-     * @throws EE_Error
4551
-     * @return EE_Model_Field_Base
4552
-     */
4553
-    public function field_settings_for($fieldName)
4554
-    {
4555
-        $fieldSettings = $this->field_settings(true);
4556
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4557
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4558
-                get_class($this)));
4559
-        }
4560
-        return $fieldSettings[$fieldName];
4561
-    }
4562
-
4563
-
4564
-
4565
-    /**
4566
-     * Checks if this field exists on this model
4567
-     *
4568
-     * @param string $fieldName a key in the model's _field_settings array
4569
-     * @return boolean
4570
-     */
4571
-    public function has_field($fieldName)
4572
-    {
4573
-        $fieldSettings = $this->field_settings(true);
4574
-        if (isset($fieldSettings[$fieldName])) {
4575
-            return true;
4576
-        } else {
4577
-            return false;
4578
-        }
4579
-    }
4580
-
4581
-
4582
-
4583
-    /**
4584
-     * Returns whether or not this model has a relation to the specified model
4585
-     *
4586
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4587
-     * @return boolean
4588
-     */
4589
-    public function has_relation($relation_name)
4590
-    {
4591
-        $relations = $this->relation_settings();
4592
-        if (isset($relations[$relation_name])) {
4593
-            return true;
4594
-        } else {
4595
-            return false;
4596
-        }
4597
-    }
4598
-
4599
-
4600
-
4601
-    /**
4602
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4603
-     * Eg, on EE_Answer that would be ANS_ID field object
4604
-     *
4605
-     * @param $field_obj
4606
-     * @return boolean
4607
-     */
4608
-    public function is_primary_key_field($field_obj)
4609
-    {
4610
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4611
-    }
4612
-
4613
-
4614
-
4615
-    /**
4616
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4617
-     * Eg, on EE_Answer that would be ANS_ID field object
4618
-     *
4619
-     * @return EE_Model_Field_Base
4620
-     * @throws EE_Error
4621
-     */
4622
-    public function get_primary_key_field()
4623
-    {
4624
-        if ($this->_primary_key_field === null) {
4625
-            foreach ($this->field_settings(true) as $field_obj) {
4626
-                if ($this->is_primary_key_field($field_obj)) {
4627
-                    $this->_primary_key_field = $field_obj;
4628
-                    break;
4629
-                }
4630
-            }
4631
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4632
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4633
-                    get_class($this)));
4634
-            }
4635
-        }
4636
-        return $this->_primary_key_field;
4637
-    }
4638
-
4639
-
4640
-
4641
-    /**
4642
-     * Returns whether or not not there is a primary key on this model.
4643
-     * Internally does some caching.
4644
-     *
4645
-     * @return boolean
4646
-     */
4647
-    public function has_primary_key_field()
4648
-    {
4649
-        if ($this->_has_primary_key_field === null) {
4650
-            try {
4651
-                $this->get_primary_key_field();
4652
-                $this->_has_primary_key_field = true;
4653
-            } catch (EE_Error $e) {
4654
-                $this->_has_primary_key_field = false;
4655
-            }
4656
-        }
4657
-        return $this->_has_primary_key_field;
4658
-    }
4659
-
4660
-
4661
-
4662
-    /**
4663
-     * Finds the first field of type $field_class_name.
4664
-     *
4665
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4666
-     *                                 EE_Foreign_Key_Field, etc
4667
-     * @return EE_Model_Field_Base or null if none is found
4668
-     */
4669
-    public function get_a_field_of_type($field_class_name)
4670
-    {
4671
-        foreach ($this->field_settings() as $field) {
4672
-            if ($field instanceof $field_class_name) {
4673
-                return $field;
4674
-            }
4675
-        }
4676
-        return null;
4677
-    }
4678
-
4679
-
4680
-
4681
-    /**
4682
-     * Gets a foreign key field pointing to model.
4683
-     *
4684
-     * @param string $model_name eg Event, Registration, not EEM_Event
4685
-     * @return EE_Foreign_Key_Field_Base
4686
-     * @throws EE_Error
4687
-     */
4688
-    public function get_foreign_key_to($model_name)
4689
-    {
4690
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4691
-            foreach ($this->field_settings() as $field) {
4692
-                if (
4693
-                    $field instanceof EE_Foreign_Key_Field_Base
4694
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4695
-                ) {
4696
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4697
-                    break;
4698
-                }
4699
-            }
4700
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4701
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4702
-                    'event_espresso'), $model_name, get_class($this)));
4703
-            }
4704
-        }
4705
-        return $this->_cache_foreign_key_to_fields[$model_name];
4706
-    }
4707
-
4708
-
4709
-
4710
-    /**
4711
-     * Gets the actual table for the table alias
4712
-     *
4713
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4714
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4715
-     *                            Either one works
4716
-     * @return EE_Table_Base
4717
-     */
4718
-    public function get_table_for_alias($table_alias)
4719
-    {
4720
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4721
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4722
-    }
4723
-
4724
-
4725
-
4726
-    /**
4727
-     * Returns a flat array of all field son this model, instead of organizing them
4728
-     * by table_alias as they are in the constructor.
4729
-     *
4730
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4731
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4732
-     */
4733
-    public function field_settings($include_db_only_fields = false)
4734
-    {
4735
-        if ($include_db_only_fields) {
4736
-            if ($this->_cached_fields === null) {
4737
-                $this->_cached_fields = array();
4738
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4739
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4740
-                        $this->_cached_fields[$field_name] = $field_obj;
4741
-                    }
4742
-                }
4743
-            }
4744
-            return $this->_cached_fields;
4745
-        } else {
4746
-            if ($this->_cached_fields_non_db_only === null) {
4747
-                $this->_cached_fields_non_db_only = array();
4748
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4749
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4750
-                        /** @var $field_obj EE_Model_Field_Base */
4751
-                        if (! $field_obj->is_db_only_field()) {
4752
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4753
-                        }
4754
-                    }
4755
-                }
4756
-            }
4757
-            return $this->_cached_fields_non_db_only;
4758
-        }
4759
-    }
4760
-
4761
-
4762
-
4763
-    /**
4764
-     *        cycle though array of attendees and create objects out of each item
4765
-     *
4766
-     * @access        private
4767
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4768
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4769
-     *                           numerically indexed)
4770
-     * @throws \EE_Error
4771
-     */
4772
-    protected function _create_objects($rows = array())
4773
-    {
4774
-        $array_of_objects = array();
4775
-        if (empty($rows)) {
4776
-            return array();
4777
-        }
4778
-        $count_if_model_has_no_primary_key = 0;
4779
-        $has_primary_key = $this->has_primary_key_field();
4780
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4781
-        foreach ((array)$rows as $row) {
4782
-            if (empty($row)) {
4783
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4784
-                return array();
4785
-            }
4786
-            //check if we've already set this object in the results array,
4787
-            //in which case there's no need to process it further (again)
4788
-            if ($has_primary_key) {
4789
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4790
-                    $row,
4791
-                    $primary_key_field->get_qualified_column(),
4792
-                    $primary_key_field->get_table_column()
4793
-                );
4794
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4795
-                    continue;
4796
-                }
4797
-            }
4798
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4799
-            if (! $classInstance) {
4800
-                throw new EE_Error(
4801
-                    sprintf(
4802
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4803
-                        $this->get_this_model_name(),
4804
-                        http_build_query($row)
4805
-                    )
4806
-                );
4807
-            }
4808
-            //set the timezone on the instantiated objects
4809
-            $classInstance->set_timezone($this->_timezone);
4810
-            //make sure if there is any timezone setting present that we set the timezone for the object
4811
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4812
-            $array_of_objects[$key] = $classInstance;
4813
-            //also, for all the relations of type BelongsTo, see if we can cache
4814
-            //those related models
4815
-            //(we could do this for other relations too, but if there are conditions
4816
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4817
-            //so it requires a little more thought than just caching them immediately...)
4818
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4819
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4820
-                    //check if this model's INFO is present. If so, cache it on the model
4821
-                    $other_model = $relation_obj->get_other_model();
4822
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4823
-                    //if we managed to make a model object from the results, cache it on the main model object
4824
-                    if ($other_model_obj_maybe) {
4825
-                        //set timezone on these other model objects if they are present
4826
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4827
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4828
-                    }
4829
-                }
4830
-            }
4831
-        }
4832
-        return $array_of_objects;
4833
-    }
4834
-
4835
-
4836
-
4837
-    /**
4838
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4839
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4840
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4841
-     * object (as set in the model_field!).
4842
-     *
4843
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4844
-     */
4845
-    public function create_default_object()
4846
-    {
4847
-        $this_model_fields_and_values = array();
4848
-        //setup the row using default values;
4849
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4850
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4851
-        }
4852
-        $className = $this->_get_class_name();
4853
-        $classInstance = EE_Registry::instance()
4854
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4855
-        return $classInstance;
4856
-    }
4857
-
4858
-
4859
-
4860
-    /**
4861
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4862
-     *                             or an stdClass where each property is the name of a column,
4863
-     * @return EE_Base_Class
4864
-     * @throws \EE_Error
4865
-     */
4866
-    public function instantiate_class_from_array_or_object($cols_n_values)
4867
-    {
4868
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4869
-            $cols_n_values = get_object_vars($cols_n_values);
4870
-        }
4871
-        $primary_key = null;
4872
-        //make sure the array only has keys that are fields/columns on this model
4873
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4874
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4875
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4876
-        }
4877
-        $className = $this->_get_class_name();
4878
-        //check we actually found results that we can use to build our model object
4879
-        //if not, return null
4880
-        if ($this->has_primary_key_field()) {
4881
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4882
-                return null;
4883
-            }
4884
-        } else if ($this->unique_indexes()) {
4885
-            $first_column = reset($this_model_fields_n_values);
4886
-            if (empty($first_column)) {
4887
-                return null;
4888
-            }
4889
-        }
4890
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4891
-        if ($primary_key) {
4892
-            $classInstance = $this->get_from_entity_map($primary_key);
4893
-            if (! $classInstance) {
4894
-                $classInstance = EE_Registry::instance()
4895
-                                            ->load_class($className,
4896
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4897
-                // add this new object to the entity map
4898
-                $classInstance = $this->add_to_entity_map($classInstance);
4899
-            }
4900
-        } else {
4901
-            $classInstance = EE_Registry::instance()
4902
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4903
-                                            true, false);
4904
-        }
4905
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4906
-        $this->set_timezone($classInstance->get_timezone());
4907
-        return $classInstance;
4908
-    }
4909
-
4910
-
4911
-
4912
-    /**
4913
-     * Gets the model object from the  entity map if it exists
4914
-     *
4915
-     * @param int|string $id the ID of the model object
4916
-     * @return EE_Base_Class
4917
-     */
4918
-    public function get_from_entity_map($id)
4919
-    {
4920
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4921
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4922
-    }
4923
-
4924
-
4925
-
4926
-    /**
4927
-     * add_to_entity_map
4928
-     * Adds the object to the model's entity mappings
4929
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4930
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4931
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4932
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4933
-     *        then this method should be called immediately after the update query
4934
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4935
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4936
-     *
4937
-     * @param    EE_Base_Class $object
4938
-     * @throws EE_Error
4939
-     * @return \EE_Base_Class
4940
-     */
4941
-    public function add_to_entity_map(EE_Base_Class $object)
4942
-    {
4943
-        $className = $this->_get_class_name();
4944
-        if (! $object instanceof $className) {
4945
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4946
-                is_object($object) ? get_class($object) : $object, $className));
4947
-        }
4948
-        /** @var $object EE_Base_Class */
4949
-        if (! $object->ID()) {
4950
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4951
-                "event_espresso"), get_class($this)));
4952
-        }
4953
-        // double check it's not already there
4954
-        $classInstance = $this->get_from_entity_map($object->ID());
4955
-        if ($classInstance) {
4956
-            return $classInstance;
4957
-        } else {
4958
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4959
-            return $object;
4960
-        }
4961
-    }
4962
-
4963
-
4964
-
4965
-    /**
4966
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4967
-     * if no identifier is provided, then the entire entity map is emptied
4968
-     *
4969
-     * @param int|string $id the ID of the model object
4970
-     * @return boolean
4971
-     */
4972
-    public function clear_entity_map($id = null)
4973
-    {
4974
-        if (empty($id)) {
4975
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4976
-            return true;
4977
-        }
4978
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4979
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4980
-            return true;
4981
-        }
4982
-        return false;
4983
-    }
4984
-
4985
-
4986
-
4987
-    /**
4988
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4989
-     * Given an array where keys are column (or column alias) names and values,
4990
-     * returns an array of their corresponding field names and database values
4991
-     *
4992
-     * @param array $cols_n_values
4993
-     * @return array
4994
-     */
4995
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4996
-    {
4997
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4998
-    }
4999
-
5000
-
5001
-
5002
-    /**
5003
-     * _deduce_fields_n_values_from_cols_n_values
5004
-     * Given an array where keys are column (or column alias) names and values,
5005
-     * returns an array of their corresponding field names and database values
5006
-     *
5007
-     * @param string $cols_n_values
5008
-     * @return array
5009
-     */
5010
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5011
-    {
5012
-        $this_model_fields_n_values = array();
5013
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5014
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5015
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5016
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5017
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5018
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5019
-                    if (! $field_obj->is_db_only_field()) {
5020
-                        //prepare field as if its coming from db
5021
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5022
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5023
-                    }
5024
-                }
5025
-            } else {
5026
-                //the table's rows existed. Use their values
5027
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5028
-                    if (! $field_obj->is_db_only_field()) {
5029
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5030
-                            $cols_n_values, $field_obj->get_qualified_column(),
5031
-                            $field_obj->get_table_column()
5032
-                        );
5033
-                    }
5034
-                }
5035
-            }
5036
-        }
5037
-        return $this_model_fields_n_values;
5038
-    }
5039
-
5040
-
5041
-
5042
-    /**
5043
-     * @param $cols_n_values
5044
-     * @param $qualified_column
5045
-     * @param $regular_column
5046
-     * @return null
5047
-     */
5048
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5049
-    {
5050
-        $value = null;
5051
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5052
-        //does the field on the model relate to this column retrieved from the db?
5053
-        //or is it a db-only field? (not relating to the model)
5054
-        if (isset($cols_n_values[$qualified_column])) {
5055
-            $value = $cols_n_values[$qualified_column];
5056
-        } elseif (isset($cols_n_values[$regular_column])) {
5057
-            $value = $cols_n_values[$regular_column];
5058
-        }
5059
-        return $value;
5060
-    }
5061
-
5062
-
5063
-
5064
-    /**
5065
-     * refresh_entity_map_from_db
5066
-     * Makes sure the model object in the entity map at $id assumes the values
5067
-     * of the database (opposite of EE_base_Class::save())
5068
-     *
5069
-     * @param int|string $id
5070
-     * @return EE_Base_Class
5071
-     * @throws \EE_Error
5072
-     */
5073
-    public function refresh_entity_map_from_db($id)
5074
-    {
5075
-        $obj_in_map = $this->get_from_entity_map($id);
5076
-        if ($obj_in_map) {
5077
-            $wpdb_results = $this->_get_all_wpdb_results(
5078
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5079
-            );
5080
-            if ($wpdb_results && is_array($wpdb_results)) {
5081
-                $one_row = reset($wpdb_results);
5082
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5083
-                    $obj_in_map->set_from_db($field_name, $db_value);
5084
-                }
5085
-                //clear the cache of related model objects
5086
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5087
-                    $obj_in_map->clear_cache($relation_name, null, true);
5088
-                }
5089
-            }
5090
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5091
-            return $obj_in_map;
5092
-        } else {
5093
-            return $this->get_one_by_ID($id);
5094
-        }
5095
-    }
5096
-
5097
-
5098
-
5099
-    /**
5100
-     * refresh_entity_map_with
5101
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5102
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5103
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5104
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5105
-     *
5106
-     * @param int|string    $id
5107
-     * @param EE_Base_Class $replacing_model_obj
5108
-     * @return \EE_Base_Class
5109
-     * @throws \EE_Error
5110
-     */
5111
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5112
-    {
5113
-        $obj_in_map = $this->get_from_entity_map($id);
5114
-        if ($obj_in_map) {
5115
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5116
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5117
-                    $obj_in_map->set($field_name, $value);
5118
-                }
5119
-                //make the model object in the entity map's cache match the $replacing_model_obj
5120
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5121
-                    $obj_in_map->clear_cache($relation_name, null, true);
5122
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5123
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5124
-                    }
5125
-                }
5126
-            }
5127
-            return $obj_in_map;
5128
-        } else {
5129
-            $this->add_to_entity_map($replacing_model_obj);
5130
-            return $replacing_model_obj;
5131
-        }
5132
-    }
5133
-
5134
-
5135
-
5136
-    /**
5137
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5138
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5139
-     * require_once($this->_getClassName().".class.php");
5140
-     *
5141
-     * @return string
5142
-     */
5143
-    private function _get_class_name()
5144
-    {
5145
-        return "EE_" . $this->get_this_model_name();
5146
-    }
5147
-
5148
-
5149
-
5150
-    /**
5151
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5152
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5153
-     * it would be 'Events'.
5154
-     *
5155
-     * @param int $quantity
5156
-     * @return string
5157
-     */
5158
-    public function item_name($quantity = 1)
5159
-    {
5160
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5161
-    }
5162
-
5163
-
5164
-
5165
-    /**
5166
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5167
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5168
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5169
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5170
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5171
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5172
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5173
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5174
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5175
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5176
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5177
-     *        return $previousReturnValue.$returnString;
5178
-     * }
5179
-     * require('EEM_Answer.model.php');
5180
-     * $answer=EEM_Answer::instance();
5181
-     * echo $answer->my_callback('monkeys',100);
5182
-     * //will output "you called my_callback! and passed args:monkeys,100"
5183
-     *
5184
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5185
-     * @param array  $args       array of original arguments passed to the function
5186
-     * @throws EE_Error
5187
-     * @return mixed whatever the plugin which calls add_filter decides
5188
-     */
5189
-    public function __call($methodName, $args)
5190
-    {
5191
-        $className = get_class($this);
5192
-        $tagName = "FHEE__{$className}__{$methodName}";
5193
-        if (! has_filter($tagName)) {
5194
-            throw new EE_Error(
5195
-                sprintf(
5196
-                    __('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 );',
5197
-                        'event_espresso'),
5198
-                    $methodName,
5199
-                    $className,
5200
-                    $tagName,
5201
-                    '<br />'
5202
-                )
5203
-            );
5204
-        }
5205
-        return apply_filters($tagName, null, $this, $args);
5206
-    }
5207
-
5208
-
5209
-
5210
-    /**
5211
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5212
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5213
-     *
5214
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5215
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5216
-     *                                                       the object's class name
5217
-     *                                                       or object's ID
5218
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5219
-     *                                                       exists in the database. If it does not, we add it
5220
-     * @throws EE_Error
5221
-     * @return EE_Base_Class
5222
-     */
5223
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5224
-    {
5225
-        $className = $this->_get_class_name();
5226
-        if ($base_class_obj_or_id instanceof $className) {
5227
-            $model_object = $base_class_obj_or_id;
5228
-        } else {
5229
-            $primary_key_field = $this->get_primary_key_field();
5230
-            if (
5231
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5232
-                && (
5233
-                    is_int($base_class_obj_or_id)
5234
-                    || is_string($base_class_obj_or_id)
5235
-                )
5236
-            ) {
5237
-                // assume it's an ID.
5238
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5239
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5240
-            } else if (
5241
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5242
-                && is_string($base_class_obj_or_id)
5243
-            ) {
5244
-                // assume its a string representation of the object
5245
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5246
-            } else {
5247
-                throw new EE_Error(
5248
-                    sprintf(
5249
-                        __(
5250
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5251
-                            'event_espresso'
5252
-                        ),
5253
-                        $base_class_obj_or_id,
5254
-                        $this->_get_class_name(),
5255
-                        print_r($base_class_obj_or_id, true)
5256
-                    )
5257
-                );
5258
-            }
5259
-        }
5260
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5261
-            $model_object->save();
5262
-        }
5263
-        return $model_object;
5264
-    }
5265
-
5266
-
5267
-
5268
-    /**
5269
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5270
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5271
-     * returns it ID.
5272
-     *
5273
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5274
-     * @return int|string depending on the type of this model object's ID
5275
-     * @throws EE_Error
5276
-     */
5277
-    public function ensure_is_ID($base_class_obj_or_id)
5278
-    {
5279
-        $className = $this->_get_class_name();
5280
-        if ($base_class_obj_or_id instanceof $className) {
5281
-            /** @var $base_class_obj_or_id EE_Base_Class */
5282
-            $id = $base_class_obj_or_id->ID();
5283
-        } elseif (is_int($base_class_obj_or_id)) {
5284
-            //assume it's an ID
5285
-            $id = $base_class_obj_or_id;
5286
-        } elseif (is_string($base_class_obj_or_id)) {
5287
-            //assume its a string representation of the object
5288
-            $id = $base_class_obj_or_id;
5289
-        } else {
5290
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5291
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5292
-                print_r($base_class_obj_or_id, true)));
5293
-        }
5294
-        return $id;
5295
-    }
5296
-
5297
-
5298
-
5299
-    /**
5300
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5301
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5302
-     * been sanitized and converted into the appropriate domain.
5303
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5304
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5305
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5306
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5307
-     * $EVT = EEM_Event::instance(); $old_setting =
5308
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5309
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5310
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5311
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5312
-     *
5313
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5314
-     * @return void
5315
-     */
5316
-    public function assume_values_already_prepared_by_model_object(
5317
-        $values_already_prepared = self::not_prepared_by_model_object
5318
-    ) {
5319
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5320
-    }
5321
-
5322
-
5323
-
5324
-    /**
5325
-     * Read comments for assume_values_already_prepared_by_model_object()
5326
-     *
5327
-     * @return int
5328
-     */
5329
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5330
-    {
5331
-        return $this->_values_already_prepared_by_model_object;
5332
-    }
5333
-
5334
-
5335
-
5336
-    /**
5337
-     * Gets all the indexes on this model
5338
-     *
5339
-     * @return EE_Index[]
5340
-     */
5341
-    public function indexes()
5342
-    {
5343
-        return $this->_indexes;
5344
-    }
5345
-
5346
-
5347
-
5348
-    /**
5349
-     * Gets all the Unique Indexes on this model
5350
-     *
5351
-     * @return EE_Unique_Index[]
5352
-     */
5353
-    public function unique_indexes()
5354
-    {
5355
-        $unique_indexes = array();
5356
-        foreach ($this->_indexes as $name => $index) {
5357
-            if ($index instanceof EE_Unique_Index) {
5358
-                $unique_indexes [$name] = $index;
5359
-            }
5360
-        }
5361
-        return $unique_indexes;
5362
-    }
5363
-
5364
-
5365
-
5366
-    /**
5367
-     * Gets all the fields which, when combined, make the primary key.
5368
-     * This is usually just an array with 1 element (the primary key), but in cases
5369
-     * where there is no primary key, it's a combination of fields as defined
5370
-     * on a primary index
5371
-     *
5372
-     * @return EE_Model_Field_Base[] indexed by the field's name
5373
-     * @throws \EE_Error
5374
-     */
5375
-    public function get_combined_primary_key_fields()
5376
-    {
5377
-        foreach ($this->indexes() as $index) {
5378
-            if ($index instanceof EE_Primary_Key_Index) {
5379
-                return $index->fields();
5380
-            }
5381
-        }
5382
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5383
-    }
5384
-
5385
-
5386
-
5387
-    /**
5388
-     * Used to build a primary key string (when the model has no primary key),
5389
-     * which can be used a unique string to identify this model object.
5390
-     *
5391
-     * @param array $cols_n_values keys are field names, values are their values
5392
-     * @return string
5393
-     * @throws \EE_Error
5394
-     */
5395
-    public function get_index_primary_key_string($cols_n_values)
5396
-    {
5397
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5398
-            $this->get_combined_primary_key_fields());
5399
-        return http_build_query($cols_n_values_for_primary_key_index);
5400
-    }
5401
-
5402
-
5403
-
5404
-    /**
5405
-     * Gets the field values from the primary key string
5406
-     *
5407
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5408
-     * @param string $index_primary_key_string
5409
-     * @return null|array
5410
-     * @throws \EE_Error
5411
-     */
5412
-    public function parse_index_primary_key_string($index_primary_key_string)
5413
-    {
5414
-        $key_fields = $this->get_combined_primary_key_fields();
5415
-        //check all of them are in the $id
5416
-        $key_vals_in_combined_pk = array();
5417
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5418
-        foreach ($key_fields as $key_field_name => $field_obj) {
5419
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5420
-                return null;
5421
-            }
5422
-        }
5423
-        return $key_vals_in_combined_pk;
5424
-    }
5425
-
5426
-
5427
-
5428
-    /**
5429
-     * verifies that an array of key-value pairs for model fields has a key
5430
-     * for each field comprising the primary key index
5431
-     *
5432
-     * @param array $key_vals
5433
-     * @return boolean
5434
-     * @throws \EE_Error
5435
-     */
5436
-    public function has_all_combined_primary_key_fields($key_vals)
5437
-    {
5438
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5439
-        foreach ($keys_it_should_have as $key) {
5440
-            if (! isset($key_vals[$key])) {
5441
-                return false;
5442
-            }
5443
-        }
5444
-        return true;
5445
-    }
5446
-
5447
-
5448
-
5449
-    /**
5450
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5451
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5452
-     *
5453
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5454
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5455
-     * @throws EE_Error
5456
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5457
-     *                                                              indexed)
5458
-     */
5459
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5460
-    {
5461
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5462
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5463
-        } elseif (is_array($model_object_or_attributes_array)) {
5464
-            $attributes_array = $model_object_or_attributes_array;
5465
-        } else {
5466
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5467
-                "event_espresso"), $model_object_or_attributes_array));
5468
-        }
5469
-        //even copies obviously won't have the same ID, so remove the primary key
5470
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5471
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5472
-            unset($attributes_array[$this->primary_key_name()]);
5473
-        }
5474
-        if (isset($query_params[0])) {
5475
-            $query_params[0] = array_merge($attributes_array, $query_params);
5476
-        } else {
5477
-            $query_params[0] = $attributes_array;
5478
-        }
5479
-        return $this->get_all($query_params);
5480
-    }
5481
-
5482
-
5483
-
5484
-    /**
5485
-     * Gets the first copy we find. See get_all_copies for more details
5486
-     *
5487
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5488
-     * @param array $query_params
5489
-     * @return EE_Base_Class
5490
-     * @throws \EE_Error
5491
-     */
5492
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5493
-    {
5494
-        if (! is_array($query_params)) {
5495
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5496
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5497
-                    gettype($query_params)), '4.6.0');
5498
-            $query_params = array();
5499
-        }
5500
-        $query_params['limit'] = 1;
5501
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5502
-        if (is_array($copies)) {
5503
-            return array_shift($copies);
5504
-        } else {
5505
-            return null;
5506
-        }
5507
-    }
5508
-
5509
-
5510
-
5511
-    /**
5512
-     * Updates the item with the specified id. Ignores default query parameters because
5513
-     * we have specified the ID, and its assumed we KNOW what we're doing
5514
-     *
5515
-     * @param array      $fields_n_values keys are field names, values are their new values
5516
-     * @param int|string $id              the value of the primary key to update
5517
-     * @return int number of rows updated
5518
-     * @throws \EE_Error
5519
-     */
5520
-    public function update_by_ID($fields_n_values, $id)
5521
-    {
5522
-        $query_params = array(
5523
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5524
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5525
-        );
5526
-        return $this->update($fields_n_values, $query_params);
5527
-    }
5528
-
5529
-
5530
-
5531
-    /**
5532
-     * Changes an operator which was supplied to the models into one usable in SQL
5533
-     *
5534
-     * @param string $operator_supplied
5535
-     * @return string an operator which can be used in SQL
5536
-     * @throws EE_Error
5537
-     */
5538
-    private function _prepare_operator_for_sql($operator_supplied)
5539
-    {
5540
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5541
-            : null;
5542
-        if ($sql_operator) {
5543
-            return $sql_operator;
5544
-        } else {
5545
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5546
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5547
-        }
5548
-    }
5549
-
5550
-
5551
-
5552
-    /**
5553
-     * Gets an array where keys are the primary keys and values are their 'names'
5554
-     * (as determined by the model object's name() function, which is often overridden)
5555
-     *
5556
-     * @param array $query_params like get_all's
5557
-     * @return string[]
5558
-     * @throws \EE_Error
5559
-     */
5560
-    public function get_all_names($query_params = array())
5561
-    {
5562
-        $objs = $this->get_all($query_params);
5563
-        $names = array();
5564
-        foreach ($objs as $obj) {
5565
-            $names[$obj->ID()] = $obj->name();
5566
-        }
5567
-        return $names;
5568
-    }
5569
-
5570
-
5571
-
5572
-    /**
5573
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5574
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5575
-     * this is duplicated effort and reduces efficiency) you would be better to use
5576
-     * array_keys() on $model_objects.
5577
-     *
5578
-     * @param \EE_Base_Class[] $model_objects
5579
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5580
-     *                                               in the returned array
5581
-     * @return array
5582
-     * @throws \EE_Error
5583
-     */
5584
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5585
-    {
5586
-        if (! $this->has_primary_key_field()) {
5587
-            if (WP_DEBUG) {
5588
-                EE_Error::add_error(
5589
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5590
-                    __FILE__,
5591
-                    __FUNCTION__,
5592
-                    __LINE__
5593
-                );
5594
-            }
5595
-        }
5596
-        $IDs = array();
5597
-        foreach ($model_objects as $model_object) {
5598
-            $id = $model_object->ID();
5599
-            if (! $id) {
5600
-                if ($filter_out_empty_ids) {
5601
-                    continue;
5602
-                }
5603
-                if (WP_DEBUG) {
5604
-                    EE_Error::add_error(
5605
-                        __(
5606
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5607
-                            'event_espresso'
5608
-                        ),
5609
-                        __FILE__,
5610
-                        __FUNCTION__,
5611
-                        __LINE__
5612
-                    );
5613
-                }
5614
-            }
5615
-            $IDs[] = $id;
5616
-        }
5617
-        return $IDs;
5618
-    }
5619
-
5620
-
5621
-
5622
-    /**
5623
-     * Returns the string used in capabilities relating to this model. If there
5624
-     * are no capabilities that relate to this model returns false
5625
-     *
5626
-     * @return string|false
5627
-     */
5628
-    public function cap_slug()
5629
-    {
5630
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5631
-    }
5632
-
5633
-
5634
-
5635
-    /**
5636
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5637
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5638
-     * only returns the cap restrictions array in that context (ie, the array
5639
-     * at that key)
5640
-     *
5641
-     * @param string $context
5642
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5643
-     * @throws \EE_Error
5644
-     */
5645
-    public function cap_restrictions($context = EEM_Base::caps_read)
5646
-    {
5647
-        EEM_Base::verify_is_valid_cap_context($context);
5648
-        //check if we ought to run the restriction generator first
5649
-        if (
5650
-            isset($this->_cap_restriction_generators[$context])
5651
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5652
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5653
-        ) {
5654
-            $this->_cap_restrictions[$context] = array_merge(
5655
-                $this->_cap_restrictions[$context],
5656
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5657
-            );
5658
-        }
5659
-        //and make sure we've finalized the construction of each restriction
5660
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5661
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5662
-                $where_conditions_obj->_finalize_construct($this);
5663
-            }
5664
-        }
5665
-        return $this->_cap_restrictions[$context];
5666
-    }
5667
-
5668
-
5669
-
5670
-    /**
5671
-     * Indicating whether or not this model thinks its a wp core model
5672
-     *
5673
-     * @return boolean
5674
-     */
5675
-    public function is_wp_core_model()
5676
-    {
5677
-        return $this->_wp_core_model;
5678
-    }
5679
-
5680
-
5681
-
5682
-    /**
5683
-     * Gets all the caps that are missing which impose a restriction on
5684
-     * queries made in this context
5685
-     *
5686
-     * @param string $context one of EEM_Base::caps_ constants
5687
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5688
-     * @throws \EE_Error
5689
-     */
5690
-    public function caps_missing($context = EEM_Base::caps_read)
5691
-    {
5692
-        $missing_caps = array();
5693
-        $cap_restrictions = $this->cap_restrictions($context);
5694
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5695
-            if (! EE_Capabilities::instance()
5696
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5697
-            ) {
5698
-                $missing_caps[$cap] = $restriction_if_no_cap;
5699
-            }
5700
-        }
5701
-        return $missing_caps;
5702
-    }
5703
-
5704
-
5705
-
5706
-    /**
5707
-     * Gets the mapping from capability contexts to action strings used in capability names
5708
-     *
5709
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5710
-     * one of 'read', 'edit', or 'delete'
5711
-     */
5712
-    public function cap_contexts_to_cap_action_map()
5713
-    {
5714
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5715
-            $this);
5716
-    }
5717
-
5718
-
5719
-
5720
-    /**
5721
-     * Gets the action string for the specified capability context
5722
-     *
5723
-     * @param string $context
5724
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5725
-     * @throws \EE_Error
5726
-     */
5727
-    public function cap_action_for_context($context)
5728
-    {
5729
-        $mapping = $this->cap_contexts_to_cap_action_map();
5730
-        if (isset($mapping[$context])) {
5731
-            return $mapping[$context];
5732
-        }
5733
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5734
-            return $action;
5735
-        }
5736
-        throw new EE_Error(
5737
-            sprintf(
5738
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5739
-                $context,
5740
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5741
-            )
5742
-        );
5743
-    }
5744
-
5745
-
5746
-
5747
-    /**
5748
-     * Returns all the capability contexts which are valid when querying models
5749
-     *
5750
-     * @return array
5751
-     */
5752
-    public static function valid_cap_contexts()
5753
-    {
5754
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5755
-            self::caps_read,
5756
-            self::caps_read_admin,
5757
-            self::caps_edit,
5758
-            self::caps_delete,
5759
-        ));
5760
-    }
5761
-
5762
-
5763
-
5764
-    /**
5765
-     * Returns all valid options for 'default_where_conditions'
5766
-     *
5767
-     * @return array
5768
-     */
5769
-    public static function valid_default_where_conditions()
5770
-    {
5771
-        return array(
5772
-            EEM_Base::default_where_conditions_all,
5773
-            EEM_Base::default_where_conditions_this_only,
5774
-            EEM_Base::default_where_conditions_others_only,
5775
-            EEM_Base::default_where_conditions_minimum_all,
5776
-            EEM_Base::default_where_conditions_minimum_others,
5777
-            EEM_Base::default_where_conditions_none
5778
-        );
5779
-    }
5780
-
5781
-    // public static function default_where_conditions_full
5782
-    /**
5783
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5784
-     *
5785
-     * @param string $context
5786
-     * @return bool
5787
-     * @throws \EE_Error
5788
-     */
5789
-    static public function verify_is_valid_cap_context($context)
5790
-    {
5791
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5792
-        if (in_array($context, $valid_cap_contexts)) {
5793
-            return true;
5794
-        } else {
5795
-            throw new EE_Error(
5796
-                sprintf(
5797
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5798
-                        'event_espresso'),
5799
-                    $context,
5800
-                    'EEM_Base',
5801
-                    implode(',', $valid_cap_contexts)
5802
-                )
5803
-            );
5804
-        }
5805
-    }
5806
-
5807
-
5808
-
5809
-    /**
5810
-     * Clears all the models field caches. This is only useful when a sub-class
5811
-     * might have added a field or something and these caches might be invalidated
5812
-     */
5813
-    protected function _invalidate_field_caches()
5814
-    {
5815
-        $this->_cache_foreign_key_to_fields = array();
5816
-        $this->_cached_fields = null;
5817
-        $this->_cached_fields_non_db_only = null;
5818
-    }
5819
-
5820
-
5821
-
5822
-    /**
5823
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5824
-     * (eg "and", "or", "not").
5825
-     *
5826
-     * @return array
5827
-     */
5828
-    public function logic_query_param_keys()
5829
-    {
5830
-        return $this->_logic_query_param_keys;
5831
-    }
5832
-
5833
-
5834
-
5835
-    /**
5836
-     * Determines whether or not the where query param array key is for a logic query param.
5837
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5838
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5839
-     *
5840
-     * @param $query_param_key
5841
-     * @return bool
5842
-     */
5843
-    public function is_logic_query_param_key($query_param_key)
5844
-    {
5845
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5846
-            if ($query_param_key === $logic_query_param_key
5847
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5848
-            ) {
5849
-                return true;
5850
-            }
5851
-        }
5852
-        return false;
5853
-    }
3613
+		}
3614
+		return $null_friendly_where_conditions;
3615
+	}
3616
+
3617
+
3618
+
3619
+	/**
3620
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3621
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3622
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3623
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3624
+	 *
3625
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3626
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3627
+	 */
3628
+	private function _get_default_where_conditions($model_relation_path = null)
3629
+	{
3630
+		if ($this->_ignore_where_strategy) {
3631
+			return array();
3632
+		}
3633
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3634
+	}
3635
+
3636
+
3637
+
3638
+	/**
3639
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3640
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3641
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3642
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3643
+	 * Similar to _get_default_where_conditions
3644
+	 *
3645
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3646
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3647
+	 */
3648
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3649
+	{
3650
+		if ($this->_ignore_where_strategy) {
3651
+			return array();
3652
+		}
3653
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3654
+	}
3655
+
3656
+
3657
+
3658
+	/**
3659
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3660
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3661
+	 *
3662
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3663
+	 * @return string
3664
+	 * @throws \EE_Error
3665
+	 */
3666
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3667
+	{
3668
+		$selects = $this->_get_columns_to_select_for_this_model();
3669
+		foreach (
3670
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3671
+			$name_of_other_model_included
3672
+		) {
3673
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3674
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3675
+			foreach ($other_model_selects as $key => $value) {
3676
+				$selects[] = $value;
3677
+			}
3678
+		}
3679
+		return implode(", ", $selects);
3680
+	}
3681
+
3682
+
3683
+
3684
+	/**
3685
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3686
+	 * So that's going to be the columns for all the fields on the model
3687
+	 *
3688
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3689
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3690
+	 */
3691
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3692
+	{
3693
+		$fields = $this->field_settings();
3694
+		$selects = array();
3695
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3696
+			$this->get_this_model_name());
3697
+		foreach ($fields as $field_obj) {
3698
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3699
+						 . $field_obj->get_table_alias()
3700
+						 . "."
3701
+						 . $field_obj->get_table_column()
3702
+						 . " AS '"
3703
+						 . $table_alias_with_model_relation_chain_prefix
3704
+						 . $field_obj->get_table_alias()
3705
+						 . "."
3706
+						 . $field_obj->get_table_column()
3707
+						 . "'";
3708
+		}
3709
+		//make sure we are also getting the PKs of each table
3710
+		$tables = $this->get_tables();
3711
+		if (count($tables) > 1) {
3712
+			foreach ($tables as $table_obj) {
3713
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3714
+									   . $table_obj->get_fully_qualified_pk_column();
3715
+				if (! in_array($qualified_pk_column, $selects)) {
3716
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3717
+				}
3718
+			}
3719
+		}
3720
+		return $selects;
3721
+	}
3722
+
3723
+
3724
+
3725
+	/**
3726
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3727
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3728
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3729
+	 * SQL for joining, and the data types
3730
+	 *
3731
+	 * @param null|string                 $original_query_param
3732
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3733
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3734
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3735
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3736
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3737
+	 *                                                          or 'Registration's
3738
+	 * @param string                      $original_query_param what it originally was (eg
3739
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3740
+	 *                                                          matches $query_param
3741
+	 * @throws EE_Error
3742
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3743
+	 */
3744
+	private function _extract_related_model_info_from_query_param(
3745
+		$query_param,
3746
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3747
+		$query_param_type,
3748
+		$original_query_param = null
3749
+	) {
3750
+		if ($original_query_param === null) {
3751
+			$original_query_param = $query_param;
3752
+		}
3753
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3754
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3755
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3756
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3757
+		//check to see if we have a field on this model
3758
+		$this_model_fields = $this->field_settings(true);
3759
+		if (array_key_exists($query_param, $this_model_fields)) {
3760
+			if ($allow_fields) {
3761
+				return;
3762
+			} else {
3763
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3764
+					"event_espresso"),
3765
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3766
+			}
3767
+		} //check if this is a special logic query param
3768
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3769
+			if ($allow_logic_query_params) {
3770
+				return;
3771
+			} else {
3772
+				throw new EE_Error(
3773
+					sprintf(
3774
+						__('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',
3775
+							'event_espresso'),
3776
+						implode('", "', $this->_logic_query_param_keys),
3777
+						$query_param,
3778
+						get_class($this),
3779
+						'<br />',
3780
+						"\t"
3781
+						. ' $passed_in_query_info = <pre>'
3782
+						. print_r($passed_in_query_info, true)
3783
+						. '</pre>'
3784
+						. "\n\t"
3785
+						. ' $query_param_type = '
3786
+						. $query_param_type
3787
+						. "\n\t"
3788
+						. ' $original_query_param = '
3789
+						. $original_query_param
3790
+					)
3791
+				);
3792
+			}
3793
+		} //check if it's a custom selection
3794
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3795
+			return;
3796
+		}
3797
+		//check if has a model name at the beginning
3798
+		//and
3799
+		//check if it's a field on a related model
3800
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3801
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3802
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3803
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3804
+				if ($query_param === '') {
3805
+					//nothing left to $query_param
3806
+					//we should actually end in a field name, not a model like this!
3807
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3808
+						"event_espresso"),
3809
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3810
+				} else {
3811
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3812
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3813
+						$passed_in_query_info, $query_param_type, $original_query_param);
3814
+					return;
3815
+				}
3816
+			} elseif ($query_param === $valid_related_model_name) {
3817
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3818
+				return;
3819
+			}
3820
+		}
3821
+		//ok so $query_param didn't start with a model name
3822
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3823
+		//it's wack, that's what it is
3824
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3825
+			"event_espresso"),
3826
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3827
+	}
3828
+
3829
+
3830
+
3831
+	/**
3832
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3833
+	 * and store it on $passed_in_query_info
3834
+	 *
3835
+	 * @param string                      $model_name
3836
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3837
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3838
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3839
+	 *                                                          and are adding a join to 'Payment' with the original
3840
+	 *                                                          query param key
3841
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3842
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3843
+	 *                                                          Payment wants to add default query params so that it
3844
+	 *                                                          will know what models to prepend onto its default query
3845
+	 *                                                          params or in case it wants to rename tables (in case
3846
+	 *                                                          there are multiple joins to the same table)
3847
+	 * @return void
3848
+	 * @throws \EE_Error
3849
+	 */
3850
+	private function _add_join_to_model(
3851
+		$model_name,
3852
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3853
+		$original_query_param
3854
+	) {
3855
+		$relation_obj = $this->related_settings_for($model_name);
3856
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3857
+		//check if the relation is HABTM, because then we're essentially doing two joins
3858
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3859
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3860
+			$join_model_obj = $relation_obj->get_join_model();
3861
+			//replace the model specified with the join model for this relation chain, whi
3862
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3863
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3864
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3865
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3866
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3867
+			$passed_in_query_info->merge($new_query_info);
3868
+		}
3869
+		//now just join to the other table pointed to by the relation object, and add its data types
3870
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3871
+			array($model_relation_chain => $model_name),
3872
+			$relation_obj->get_join_statement($model_relation_chain));
3873
+		$passed_in_query_info->merge($new_query_info);
3874
+	}
3875
+
3876
+
3877
+
3878
+	/**
3879
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3880
+	 *
3881
+	 * @param array $where_params like EEM_Base::get_all
3882
+	 * @return string of SQL
3883
+	 * @throws \EE_Error
3884
+	 */
3885
+	private function _construct_where_clause($where_params)
3886
+	{
3887
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3888
+		if ($SQL) {
3889
+			return " WHERE " . $SQL;
3890
+		} else {
3891
+			return '';
3892
+		}
3893
+	}
3894
+
3895
+
3896
+
3897
+	/**
3898
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3899
+	 * and should be passed HAVING parameters, not WHERE parameters
3900
+	 *
3901
+	 * @param array $having_params
3902
+	 * @return string
3903
+	 * @throws \EE_Error
3904
+	 */
3905
+	private function _construct_having_clause($having_params)
3906
+	{
3907
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3908
+		if ($SQL) {
3909
+			return " HAVING " . $SQL;
3910
+		} else {
3911
+			return '';
3912
+		}
3913
+	}
3914
+
3915
+
3916
+
3917
+	/**
3918
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3919
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3920
+	 * EEM_Attendee.
3921
+	 *
3922
+	 * @param string $field_name
3923
+	 * @param string $model_name
3924
+	 * @return EE_Model_Field_Base
3925
+	 * @throws EE_Error
3926
+	 */
3927
+	protected function _get_field_on_model($field_name, $model_name)
3928
+	{
3929
+		$model_class = 'EEM_' . $model_name;
3930
+		$model_filepath = $model_class . ".model.php";
3931
+		if (is_readable($model_filepath)) {
3932
+			require_once($model_filepath);
3933
+			$model_instance = call_user_func($model_name . "::instance");
3934
+			/* @var $model_instance EEM_Base */
3935
+			return $model_instance->field_settings_for($field_name);
3936
+		} else {
3937
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3938
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3939
+		}
3940
+	}
3941
+
3942
+
3943
+
3944
+	/**
3945
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3946
+	 * Event_Meta.meta_value = 'foo'))"
3947
+	 *
3948
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3949
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3950
+	 * @throws EE_Error
3951
+	 * @return string of SQL
3952
+	 */
3953
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3954
+	{
3955
+		$where_clauses = array();
3956
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3957
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3958
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3959
+				switch ($query_param) {
3960
+					case 'not':
3961
+					case 'NOT':
3962
+						$where_clauses[] = "! ("
3963
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3964
+								$glue)
3965
+										   . ")";
3966
+						break;
3967
+					case 'and':
3968
+					case 'AND':
3969
+						$where_clauses[] = " ("
3970
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3971
+								' AND ')
3972
+										   . ")";
3973
+						break;
3974
+					case 'or':
3975
+					case 'OR':
3976
+						$where_clauses[] = " ("
3977
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3978
+								' OR ')
3979
+										   . ")";
3980
+						break;
3981
+				}
3982
+			} else {
3983
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3984
+				//if it's not a normal field, maybe it's a custom selection?
3985
+				if (! $field_obj) {
3986
+					if (isset($this->_custom_selections[$query_param][1])) {
3987
+						$field_obj = $this->_custom_selections[$query_param][1];
3988
+					} else {
3989
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3990
+							"event_espresso"), $query_param));
3991
+					}
3992
+				}
3993
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3994
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3995
+			}
3996
+		}
3997
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3998
+	}
3999
+
4000
+
4001
+
4002
+	/**
4003
+	 * Takes the input parameter and extract the table name (alias) and column name
4004
+	 *
4005
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4006
+	 * @throws EE_Error
4007
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4008
+	 */
4009
+	private function _deduce_column_name_from_query_param($query_param)
4010
+	{
4011
+		$field = $this->_deduce_field_from_query_param($query_param);
4012
+		if ($field) {
4013
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4014
+				$query_param);
4015
+			return $table_alias_prefix . $field->get_qualified_column();
4016
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4017
+			//maybe it's custom selection item?
4018
+			//if so, just use it as the "column name"
4019
+			return $query_param;
4020
+		} else {
4021
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4022
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4023
+		}
4024
+	}
4025
+
4026
+
4027
+
4028
+	/**
4029
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4030
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4031
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4032
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4033
+	 *
4034
+	 * @param string $condition_query_param_key
4035
+	 * @return string
4036
+	 */
4037
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4038
+	{
4039
+		$pos_of_star = strpos($condition_query_param_key, '*');
4040
+		if ($pos_of_star === false) {
4041
+			return $condition_query_param_key;
4042
+		} else {
4043
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4044
+			return $condition_query_param_sans_star;
4045
+		}
4046
+	}
4047
+
4048
+
4049
+
4050
+	/**
4051
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4052
+	 *
4053
+	 * @param                            mixed      array | string    $op_and_value
4054
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4055
+	 * @throws EE_Error
4056
+	 * @return string
4057
+	 */
4058
+	private function _construct_op_and_value($op_and_value, $field_obj)
4059
+	{
4060
+		if (is_array($op_and_value)) {
4061
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4062
+			if (! $operator) {
4063
+				$php_array_like_string = array();
4064
+				foreach ($op_and_value as $key => $value) {
4065
+					$php_array_like_string[] = "$key=>$value";
4066
+				}
4067
+				throw new EE_Error(
4068
+					sprintf(
4069
+						__(
4070
+							"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))",
4071
+							"event_espresso"
4072
+						),
4073
+						implode(",", $php_array_like_string)
4074
+					)
4075
+				);
4076
+			}
4077
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4078
+		} else {
4079
+			$operator = '=';
4080
+			$value = $op_and_value;
4081
+		}
4082
+		//check to see if the value is actually another field
4083
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4084
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4085
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4086
+			//in this case, the value should be an array, or at least a comma-separated list
4087
+			//it will need to handle a little differently
4088
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4089
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4090
+			return $operator . SP . $cleaned_value;
4091
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4092
+			//the value should be an array with count of two.
4093
+			if (count($value) !== 2) {
4094
+				throw new EE_Error(
4095
+					sprintf(
4096
+						__(
4097
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4098
+							'event_espresso'
4099
+						),
4100
+						"BETWEEN"
4101
+					)
4102
+				);
4103
+			}
4104
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4105
+			return $operator . SP . $cleaned_value;
4106
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4107
+			if ($value !== null) {
4108
+				throw new EE_Error(
4109
+					sprintf(
4110
+						__(
4111
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4112
+							"event_espresso"
4113
+						),
4114
+						$value,
4115
+						$operator
4116
+					)
4117
+				);
4118
+			}
4119
+			return $operator;
4120
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4121
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4122
+			//remove other junk. So just treat it as a string.
4123
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4124
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4125
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4126
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4127
+			throw new EE_Error(
4128
+				sprintf(
4129
+					__(
4130
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4131
+						'event_espresso'
4132
+					),
4133
+					$operator,
4134
+					$operator
4135
+				)
4136
+			);
4137
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4138
+			throw new EE_Error(
4139
+				sprintf(
4140
+					__(
4141
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4142
+						'event_espresso'
4143
+					),
4144
+					$operator,
4145
+					$operator
4146
+				)
4147
+			);
4148
+		} else {
4149
+			throw new EE_Error(
4150
+				sprintf(
4151
+					__(
4152
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4153
+						"event_espresso"
4154
+					),
4155
+					http_build_query($op_and_value)
4156
+				)
4157
+			);
4158
+		}
4159
+	}
4160
+
4161
+
4162
+
4163
+	/**
4164
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4165
+	 *
4166
+	 * @param array                      $values
4167
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4168
+	 *                                              '%s'
4169
+	 * @return string
4170
+	 * @throws \EE_Error
4171
+	 */
4172
+	public function _construct_between_value($values, $field_obj)
4173
+	{
4174
+		$cleaned_values = array();
4175
+		foreach ($values as $value) {
4176
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4177
+		}
4178
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4179
+	}
4180
+
4181
+
4182
+
4183
+	/**
4184
+	 * Takes an array or a comma-separated list of $values and cleans them
4185
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4186
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4187
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4188
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4189
+	 *
4190
+	 * @param mixed                      $values    array or comma-separated string
4191
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4192
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4193
+	 * @throws \EE_Error
4194
+	 */
4195
+	public function _construct_in_value($values, $field_obj)
4196
+	{
4197
+		//check if the value is a CSV list
4198
+		if (is_string($values)) {
4199
+			//in which case, turn it into an array
4200
+			$values = explode(",", $values);
4201
+		}
4202
+		$cleaned_values = array();
4203
+		foreach ($values as $value) {
4204
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4205
+		}
4206
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4207
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4208
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4209
+		if (empty($cleaned_values)) {
4210
+			$all_fields = $this->field_settings();
4211
+			$a_field = array_shift($all_fields);
4212
+			$main_table = $this->_get_main_table();
4213
+			$cleaned_values[] = "SELECT "
4214
+								. $a_field->get_table_column()
4215
+								. " FROM "
4216
+								. $main_table->get_table_name()
4217
+								. " WHERE FALSE";
4218
+		}
4219
+		return "(" . implode(",", $cleaned_values) . ")";
4220
+	}
4221
+
4222
+
4223
+
4224
+	/**
4225
+	 * @param mixed                      $value
4226
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4227
+	 * @throws EE_Error
4228
+	 * @return false|null|string
4229
+	 */
4230
+	private function _wpdb_prepare_using_field($value, $field_obj)
4231
+	{
4232
+		/** @type WPDB $wpdb */
4233
+		global $wpdb;
4234
+		if ($field_obj instanceof EE_Model_Field_Base) {
4235
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4236
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4237
+		} else {//$field_obj should really just be a data type
4238
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4239
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4240
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4241
+			}
4242
+			return $wpdb->prepare($field_obj, $value);
4243
+		}
4244
+	}
4245
+
4246
+
4247
+
4248
+	/**
4249
+	 * Takes the input parameter and finds the model field that it indicates.
4250
+	 *
4251
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4252
+	 * @throws EE_Error
4253
+	 * @return EE_Model_Field_Base
4254
+	 */
4255
+	protected function _deduce_field_from_query_param($query_param_name)
4256
+	{
4257
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4258
+		//which will help us find the database table and column
4259
+		$query_param_parts = explode(".", $query_param_name);
4260
+		if (empty($query_param_parts)) {
4261
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4262
+				'event_espresso'), $query_param_name));
4263
+		}
4264
+		$number_of_parts = count($query_param_parts);
4265
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4266
+		if ($number_of_parts === 1) {
4267
+			$field_name = $last_query_param_part;
4268
+			$model_obj = $this;
4269
+		} else {// $number_of_parts >= 2
4270
+			//the last part is the column name, and there are only 2parts. therefore...
4271
+			$field_name = $last_query_param_part;
4272
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4273
+		}
4274
+		try {
4275
+			return $model_obj->field_settings_for($field_name);
4276
+		} catch (EE_Error $e) {
4277
+			return null;
4278
+		}
4279
+	}
4280
+
4281
+
4282
+
4283
+	/**
4284
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4285
+	 * alias and column which corresponds to it
4286
+	 *
4287
+	 * @param string $field_name
4288
+	 * @throws EE_Error
4289
+	 * @return string
4290
+	 */
4291
+	public function _get_qualified_column_for_field($field_name)
4292
+	{
4293
+		$all_fields = $this->field_settings();
4294
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4295
+		if ($field) {
4296
+			return $field->get_qualified_column();
4297
+		} else {
4298
+			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4299
+				'event_espresso'), $field_name, get_class($this)));
4300
+		}
4301
+	}
4302
+
4303
+
4304
+
4305
+	/**
4306
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4307
+	 * Example usage:
4308
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4309
+	 *      array(),
4310
+	 *      ARRAY_A,
4311
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4312
+	 *  );
4313
+	 * is equivalent to
4314
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4315
+	 * and
4316
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4317
+	 *      array(
4318
+	 *          array(
4319
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4320
+	 *          ),
4321
+	 *          ARRAY_A,
4322
+	 *          implode(
4323
+	 *              ', ',
4324
+	 *              array_merge(
4325
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4326
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4327
+	 *              )
4328
+	 *          )
4329
+	 *      )
4330
+	 *  );
4331
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4332
+	 *
4333
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4334
+	 *                                            and the one whose fields you are selecting for example: when querying
4335
+	 *                                            tickets model and selecting fields from the tickets model you would
4336
+	 *                                            leave this parameter empty, because no models are needed to join
4337
+	 *                                            between the queried model and the selected one. Likewise when
4338
+	 *                                            querying the datetime model and selecting fields from the tickets
4339
+	 *                                            model, it would also be left empty, because there is a direct
4340
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4341
+	 *                                            them together. However, when querying from the event model and
4342
+	 *                                            selecting fields from the ticket model, you should provide the string
4343
+	 *                                            'Datetime', indicating that the event model must first join to the
4344
+	 *                                            datetime model in order to find its relation to ticket model.
4345
+	 *                                            Also, when querying from the venue model and selecting fields from
4346
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4347
+	 *                                            indicating you need to join the venue model to the event model,
4348
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4349
+	 *                                            This string is used to deduce the prefix that gets added onto the
4350
+	 *                                            models' tables qualified columns
4351
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4352
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4353
+	 *                                            qualified column names
4354
+	 * @return array|string
4355
+	 */
4356
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4357
+	{
4358
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4359
+		$qualified_columns = array();
4360
+		foreach ($this->field_settings() as $field_name => $field) {
4361
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4362
+		}
4363
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4364
+	}
4365
+
4366
+
4367
+
4368
+	/**
4369
+	 * constructs the select use on special limit joins
4370
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4371
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4372
+	 * (as that is typically where the limits would be set).
4373
+	 *
4374
+	 * @param  string       $table_alias The table the select is being built for
4375
+	 * @param  mixed|string $limit       The limit for this select
4376
+	 * @return string                The final select join element for the query.
4377
+	 */
4378
+	public function _construct_limit_join_select($table_alias, $limit)
4379
+	{
4380
+		$SQL = '';
4381
+		foreach ($this->_tables as $table_obj) {
4382
+			if ($table_obj instanceof EE_Primary_Table) {
4383
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4384
+					? $table_obj->get_select_join_limit($limit)
4385
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4386
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4387
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4388
+					? $table_obj->get_select_join_limit_join($limit)
4389
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4390
+			}
4391
+		}
4392
+		return $SQL;
4393
+	}
4394
+
4395
+
4396
+
4397
+	/**
4398
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4399
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4400
+	 *
4401
+	 * @return string SQL
4402
+	 * @throws \EE_Error
4403
+	 */
4404
+	public function _construct_internal_join()
4405
+	{
4406
+		$SQL = $this->_get_main_table()->get_table_sql();
4407
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4408
+		return $SQL;
4409
+	}
4410
+
4411
+
4412
+
4413
+	/**
4414
+	 * Constructs the SQL for joining all the tables on this model.
4415
+	 * Normally $alias should be the primary table's alias, but in cases where
4416
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4417
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4418
+	 * alias, this will construct SQL like:
4419
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4420
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4421
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4422
+	 *
4423
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4424
+	 * @return string
4425
+	 */
4426
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4427
+	{
4428
+		$SQL = '';
4429
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4430
+		foreach ($this->_tables as $table_obj) {
4431
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4432
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4433
+					//so we're joining to this table, meaning the table is already in
4434
+					//the FROM statement, BUT the primary table isn't. So we want
4435
+					//to add the inverse join sql
4436
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4437
+				} else {
4438
+					//just add a regular JOIN to this table from the primary table
4439
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4440
+				}
4441
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4442
+		}
4443
+		return $SQL;
4444
+	}
4445
+
4446
+
4447
+
4448
+	/**
4449
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4450
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4451
+	 * their data type (eg, '%s', '%d', etc)
4452
+	 *
4453
+	 * @return array
4454
+	 */
4455
+	public function _get_data_types()
4456
+	{
4457
+		$data_types = array();
4458
+		foreach ($this->field_settings() as $field_obj) {
4459
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4460
+			/** @var $field_obj EE_Model_Field_Base */
4461
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4462
+		}
4463
+		return $data_types;
4464
+	}
4465
+
4466
+
4467
+
4468
+	/**
4469
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4470
+	 *
4471
+	 * @param string $model_name
4472
+	 * @throws EE_Error
4473
+	 * @return EEM_Base
4474
+	 */
4475
+	public function get_related_model_obj($model_name)
4476
+	{
4477
+		$model_classname = "EEM_" . $model_name;
4478
+		if (! class_exists($model_classname)) {
4479
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4480
+				'event_espresso'), $model_name, $model_classname));
4481
+		}
4482
+		return call_user_func($model_classname . "::instance");
4483
+	}
4484
+
4485
+
4486
+
4487
+	/**
4488
+	 * Returns the array of EE_ModelRelations for this model.
4489
+	 *
4490
+	 * @return EE_Model_Relation_Base[]
4491
+	 */
4492
+	public function relation_settings()
4493
+	{
4494
+		return $this->_model_relations;
4495
+	}
4496
+
4497
+
4498
+
4499
+	/**
4500
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4501
+	 * because without THOSE models, this model probably doesn't have much purpose.
4502
+	 * (Eg, without an event, datetimes have little purpose.)
4503
+	 *
4504
+	 * @return EE_Belongs_To_Relation[]
4505
+	 */
4506
+	public function belongs_to_relations()
4507
+	{
4508
+		$belongs_to_relations = array();
4509
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4510
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4511
+				$belongs_to_relations[$model_name] = $relation_obj;
4512
+			}
4513
+		}
4514
+		return $belongs_to_relations;
4515
+	}
4516
+
4517
+
4518
+
4519
+	/**
4520
+	 * Returns the specified EE_Model_Relation, or throws an exception
4521
+	 *
4522
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4523
+	 * @throws EE_Error
4524
+	 * @return EE_Model_Relation_Base
4525
+	 */
4526
+	public function related_settings_for($relation_name)
4527
+	{
4528
+		$relatedModels = $this->relation_settings();
4529
+		if (! array_key_exists($relation_name, $relatedModels)) {
4530
+			throw new EE_Error(
4531
+				sprintf(
4532
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4533
+						'event_espresso'),
4534
+					$relation_name,
4535
+					$this->_get_class_name(),
4536
+					implode(', ', array_keys($relatedModels))
4537
+				)
4538
+			);
4539
+		}
4540
+		return $relatedModels[$relation_name];
4541
+	}
4542
+
4543
+
4544
+
4545
+	/**
4546
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4547
+	 * fields
4548
+	 *
4549
+	 * @param string $fieldName
4550
+	 * @throws EE_Error
4551
+	 * @return EE_Model_Field_Base
4552
+	 */
4553
+	public function field_settings_for($fieldName)
4554
+	{
4555
+		$fieldSettings = $this->field_settings(true);
4556
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4557
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4558
+				get_class($this)));
4559
+		}
4560
+		return $fieldSettings[$fieldName];
4561
+	}
4562
+
4563
+
4564
+
4565
+	/**
4566
+	 * Checks if this field exists on this model
4567
+	 *
4568
+	 * @param string $fieldName a key in the model's _field_settings array
4569
+	 * @return boolean
4570
+	 */
4571
+	public function has_field($fieldName)
4572
+	{
4573
+		$fieldSettings = $this->field_settings(true);
4574
+		if (isset($fieldSettings[$fieldName])) {
4575
+			return true;
4576
+		} else {
4577
+			return false;
4578
+		}
4579
+	}
4580
+
4581
+
4582
+
4583
+	/**
4584
+	 * Returns whether or not this model has a relation to the specified model
4585
+	 *
4586
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4587
+	 * @return boolean
4588
+	 */
4589
+	public function has_relation($relation_name)
4590
+	{
4591
+		$relations = $this->relation_settings();
4592
+		if (isset($relations[$relation_name])) {
4593
+			return true;
4594
+		} else {
4595
+			return false;
4596
+		}
4597
+	}
4598
+
4599
+
4600
+
4601
+	/**
4602
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4603
+	 * Eg, on EE_Answer that would be ANS_ID field object
4604
+	 *
4605
+	 * @param $field_obj
4606
+	 * @return boolean
4607
+	 */
4608
+	public function is_primary_key_field($field_obj)
4609
+	{
4610
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4611
+	}
4612
+
4613
+
4614
+
4615
+	/**
4616
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4617
+	 * Eg, on EE_Answer that would be ANS_ID field object
4618
+	 *
4619
+	 * @return EE_Model_Field_Base
4620
+	 * @throws EE_Error
4621
+	 */
4622
+	public function get_primary_key_field()
4623
+	{
4624
+		if ($this->_primary_key_field === null) {
4625
+			foreach ($this->field_settings(true) as $field_obj) {
4626
+				if ($this->is_primary_key_field($field_obj)) {
4627
+					$this->_primary_key_field = $field_obj;
4628
+					break;
4629
+				}
4630
+			}
4631
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4632
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4633
+					get_class($this)));
4634
+			}
4635
+		}
4636
+		return $this->_primary_key_field;
4637
+	}
4638
+
4639
+
4640
+
4641
+	/**
4642
+	 * Returns whether or not not there is a primary key on this model.
4643
+	 * Internally does some caching.
4644
+	 *
4645
+	 * @return boolean
4646
+	 */
4647
+	public function has_primary_key_field()
4648
+	{
4649
+		if ($this->_has_primary_key_field === null) {
4650
+			try {
4651
+				$this->get_primary_key_field();
4652
+				$this->_has_primary_key_field = true;
4653
+			} catch (EE_Error $e) {
4654
+				$this->_has_primary_key_field = false;
4655
+			}
4656
+		}
4657
+		return $this->_has_primary_key_field;
4658
+	}
4659
+
4660
+
4661
+
4662
+	/**
4663
+	 * Finds the first field of type $field_class_name.
4664
+	 *
4665
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4666
+	 *                                 EE_Foreign_Key_Field, etc
4667
+	 * @return EE_Model_Field_Base or null if none is found
4668
+	 */
4669
+	public function get_a_field_of_type($field_class_name)
4670
+	{
4671
+		foreach ($this->field_settings() as $field) {
4672
+			if ($field instanceof $field_class_name) {
4673
+				return $field;
4674
+			}
4675
+		}
4676
+		return null;
4677
+	}
4678
+
4679
+
4680
+
4681
+	/**
4682
+	 * Gets a foreign key field pointing to model.
4683
+	 *
4684
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4685
+	 * @return EE_Foreign_Key_Field_Base
4686
+	 * @throws EE_Error
4687
+	 */
4688
+	public function get_foreign_key_to($model_name)
4689
+	{
4690
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4691
+			foreach ($this->field_settings() as $field) {
4692
+				if (
4693
+					$field instanceof EE_Foreign_Key_Field_Base
4694
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4695
+				) {
4696
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4697
+					break;
4698
+				}
4699
+			}
4700
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4701
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4702
+					'event_espresso'), $model_name, get_class($this)));
4703
+			}
4704
+		}
4705
+		return $this->_cache_foreign_key_to_fields[$model_name];
4706
+	}
4707
+
4708
+
4709
+
4710
+	/**
4711
+	 * Gets the actual table for the table alias
4712
+	 *
4713
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4714
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4715
+	 *                            Either one works
4716
+	 * @return EE_Table_Base
4717
+	 */
4718
+	public function get_table_for_alias($table_alias)
4719
+	{
4720
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4721
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4722
+	}
4723
+
4724
+
4725
+
4726
+	/**
4727
+	 * Returns a flat array of all field son this model, instead of organizing them
4728
+	 * by table_alias as they are in the constructor.
4729
+	 *
4730
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4731
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4732
+	 */
4733
+	public function field_settings($include_db_only_fields = false)
4734
+	{
4735
+		if ($include_db_only_fields) {
4736
+			if ($this->_cached_fields === null) {
4737
+				$this->_cached_fields = array();
4738
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4739
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4740
+						$this->_cached_fields[$field_name] = $field_obj;
4741
+					}
4742
+				}
4743
+			}
4744
+			return $this->_cached_fields;
4745
+		} else {
4746
+			if ($this->_cached_fields_non_db_only === null) {
4747
+				$this->_cached_fields_non_db_only = array();
4748
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4749
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4750
+						/** @var $field_obj EE_Model_Field_Base */
4751
+						if (! $field_obj->is_db_only_field()) {
4752
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4753
+						}
4754
+					}
4755
+				}
4756
+			}
4757
+			return $this->_cached_fields_non_db_only;
4758
+		}
4759
+	}
4760
+
4761
+
4762
+
4763
+	/**
4764
+	 *        cycle though array of attendees and create objects out of each item
4765
+	 *
4766
+	 * @access        private
4767
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4768
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4769
+	 *                           numerically indexed)
4770
+	 * @throws \EE_Error
4771
+	 */
4772
+	protected function _create_objects($rows = array())
4773
+	{
4774
+		$array_of_objects = array();
4775
+		if (empty($rows)) {
4776
+			return array();
4777
+		}
4778
+		$count_if_model_has_no_primary_key = 0;
4779
+		$has_primary_key = $this->has_primary_key_field();
4780
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4781
+		foreach ((array)$rows as $row) {
4782
+			if (empty($row)) {
4783
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4784
+				return array();
4785
+			}
4786
+			//check if we've already set this object in the results array,
4787
+			//in which case there's no need to process it further (again)
4788
+			if ($has_primary_key) {
4789
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4790
+					$row,
4791
+					$primary_key_field->get_qualified_column(),
4792
+					$primary_key_field->get_table_column()
4793
+				);
4794
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4795
+					continue;
4796
+				}
4797
+			}
4798
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4799
+			if (! $classInstance) {
4800
+				throw new EE_Error(
4801
+					sprintf(
4802
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4803
+						$this->get_this_model_name(),
4804
+						http_build_query($row)
4805
+					)
4806
+				);
4807
+			}
4808
+			//set the timezone on the instantiated objects
4809
+			$classInstance->set_timezone($this->_timezone);
4810
+			//make sure if there is any timezone setting present that we set the timezone for the object
4811
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4812
+			$array_of_objects[$key] = $classInstance;
4813
+			//also, for all the relations of type BelongsTo, see if we can cache
4814
+			//those related models
4815
+			//(we could do this for other relations too, but if there are conditions
4816
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4817
+			//so it requires a little more thought than just caching them immediately...)
4818
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4819
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4820
+					//check if this model's INFO is present. If so, cache it on the model
4821
+					$other_model = $relation_obj->get_other_model();
4822
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4823
+					//if we managed to make a model object from the results, cache it on the main model object
4824
+					if ($other_model_obj_maybe) {
4825
+						//set timezone on these other model objects if they are present
4826
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4827
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4828
+					}
4829
+				}
4830
+			}
4831
+		}
4832
+		return $array_of_objects;
4833
+	}
4834
+
4835
+
4836
+
4837
+	/**
4838
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4839
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4840
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4841
+	 * object (as set in the model_field!).
4842
+	 *
4843
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4844
+	 */
4845
+	public function create_default_object()
4846
+	{
4847
+		$this_model_fields_and_values = array();
4848
+		//setup the row using default values;
4849
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4850
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4851
+		}
4852
+		$className = $this->_get_class_name();
4853
+		$classInstance = EE_Registry::instance()
4854
+									->load_class($className, array($this_model_fields_and_values), false, false);
4855
+		return $classInstance;
4856
+	}
4857
+
4858
+
4859
+
4860
+	/**
4861
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4862
+	 *                             or an stdClass where each property is the name of a column,
4863
+	 * @return EE_Base_Class
4864
+	 * @throws \EE_Error
4865
+	 */
4866
+	public function instantiate_class_from_array_or_object($cols_n_values)
4867
+	{
4868
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4869
+			$cols_n_values = get_object_vars($cols_n_values);
4870
+		}
4871
+		$primary_key = null;
4872
+		//make sure the array only has keys that are fields/columns on this model
4873
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4874
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4875
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4876
+		}
4877
+		$className = $this->_get_class_name();
4878
+		//check we actually found results that we can use to build our model object
4879
+		//if not, return null
4880
+		if ($this->has_primary_key_field()) {
4881
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4882
+				return null;
4883
+			}
4884
+		} else if ($this->unique_indexes()) {
4885
+			$first_column = reset($this_model_fields_n_values);
4886
+			if (empty($first_column)) {
4887
+				return null;
4888
+			}
4889
+		}
4890
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4891
+		if ($primary_key) {
4892
+			$classInstance = $this->get_from_entity_map($primary_key);
4893
+			if (! $classInstance) {
4894
+				$classInstance = EE_Registry::instance()
4895
+											->load_class($className,
4896
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4897
+				// add this new object to the entity map
4898
+				$classInstance = $this->add_to_entity_map($classInstance);
4899
+			}
4900
+		} else {
4901
+			$classInstance = EE_Registry::instance()
4902
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4903
+											true, false);
4904
+		}
4905
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4906
+		$this->set_timezone($classInstance->get_timezone());
4907
+		return $classInstance;
4908
+	}
4909
+
4910
+
4911
+
4912
+	/**
4913
+	 * Gets the model object from the  entity map if it exists
4914
+	 *
4915
+	 * @param int|string $id the ID of the model object
4916
+	 * @return EE_Base_Class
4917
+	 */
4918
+	public function get_from_entity_map($id)
4919
+	{
4920
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4921
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4922
+	}
4923
+
4924
+
4925
+
4926
+	/**
4927
+	 * add_to_entity_map
4928
+	 * Adds the object to the model's entity mappings
4929
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4930
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4931
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4932
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4933
+	 *        then this method should be called immediately after the update query
4934
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4935
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4936
+	 *
4937
+	 * @param    EE_Base_Class $object
4938
+	 * @throws EE_Error
4939
+	 * @return \EE_Base_Class
4940
+	 */
4941
+	public function add_to_entity_map(EE_Base_Class $object)
4942
+	{
4943
+		$className = $this->_get_class_name();
4944
+		if (! $object instanceof $className) {
4945
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4946
+				is_object($object) ? get_class($object) : $object, $className));
4947
+		}
4948
+		/** @var $object EE_Base_Class */
4949
+		if (! $object->ID()) {
4950
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4951
+				"event_espresso"), get_class($this)));
4952
+		}
4953
+		// double check it's not already there
4954
+		$classInstance = $this->get_from_entity_map($object->ID());
4955
+		if ($classInstance) {
4956
+			return $classInstance;
4957
+		} else {
4958
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4959
+			return $object;
4960
+		}
4961
+	}
4962
+
4963
+
4964
+
4965
+	/**
4966
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4967
+	 * if no identifier is provided, then the entire entity map is emptied
4968
+	 *
4969
+	 * @param int|string $id the ID of the model object
4970
+	 * @return boolean
4971
+	 */
4972
+	public function clear_entity_map($id = null)
4973
+	{
4974
+		if (empty($id)) {
4975
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4976
+			return true;
4977
+		}
4978
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4979
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4980
+			return true;
4981
+		}
4982
+		return false;
4983
+	}
4984
+
4985
+
4986
+
4987
+	/**
4988
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4989
+	 * Given an array where keys are column (or column alias) names and values,
4990
+	 * returns an array of their corresponding field names and database values
4991
+	 *
4992
+	 * @param array $cols_n_values
4993
+	 * @return array
4994
+	 */
4995
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4996
+	{
4997
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4998
+	}
4999
+
5000
+
5001
+
5002
+	/**
5003
+	 * _deduce_fields_n_values_from_cols_n_values
5004
+	 * Given an array where keys are column (or column alias) names and values,
5005
+	 * returns an array of their corresponding field names and database values
5006
+	 *
5007
+	 * @param string $cols_n_values
5008
+	 * @return array
5009
+	 */
5010
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5011
+	{
5012
+		$this_model_fields_n_values = array();
5013
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5014
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5015
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5016
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5017
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5018
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5019
+					if (! $field_obj->is_db_only_field()) {
5020
+						//prepare field as if its coming from db
5021
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5022
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5023
+					}
5024
+				}
5025
+			} else {
5026
+				//the table's rows existed. Use their values
5027
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5028
+					if (! $field_obj->is_db_only_field()) {
5029
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5030
+							$cols_n_values, $field_obj->get_qualified_column(),
5031
+							$field_obj->get_table_column()
5032
+						);
5033
+					}
5034
+				}
5035
+			}
5036
+		}
5037
+		return $this_model_fields_n_values;
5038
+	}
5039
+
5040
+
5041
+
5042
+	/**
5043
+	 * @param $cols_n_values
5044
+	 * @param $qualified_column
5045
+	 * @param $regular_column
5046
+	 * @return null
5047
+	 */
5048
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5049
+	{
5050
+		$value = null;
5051
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5052
+		//does the field on the model relate to this column retrieved from the db?
5053
+		//or is it a db-only field? (not relating to the model)
5054
+		if (isset($cols_n_values[$qualified_column])) {
5055
+			$value = $cols_n_values[$qualified_column];
5056
+		} elseif (isset($cols_n_values[$regular_column])) {
5057
+			$value = $cols_n_values[$regular_column];
5058
+		}
5059
+		return $value;
5060
+	}
5061
+
5062
+
5063
+
5064
+	/**
5065
+	 * refresh_entity_map_from_db
5066
+	 * Makes sure the model object in the entity map at $id assumes the values
5067
+	 * of the database (opposite of EE_base_Class::save())
5068
+	 *
5069
+	 * @param int|string $id
5070
+	 * @return EE_Base_Class
5071
+	 * @throws \EE_Error
5072
+	 */
5073
+	public function refresh_entity_map_from_db($id)
5074
+	{
5075
+		$obj_in_map = $this->get_from_entity_map($id);
5076
+		if ($obj_in_map) {
5077
+			$wpdb_results = $this->_get_all_wpdb_results(
5078
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5079
+			);
5080
+			if ($wpdb_results && is_array($wpdb_results)) {
5081
+				$one_row = reset($wpdb_results);
5082
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5083
+					$obj_in_map->set_from_db($field_name, $db_value);
5084
+				}
5085
+				//clear the cache of related model objects
5086
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5087
+					$obj_in_map->clear_cache($relation_name, null, true);
5088
+				}
5089
+			}
5090
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5091
+			return $obj_in_map;
5092
+		} else {
5093
+			return $this->get_one_by_ID($id);
5094
+		}
5095
+	}
5096
+
5097
+
5098
+
5099
+	/**
5100
+	 * refresh_entity_map_with
5101
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5102
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5103
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5104
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5105
+	 *
5106
+	 * @param int|string    $id
5107
+	 * @param EE_Base_Class $replacing_model_obj
5108
+	 * @return \EE_Base_Class
5109
+	 * @throws \EE_Error
5110
+	 */
5111
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5112
+	{
5113
+		$obj_in_map = $this->get_from_entity_map($id);
5114
+		if ($obj_in_map) {
5115
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5116
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5117
+					$obj_in_map->set($field_name, $value);
5118
+				}
5119
+				//make the model object in the entity map's cache match the $replacing_model_obj
5120
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5121
+					$obj_in_map->clear_cache($relation_name, null, true);
5122
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5123
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5124
+					}
5125
+				}
5126
+			}
5127
+			return $obj_in_map;
5128
+		} else {
5129
+			$this->add_to_entity_map($replacing_model_obj);
5130
+			return $replacing_model_obj;
5131
+		}
5132
+	}
5133
+
5134
+
5135
+
5136
+	/**
5137
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5138
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5139
+	 * require_once($this->_getClassName().".class.php");
5140
+	 *
5141
+	 * @return string
5142
+	 */
5143
+	private function _get_class_name()
5144
+	{
5145
+		return "EE_" . $this->get_this_model_name();
5146
+	}
5147
+
5148
+
5149
+
5150
+	/**
5151
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5152
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5153
+	 * it would be 'Events'.
5154
+	 *
5155
+	 * @param int $quantity
5156
+	 * @return string
5157
+	 */
5158
+	public function item_name($quantity = 1)
5159
+	{
5160
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5161
+	}
5162
+
5163
+
5164
+
5165
+	/**
5166
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5167
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5168
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5169
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5170
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5171
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5172
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5173
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5174
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5175
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5176
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5177
+	 *        return $previousReturnValue.$returnString;
5178
+	 * }
5179
+	 * require('EEM_Answer.model.php');
5180
+	 * $answer=EEM_Answer::instance();
5181
+	 * echo $answer->my_callback('monkeys',100);
5182
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5183
+	 *
5184
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5185
+	 * @param array  $args       array of original arguments passed to the function
5186
+	 * @throws EE_Error
5187
+	 * @return mixed whatever the plugin which calls add_filter decides
5188
+	 */
5189
+	public function __call($methodName, $args)
5190
+	{
5191
+		$className = get_class($this);
5192
+		$tagName = "FHEE__{$className}__{$methodName}";
5193
+		if (! has_filter($tagName)) {
5194
+			throw new EE_Error(
5195
+				sprintf(
5196
+					__('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 );',
5197
+						'event_espresso'),
5198
+					$methodName,
5199
+					$className,
5200
+					$tagName,
5201
+					'<br />'
5202
+				)
5203
+			);
5204
+		}
5205
+		return apply_filters($tagName, null, $this, $args);
5206
+	}
5207
+
5208
+
5209
+
5210
+	/**
5211
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5212
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5213
+	 *
5214
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5215
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5216
+	 *                                                       the object's class name
5217
+	 *                                                       or object's ID
5218
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5219
+	 *                                                       exists in the database. If it does not, we add it
5220
+	 * @throws EE_Error
5221
+	 * @return EE_Base_Class
5222
+	 */
5223
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5224
+	{
5225
+		$className = $this->_get_class_name();
5226
+		if ($base_class_obj_or_id instanceof $className) {
5227
+			$model_object = $base_class_obj_or_id;
5228
+		} else {
5229
+			$primary_key_field = $this->get_primary_key_field();
5230
+			if (
5231
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5232
+				&& (
5233
+					is_int($base_class_obj_or_id)
5234
+					|| is_string($base_class_obj_or_id)
5235
+				)
5236
+			) {
5237
+				// assume it's an ID.
5238
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5239
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5240
+			} else if (
5241
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5242
+				&& is_string($base_class_obj_or_id)
5243
+			) {
5244
+				// assume its a string representation of the object
5245
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5246
+			} else {
5247
+				throw new EE_Error(
5248
+					sprintf(
5249
+						__(
5250
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5251
+							'event_espresso'
5252
+						),
5253
+						$base_class_obj_or_id,
5254
+						$this->_get_class_name(),
5255
+						print_r($base_class_obj_or_id, true)
5256
+					)
5257
+				);
5258
+			}
5259
+		}
5260
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5261
+			$model_object->save();
5262
+		}
5263
+		return $model_object;
5264
+	}
5265
+
5266
+
5267
+
5268
+	/**
5269
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5270
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5271
+	 * returns it ID.
5272
+	 *
5273
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5274
+	 * @return int|string depending on the type of this model object's ID
5275
+	 * @throws EE_Error
5276
+	 */
5277
+	public function ensure_is_ID($base_class_obj_or_id)
5278
+	{
5279
+		$className = $this->_get_class_name();
5280
+		if ($base_class_obj_or_id instanceof $className) {
5281
+			/** @var $base_class_obj_or_id EE_Base_Class */
5282
+			$id = $base_class_obj_or_id->ID();
5283
+		} elseif (is_int($base_class_obj_or_id)) {
5284
+			//assume it's an ID
5285
+			$id = $base_class_obj_or_id;
5286
+		} elseif (is_string($base_class_obj_or_id)) {
5287
+			//assume its a string representation of the object
5288
+			$id = $base_class_obj_or_id;
5289
+		} else {
5290
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5291
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5292
+				print_r($base_class_obj_or_id, true)));
5293
+		}
5294
+		return $id;
5295
+	}
5296
+
5297
+
5298
+
5299
+	/**
5300
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5301
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5302
+	 * been sanitized and converted into the appropriate domain.
5303
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5304
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5305
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5306
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5307
+	 * $EVT = EEM_Event::instance(); $old_setting =
5308
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5309
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5310
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5311
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5312
+	 *
5313
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5314
+	 * @return void
5315
+	 */
5316
+	public function assume_values_already_prepared_by_model_object(
5317
+		$values_already_prepared = self::not_prepared_by_model_object
5318
+	) {
5319
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5320
+	}
5321
+
5322
+
5323
+
5324
+	/**
5325
+	 * Read comments for assume_values_already_prepared_by_model_object()
5326
+	 *
5327
+	 * @return int
5328
+	 */
5329
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5330
+	{
5331
+		return $this->_values_already_prepared_by_model_object;
5332
+	}
5333
+
5334
+
5335
+
5336
+	/**
5337
+	 * Gets all the indexes on this model
5338
+	 *
5339
+	 * @return EE_Index[]
5340
+	 */
5341
+	public function indexes()
5342
+	{
5343
+		return $this->_indexes;
5344
+	}
5345
+
5346
+
5347
+
5348
+	/**
5349
+	 * Gets all the Unique Indexes on this model
5350
+	 *
5351
+	 * @return EE_Unique_Index[]
5352
+	 */
5353
+	public function unique_indexes()
5354
+	{
5355
+		$unique_indexes = array();
5356
+		foreach ($this->_indexes as $name => $index) {
5357
+			if ($index instanceof EE_Unique_Index) {
5358
+				$unique_indexes [$name] = $index;
5359
+			}
5360
+		}
5361
+		return $unique_indexes;
5362
+	}
5363
+
5364
+
5365
+
5366
+	/**
5367
+	 * Gets all the fields which, when combined, make the primary key.
5368
+	 * This is usually just an array with 1 element (the primary key), but in cases
5369
+	 * where there is no primary key, it's a combination of fields as defined
5370
+	 * on a primary index
5371
+	 *
5372
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5373
+	 * @throws \EE_Error
5374
+	 */
5375
+	public function get_combined_primary_key_fields()
5376
+	{
5377
+		foreach ($this->indexes() as $index) {
5378
+			if ($index instanceof EE_Primary_Key_Index) {
5379
+				return $index->fields();
5380
+			}
5381
+		}
5382
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5383
+	}
5384
+
5385
+
5386
+
5387
+	/**
5388
+	 * Used to build a primary key string (when the model has no primary key),
5389
+	 * which can be used a unique string to identify this model object.
5390
+	 *
5391
+	 * @param array $cols_n_values keys are field names, values are their values
5392
+	 * @return string
5393
+	 * @throws \EE_Error
5394
+	 */
5395
+	public function get_index_primary_key_string($cols_n_values)
5396
+	{
5397
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5398
+			$this->get_combined_primary_key_fields());
5399
+		return http_build_query($cols_n_values_for_primary_key_index);
5400
+	}
5401
+
5402
+
5403
+
5404
+	/**
5405
+	 * Gets the field values from the primary key string
5406
+	 *
5407
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5408
+	 * @param string $index_primary_key_string
5409
+	 * @return null|array
5410
+	 * @throws \EE_Error
5411
+	 */
5412
+	public function parse_index_primary_key_string($index_primary_key_string)
5413
+	{
5414
+		$key_fields = $this->get_combined_primary_key_fields();
5415
+		//check all of them are in the $id
5416
+		$key_vals_in_combined_pk = array();
5417
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5418
+		foreach ($key_fields as $key_field_name => $field_obj) {
5419
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5420
+				return null;
5421
+			}
5422
+		}
5423
+		return $key_vals_in_combined_pk;
5424
+	}
5425
+
5426
+
5427
+
5428
+	/**
5429
+	 * verifies that an array of key-value pairs for model fields has a key
5430
+	 * for each field comprising the primary key index
5431
+	 *
5432
+	 * @param array $key_vals
5433
+	 * @return boolean
5434
+	 * @throws \EE_Error
5435
+	 */
5436
+	public function has_all_combined_primary_key_fields($key_vals)
5437
+	{
5438
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5439
+		foreach ($keys_it_should_have as $key) {
5440
+			if (! isset($key_vals[$key])) {
5441
+				return false;
5442
+			}
5443
+		}
5444
+		return true;
5445
+	}
5446
+
5447
+
5448
+
5449
+	/**
5450
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5451
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5452
+	 *
5453
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5454
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5455
+	 * @throws EE_Error
5456
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5457
+	 *                                                              indexed)
5458
+	 */
5459
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5460
+	{
5461
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5462
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5463
+		} elseif (is_array($model_object_or_attributes_array)) {
5464
+			$attributes_array = $model_object_or_attributes_array;
5465
+		} else {
5466
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5467
+				"event_espresso"), $model_object_or_attributes_array));
5468
+		}
5469
+		//even copies obviously won't have the same ID, so remove the primary key
5470
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5471
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5472
+			unset($attributes_array[$this->primary_key_name()]);
5473
+		}
5474
+		if (isset($query_params[0])) {
5475
+			$query_params[0] = array_merge($attributes_array, $query_params);
5476
+		} else {
5477
+			$query_params[0] = $attributes_array;
5478
+		}
5479
+		return $this->get_all($query_params);
5480
+	}
5481
+
5482
+
5483
+
5484
+	/**
5485
+	 * Gets the first copy we find. See get_all_copies for more details
5486
+	 *
5487
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5488
+	 * @param array $query_params
5489
+	 * @return EE_Base_Class
5490
+	 * @throws \EE_Error
5491
+	 */
5492
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5493
+	{
5494
+		if (! is_array($query_params)) {
5495
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5496
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5497
+					gettype($query_params)), '4.6.0');
5498
+			$query_params = array();
5499
+		}
5500
+		$query_params['limit'] = 1;
5501
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5502
+		if (is_array($copies)) {
5503
+			return array_shift($copies);
5504
+		} else {
5505
+			return null;
5506
+		}
5507
+	}
5508
+
5509
+
5510
+
5511
+	/**
5512
+	 * Updates the item with the specified id. Ignores default query parameters because
5513
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5514
+	 *
5515
+	 * @param array      $fields_n_values keys are field names, values are their new values
5516
+	 * @param int|string $id              the value of the primary key to update
5517
+	 * @return int number of rows updated
5518
+	 * @throws \EE_Error
5519
+	 */
5520
+	public function update_by_ID($fields_n_values, $id)
5521
+	{
5522
+		$query_params = array(
5523
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5524
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5525
+		);
5526
+		return $this->update($fields_n_values, $query_params);
5527
+	}
5528
+
5529
+
5530
+
5531
+	/**
5532
+	 * Changes an operator which was supplied to the models into one usable in SQL
5533
+	 *
5534
+	 * @param string $operator_supplied
5535
+	 * @return string an operator which can be used in SQL
5536
+	 * @throws EE_Error
5537
+	 */
5538
+	private function _prepare_operator_for_sql($operator_supplied)
5539
+	{
5540
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5541
+			: null;
5542
+		if ($sql_operator) {
5543
+			return $sql_operator;
5544
+		} else {
5545
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5546
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5547
+		}
5548
+	}
5549
+
5550
+
5551
+
5552
+	/**
5553
+	 * Gets an array where keys are the primary keys and values are their 'names'
5554
+	 * (as determined by the model object's name() function, which is often overridden)
5555
+	 *
5556
+	 * @param array $query_params like get_all's
5557
+	 * @return string[]
5558
+	 * @throws \EE_Error
5559
+	 */
5560
+	public function get_all_names($query_params = array())
5561
+	{
5562
+		$objs = $this->get_all($query_params);
5563
+		$names = array();
5564
+		foreach ($objs as $obj) {
5565
+			$names[$obj->ID()] = $obj->name();
5566
+		}
5567
+		return $names;
5568
+	}
5569
+
5570
+
5571
+
5572
+	/**
5573
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5574
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5575
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5576
+	 * array_keys() on $model_objects.
5577
+	 *
5578
+	 * @param \EE_Base_Class[] $model_objects
5579
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5580
+	 *                                               in the returned array
5581
+	 * @return array
5582
+	 * @throws \EE_Error
5583
+	 */
5584
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5585
+	{
5586
+		if (! $this->has_primary_key_field()) {
5587
+			if (WP_DEBUG) {
5588
+				EE_Error::add_error(
5589
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5590
+					__FILE__,
5591
+					__FUNCTION__,
5592
+					__LINE__
5593
+				);
5594
+			}
5595
+		}
5596
+		$IDs = array();
5597
+		foreach ($model_objects as $model_object) {
5598
+			$id = $model_object->ID();
5599
+			if (! $id) {
5600
+				if ($filter_out_empty_ids) {
5601
+					continue;
5602
+				}
5603
+				if (WP_DEBUG) {
5604
+					EE_Error::add_error(
5605
+						__(
5606
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5607
+							'event_espresso'
5608
+						),
5609
+						__FILE__,
5610
+						__FUNCTION__,
5611
+						__LINE__
5612
+					);
5613
+				}
5614
+			}
5615
+			$IDs[] = $id;
5616
+		}
5617
+		return $IDs;
5618
+	}
5619
+
5620
+
5621
+
5622
+	/**
5623
+	 * Returns the string used in capabilities relating to this model. If there
5624
+	 * are no capabilities that relate to this model returns false
5625
+	 *
5626
+	 * @return string|false
5627
+	 */
5628
+	public function cap_slug()
5629
+	{
5630
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5631
+	}
5632
+
5633
+
5634
+
5635
+	/**
5636
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5637
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5638
+	 * only returns the cap restrictions array in that context (ie, the array
5639
+	 * at that key)
5640
+	 *
5641
+	 * @param string $context
5642
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5643
+	 * @throws \EE_Error
5644
+	 */
5645
+	public function cap_restrictions($context = EEM_Base::caps_read)
5646
+	{
5647
+		EEM_Base::verify_is_valid_cap_context($context);
5648
+		//check if we ought to run the restriction generator first
5649
+		if (
5650
+			isset($this->_cap_restriction_generators[$context])
5651
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5652
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5653
+		) {
5654
+			$this->_cap_restrictions[$context] = array_merge(
5655
+				$this->_cap_restrictions[$context],
5656
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5657
+			);
5658
+		}
5659
+		//and make sure we've finalized the construction of each restriction
5660
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5661
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5662
+				$where_conditions_obj->_finalize_construct($this);
5663
+			}
5664
+		}
5665
+		return $this->_cap_restrictions[$context];
5666
+	}
5667
+
5668
+
5669
+
5670
+	/**
5671
+	 * Indicating whether or not this model thinks its a wp core model
5672
+	 *
5673
+	 * @return boolean
5674
+	 */
5675
+	public function is_wp_core_model()
5676
+	{
5677
+		return $this->_wp_core_model;
5678
+	}
5679
+
5680
+
5681
+
5682
+	/**
5683
+	 * Gets all the caps that are missing which impose a restriction on
5684
+	 * queries made in this context
5685
+	 *
5686
+	 * @param string $context one of EEM_Base::caps_ constants
5687
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5688
+	 * @throws \EE_Error
5689
+	 */
5690
+	public function caps_missing($context = EEM_Base::caps_read)
5691
+	{
5692
+		$missing_caps = array();
5693
+		$cap_restrictions = $this->cap_restrictions($context);
5694
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5695
+			if (! EE_Capabilities::instance()
5696
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5697
+			) {
5698
+				$missing_caps[$cap] = $restriction_if_no_cap;
5699
+			}
5700
+		}
5701
+		return $missing_caps;
5702
+	}
5703
+
5704
+
5705
+
5706
+	/**
5707
+	 * Gets the mapping from capability contexts to action strings used in capability names
5708
+	 *
5709
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5710
+	 * one of 'read', 'edit', or 'delete'
5711
+	 */
5712
+	public function cap_contexts_to_cap_action_map()
5713
+	{
5714
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5715
+			$this);
5716
+	}
5717
+
5718
+
5719
+
5720
+	/**
5721
+	 * Gets the action string for the specified capability context
5722
+	 *
5723
+	 * @param string $context
5724
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5725
+	 * @throws \EE_Error
5726
+	 */
5727
+	public function cap_action_for_context($context)
5728
+	{
5729
+		$mapping = $this->cap_contexts_to_cap_action_map();
5730
+		if (isset($mapping[$context])) {
5731
+			return $mapping[$context];
5732
+		}
5733
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5734
+			return $action;
5735
+		}
5736
+		throw new EE_Error(
5737
+			sprintf(
5738
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5739
+				$context,
5740
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5741
+			)
5742
+		);
5743
+	}
5744
+
5745
+
5746
+
5747
+	/**
5748
+	 * Returns all the capability contexts which are valid when querying models
5749
+	 *
5750
+	 * @return array
5751
+	 */
5752
+	public static function valid_cap_contexts()
5753
+	{
5754
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5755
+			self::caps_read,
5756
+			self::caps_read_admin,
5757
+			self::caps_edit,
5758
+			self::caps_delete,
5759
+		));
5760
+	}
5761
+
5762
+
5763
+
5764
+	/**
5765
+	 * Returns all valid options for 'default_where_conditions'
5766
+	 *
5767
+	 * @return array
5768
+	 */
5769
+	public static function valid_default_where_conditions()
5770
+	{
5771
+		return array(
5772
+			EEM_Base::default_where_conditions_all,
5773
+			EEM_Base::default_where_conditions_this_only,
5774
+			EEM_Base::default_where_conditions_others_only,
5775
+			EEM_Base::default_where_conditions_minimum_all,
5776
+			EEM_Base::default_where_conditions_minimum_others,
5777
+			EEM_Base::default_where_conditions_none
5778
+		);
5779
+	}
5780
+
5781
+	// public static function default_where_conditions_full
5782
+	/**
5783
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5784
+	 *
5785
+	 * @param string $context
5786
+	 * @return bool
5787
+	 * @throws \EE_Error
5788
+	 */
5789
+	static public function verify_is_valid_cap_context($context)
5790
+	{
5791
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5792
+		if (in_array($context, $valid_cap_contexts)) {
5793
+			return true;
5794
+		} else {
5795
+			throw new EE_Error(
5796
+				sprintf(
5797
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5798
+						'event_espresso'),
5799
+					$context,
5800
+					'EEM_Base',
5801
+					implode(',', $valid_cap_contexts)
5802
+				)
5803
+			);
5804
+		}
5805
+	}
5806
+
5807
+
5808
+
5809
+	/**
5810
+	 * Clears all the models field caches. This is only useful when a sub-class
5811
+	 * might have added a field or something and these caches might be invalidated
5812
+	 */
5813
+	protected function _invalidate_field_caches()
5814
+	{
5815
+		$this->_cache_foreign_key_to_fields = array();
5816
+		$this->_cached_fields = null;
5817
+		$this->_cached_fields_non_db_only = null;
5818
+	}
5819
+
5820
+
5821
+
5822
+	/**
5823
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5824
+	 * (eg "and", "or", "not").
5825
+	 *
5826
+	 * @return array
5827
+	 */
5828
+	public function logic_query_param_keys()
5829
+	{
5830
+		return $this->_logic_query_param_keys;
5831
+	}
5832
+
5833
+
5834
+
5835
+	/**
5836
+	 * Determines whether or not the where query param array key is for a logic query param.
5837
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5838
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5839
+	 *
5840
+	 * @param $query_param_key
5841
+	 * @return bool
5842
+	 */
5843
+	public function is_logic_query_param_key($query_param_key)
5844
+	{
5845
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5846
+			if ($query_param_key === $logic_query_param_key
5847
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5848
+			) {
5849
+				return true;
5850
+			}
5851
+		}
5852
+		return false;
5853
+	}
5854 5854
 
5855 5855
 
5856 5856
 
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page_CPT.core.php 2 patches
Indentation   +1416 added lines, -1416 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -24,470 +24,470 @@  discard block
 block discarded – undo
24 24
 {
25 25
 
26 26
 
27
-    /**
28
-     * This gets set in _setup_cpt
29
-     * It will contain the object for the custom post type.
30
-     *
31
-     * @var EE_CPT_Base
32
-     */
33
-    protected $_cpt_object;
34
-
35
-
36
-
37
-    /**
38
-     * a boolean flag to set whether the current route is a cpt route or not.
39
-     *
40
-     * @var bool
41
-     */
42
-    protected $_cpt_route = false;
43
-
44
-
45
-
46
-    /**
47
-     * This property allows cpt classes to define multiple routes as cpt routes.
48
-     * //in this array we define what the custom post type for this route is.
49
-     * array(
50
-     * 'route_name' => 'custom_post_type_slug'
51
-     * )
52
-     *
53
-     * @var array
54
-     */
55
-    protected $_cpt_routes = array();
56
-
27
+	/**
28
+	 * This gets set in _setup_cpt
29
+	 * It will contain the object for the custom post type.
30
+	 *
31
+	 * @var EE_CPT_Base
32
+	 */
33
+	protected $_cpt_object;
34
+
35
+
36
+
37
+	/**
38
+	 * a boolean flag to set whether the current route is a cpt route or not.
39
+	 *
40
+	 * @var bool
41
+	 */
42
+	protected $_cpt_route = false;
43
+
44
+
45
+
46
+	/**
47
+	 * This property allows cpt classes to define multiple routes as cpt routes.
48
+	 * //in this array we define what the custom post type for this route is.
49
+	 * array(
50
+	 * 'route_name' => 'custom_post_type_slug'
51
+	 * )
52
+	 *
53
+	 * @var array
54
+	 */
55
+	protected $_cpt_routes = array();
56
+
57 57
 
58 58
 
59
-    /**
60
-     * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
-     * in this format:
62
-     * array(
63
-     * 'post_type_slug' => 'edit_route'
64
-     * )
65
-     *
66
-     * @var array
67
-     */
68
-    protected $_cpt_edit_routes = array();
69
-
70
-
71
-
72
-    /**
73
-     * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
-     * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
-     * _cpt_model_names property should be in the following format: array(
76
-     * 'route_defined_by_action_param' => 'Model_Name')
77
-     *
78
-     * @var array $_cpt_model_names
79
-     */
80
-    protected $_cpt_model_names = array();
81
-
82
-
83
-    /**
84
-     * @var EE_CPT_Base
85
-     */
86
-    protected $_cpt_model_obj = false;
87
-
88
-
89
-
90
-    /**
91
-     * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
92
-     * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
93
-     * the _register_autosave_containers() method so that we don't override any other containers already registered.
94
-     * Registration of containers should be done before load_page_dependencies() is run.
95
-     *
96
-     * @var array()
97
-     */
98
-    protected $_autosave_containers = array();
99
-    protected $_autosave_fields = array();
100
-
101
-    /**
102
-     * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
103
-     * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
104
-     *
105
-     * @var array
106
-     */
107
-    protected $_pagenow_map;
108
-
109
-
110
-
111
-    /**
112
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
113
-     * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
114
-     * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
115
-     * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
116
-     * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
117
-     *
118
-     * @access protected
119
-     * @abstract
120
-     * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
121
-     * @param  EE_CPT_Base $post    The post object of the cpt that was saved.
122
-     * @return void
123
-     */
124
-    abstract protected function _insert_update_cpt_item($post_id, $post);
125
-
126
-
127
-
128
-    /**
129
-     * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
130
-     *
131
-     * @abstract
132
-     * @access public
133
-     * @param  string $post_id The ID of the cpt that was trashed
134
-     * @return void
135
-     */
136
-    abstract public function trash_cpt_item($post_id);
137
-
138
-
139
-
140
-    /**
141
-     * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
-     *
143
-     * @param  string $post_id theID of the cpt that was untrashed
144
-     * @return void
145
-     */
146
-    abstract public function restore_cpt_item($post_id);
147
-
148
-
149
-
150
-    /**
151
-     * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
152
-     * from the db
153
-     *
154
-     * @param  string $post_id the ID of the cpt that was deleted
155
-     * @return void
156
-     */
157
-    abstract public function delete_cpt_item($post_id);
158
-
159
-
160
-
161
-    /**
162
-     * Just utilizing the method EE_Admin exposes for doing things before page setup.
163
-     *
164
-     * @access protected
165
-     * @return void
166
-     */
167
-    protected function _before_page_setup()
168
-    {
169
-        $page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
170
-        $this->_cpt_routes = array_merge(array(
171
-            'create_new' => $this->page_slug,
172
-            'edit'       => $this->page_slug,
173
-            'trash'      => $this->page_slug,
174
-        ), $this->_cpt_routes);
175
-        //let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
176
-        $this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[$this->_req_data['action']])
177
-            ? get_post_type_object($this->_cpt_routes[$this->_req_data['action']])
178
-            : get_post_type_object($page);
179
-        //tweak pagenow for page loading.
180
-        if ( ! $this->_pagenow_map) {
181
-            $this->_pagenow_map = array(
182
-                'create_new' => 'post-new.php',
183
-                'edit'       => 'post.php',
184
-                'trash'      => 'post.php',
185
-            );
186
-        }
187
-        add_action('current_screen', array($this, 'modify_pagenow'));
188
-        //TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
189
-        //get current page from autosave
190
-        $current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
191
-            ? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
192
-            : null;
193
-        $this->_current_page = isset($this->_req_data['current_page'])
194
-            ? $this->_req_data['current_page']
195
-            : $current_page;
196
-        //autosave... make sure its only for the correct page
197
-        //if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
198
-            //setup autosave ajax hook
199
-            //add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
200
-        //}
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * Simply ensure that we simulate the correct post route for cpt screens
207
-     *
208
-     * @param WP_Screen $current_screen
209
-     * @return void
210
-     */
211
-    public function modify_pagenow($current_screen)
212
-    {
213
-        global $pagenow, $hook_suffix;
214
-        //possibly reset pagenow.
215
-        if ( ! empty($this->_req_data['page'])
216
-             && $this->_req_data['page'] == $this->page_slug
217
-             && ! empty($this->_req_data['action'])
218
-             && isset($this->_pagenow_map[$this->_req_data['action']])
219
-        ) {
220
-            $pagenow = $this->_pagenow_map[$this->_req_data['action']];
221
-            $hook_suffix = $pagenow;
222
-        }
223
-    }
224
-
225
-
226
-
227
-    /**
228
-     * This method is used to register additional autosave containers to the _autosave_containers property.
229
-     *
230
-     * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
231
-     *       automatically register the id for the post metabox as a container.
232
-     * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
-     *                    you would send along the id of a metabox container.
234
-     * @return void
235
-     */
236
-    protected function _register_autosave_containers($ids)
237
-    {
238
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
245
-     * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
246
-     */
247
-    protected function _set_autosave_containers()
248
-    {
249
-        global $wp_meta_boxes;
250
-        $containers = array();
251
-        if (empty($wp_meta_boxes)) {
252
-            return;
253
-        }
254
-        $current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : array();
255
-        foreach ($current_metaboxes as $box_context) {
256
-            foreach ($box_context as $box_details) {
257
-                foreach ($box_details as $box) {
258
-                    if (
259
-                        is_array($box['callback'])
260
-                        && (
261
-                            $box['callback'][0] instanceof EE_Admin_Page
262
-                            || $box['callback'][0] instanceof EE_Admin_Hooks
263
-                        )
264
-                    ) {
265
-                        $containers[] = $box['id'];
266
-                    }
267
-                }
268
-            }
269
-        }
270
-        $this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
271
-        //add hidden inputs container
272
-        $this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
273
-    }
274
-
275
-
276
-
277
-    protected function _load_autosave_scripts_styles()
278
-    {
279
-        /*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
59
+	/**
60
+	 * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
+	 * in this format:
62
+	 * array(
63
+	 * 'post_type_slug' => 'edit_route'
64
+	 * )
65
+	 *
66
+	 * @var array
67
+	 */
68
+	protected $_cpt_edit_routes = array();
69
+
70
+
71
+
72
+	/**
73
+	 * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
+	 * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
+	 * _cpt_model_names property should be in the following format: array(
76
+	 * 'route_defined_by_action_param' => 'Model_Name')
77
+	 *
78
+	 * @var array $_cpt_model_names
79
+	 */
80
+	protected $_cpt_model_names = array();
81
+
82
+
83
+	/**
84
+	 * @var EE_CPT_Base
85
+	 */
86
+	protected $_cpt_model_obj = false;
87
+
88
+
89
+
90
+	/**
91
+	 * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
92
+	 * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
93
+	 * the _register_autosave_containers() method so that we don't override any other containers already registered.
94
+	 * Registration of containers should be done before load_page_dependencies() is run.
95
+	 *
96
+	 * @var array()
97
+	 */
98
+	protected $_autosave_containers = array();
99
+	protected $_autosave_fields = array();
100
+
101
+	/**
102
+	 * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
103
+	 * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
104
+	 *
105
+	 * @var array
106
+	 */
107
+	protected $_pagenow_map;
108
+
109
+
110
+
111
+	/**
112
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
113
+	 * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
114
+	 * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
115
+	 * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
116
+	 * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
117
+	 *
118
+	 * @access protected
119
+	 * @abstract
120
+	 * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
121
+	 * @param  EE_CPT_Base $post    The post object of the cpt that was saved.
122
+	 * @return void
123
+	 */
124
+	abstract protected function _insert_update_cpt_item($post_id, $post);
125
+
126
+
127
+
128
+	/**
129
+	 * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
130
+	 *
131
+	 * @abstract
132
+	 * @access public
133
+	 * @param  string $post_id The ID of the cpt that was trashed
134
+	 * @return void
135
+	 */
136
+	abstract public function trash_cpt_item($post_id);
137
+
138
+
139
+
140
+	/**
141
+	 * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
+	 *
143
+	 * @param  string $post_id theID of the cpt that was untrashed
144
+	 * @return void
145
+	 */
146
+	abstract public function restore_cpt_item($post_id);
147
+
148
+
149
+
150
+	/**
151
+	 * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
152
+	 * from the db
153
+	 *
154
+	 * @param  string $post_id the ID of the cpt that was deleted
155
+	 * @return void
156
+	 */
157
+	abstract public function delete_cpt_item($post_id);
158
+
159
+
160
+
161
+	/**
162
+	 * Just utilizing the method EE_Admin exposes for doing things before page setup.
163
+	 *
164
+	 * @access protected
165
+	 * @return void
166
+	 */
167
+	protected function _before_page_setup()
168
+	{
169
+		$page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
170
+		$this->_cpt_routes = array_merge(array(
171
+			'create_new' => $this->page_slug,
172
+			'edit'       => $this->page_slug,
173
+			'trash'      => $this->page_slug,
174
+		), $this->_cpt_routes);
175
+		//let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
176
+		$this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[$this->_req_data['action']])
177
+			? get_post_type_object($this->_cpt_routes[$this->_req_data['action']])
178
+			: get_post_type_object($page);
179
+		//tweak pagenow for page loading.
180
+		if ( ! $this->_pagenow_map) {
181
+			$this->_pagenow_map = array(
182
+				'create_new' => 'post-new.php',
183
+				'edit'       => 'post.php',
184
+				'trash'      => 'post.php',
185
+			);
186
+		}
187
+		add_action('current_screen', array($this, 'modify_pagenow'));
188
+		//TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
189
+		//get current page from autosave
190
+		$current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
191
+			? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
192
+			: null;
193
+		$this->_current_page = isset($this->_req_data['current_page'])
194
+			? $this->_req_data['current_page']
195
+			: $current_page;
196
+		//autosave... make sure its only for the correct page
197
+		//if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
198
+			//setup autosave ajax hook
199
+			//add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
200
+		//}
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * Simply ensure that we simulate the correct post route for cpt screens
207
+	 *
208
+	 * @param WP_Screen $current_screen
209
+	 * @return void
210
+	 */
211
+	public function modify_pagenow($current_screen)
212
+	{
213
+		global $pagenow, $hook_suffix;
214
+		//possibly reset pagenow.
215
+		if ( ! empty($this->_req_data['page'])
216
+			 && $this->_req_data['page'] == $this->page_slug
217
+			 && ! empty($this->_req_data['action'])
218
+			 && isset($this->_pagenow_map[$this->_req_data['action']])
219
+		) {
220
+			$pagenow = $this->_pagenow_map[$this->_req_data['action']];
221
+			$hook_suffix = $pagenow;
222
+		}
223
+	}
224
+
225
+
226
+
227
+	/**
228
+	 * This method is used to register additional autosave containers to the _autosave_containers property.
229
+	 *
230
+	 * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
231
+	 *       automatically register the id for the post metabox as a container.
232
+	 * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
+	 *                    you would send along the id of a metabox container.
234
+	 * @return void
235
+	 */
236
+	protected function _register_autosave_containers($ids)
237
+	{
238
+		$this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
245
+	 * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
246
+	 */
247
+	protected function _set_autosave_containers()
248
+	{
249
+		global $wp_meta_boxes;
250
+		$containers = array();
251
+		if (empty($wp_meta_boxes)) {
252
+			return;
253
+		}
254
+		$current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : array();
255
+		foreach ($current_metaboxes as $box_context) {
256
+			foreach ($box_context as $box_details) {
257
+				foreach ($box_details as $box) {
258
+					if (
259
+						is_array($box['callback'])
260
+						&& (
261
+							$box['callback'][0] instanceof EE_Admin_Page
262
+							|| $box['callback'][0] instanceof EE_Admin_Hooks
263
+						)
264
+					) {
265
+						$containers[] = $box['id'];
266
+					}
267
+				}
268
+			}
269
+		}
270
+		$this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
271
+		//add hidden inputs container
272
+		$this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
273
+	}
274
+
275
+
276
+
277
+	protected function _load_autosave_scripts_styles()
278
+	{
279
+		/*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
280 280
         wp_enqueue_script('cpt-autosave');/**/ //todo re-enable when we start doing autosave again in 4.2
281 281
 
282
-        //filter _autosave_containers
283
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
284
-            $this->_autosave_containers, $this);
285
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
286
-            $containers, $this);
287
-
288
-        wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
289
-            $containers); //todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
290
-
291
-        $unsaved_data_msg = array(
292
-            'eventmsg'     => sprintf(__("The changes you made to this %s will be lost if you navigate away from this page.",
293
-                'event_espresso'), $this->_cpt_object->labels->singular_name),
294
-            'inputChanged' => 0,
295
-        );
296
-        wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
297
-    }
298
-
299
-
300
-
301
-    public function load_page_dependencies()
302
-    {
303
-        try {
304
-            $this->_load_page_dependencies();
305
-        } catch (EE_Error $e) {
306
-            $e->get_error();
307
-        }
308
-    }
309
-
310
-
311
-
312
-    /**
313
-     * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
314
-     *
315
-     * @access protected
316
-     * @return void
317
-     */
318
-    protected function _load_page_dependencies()
319
-    {
320
-        //we only add stuff if this is a cpt_route!
321
-        if ( ! $this->_cpt_route) {
322
-            parent::_load_page_dependencies();
323
-            return;
324
-        }
325
-        // now let's do some automatic filters into the wp_system
326
-        // and we'll check to make sure the CHILD class
327
-        // automatically has the required methods in place.
328
-        // the following filters are for setting all the redirects
329
-        // on DEFAULT WP custom post type actions
330
-        // let's add a hidden input to the post-edit form
331
-        // so we know when we have to trigger our custom redirects!
332
-        // Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
333
-        add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
334
-        // inject our Admin page nav tabs...
335
-        // let's make sure the nav tabs are set if they aren't already
336
-        // if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
337
-        add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
338
-        // modify the post_updated messages array
339
-        add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
340
-        // add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE,
341
-        // cpts use the same format for shortlinks as posts!
342
-        add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
343
-        // This basically allows us to change the title of the "publish" metabox area
344
-        // on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
345
-        if ( ! empty($this->_labels['publishbox'])) {
346
-            $box_label = is_array($this->_labels['publishbox'])
347
-                         && isset($this->_labels['publishbox'][$this->_req_action])
348
-                    ? $this->_labels['publishbox'][$this->_req_action]
349
-                    : $this->_labels['publishbox'];
350
-            add_meta_box(
351
-                'submitdiv',
352
-                $box_label,
353
-                'post_submit_meta_box',
354
-                $this->_cpt_routes[$this->_req_action],
355
-                'side',
356
-                'core'
357
-            );
358
-        }
359
-        //let's add page_templates metabox if this cpt added support for it.
360
-        if ($this->_supports_page_templates($this->_cpt_object->name)) {
361
-            add_meta_box(
362
-                'page_templates',
363
-                __('Page Template', 'event_espresso'),
364
-                array($this, 'page_template_meta_box'),
365
-                $this->_cpt_routes[$this->_req_action],
366
-                'side',
367
-                'default'
368
-            );
369
-        }
370
-        //this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
371
-        if (method_exists($this, 'extra_permalink_field_buttons')) {
372
-            add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
373
-        }
374
-        //add preview button
375
-        add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
376
-        //insert our own post_stati dropdown
377
-        add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
378
-        //This allows adding additional information to the publish post submitbox on the wp post edit form
379
-        if (method_exists($this, 'extra_misc_actions_publish_box')) {
380
-            add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
381
-        }
382
-        // This allows for adding additional stuff after the title field on the wp post edit form.
383
-        // This is also before the wp_editor for post description field.
384
-        if (method_exists($this, 'edit_form_after_title')) {
385
-            add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
386
-        }
387
-        /**
388
-         * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
389
-         */
390
-        add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
391
-        parent::_load_page_dependencies();
392
-        // notice we are ALSO going to load the pagenow hook set for this route
393
-        // (see _before_page_setup for the reset of the pagenow global ).
394
-        // This is for any plugins that are doing things properly
395
-        // and hooking into the load page hook for core wp cpt routes.
396
-        global $pagenow;
397
-        do_action('load-' . $pagenow);
398
-        $this->modify_current_screen();
399
-        add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
400
-        //we route REALLY early.
401
-        try {
402
-            $this->_route_admin_request();
403
-        } catch (EE_Error $e) {
404
-            $e->get_error();
405
-        }
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * Since we don't want users going to default core wp routes, this will check any wp urls run through the
412
-     * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
413
-     * route instead.
414
-     *
415
-     * @param string $good_protocol_url The escaped url.
416
-     * @param string $original_url      The original url.
417
-     * @param string $_context          The context sent to the esc_url method.
418
-     * @return string possibly a new url for our route.
419
-     */
420
-    public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
421
-    {
422
-        $routes_to_match = array(
423
-            0 => array(
424
-                'edit.php?post_type=espresso_attendees',
425
-                'admin.php?page=espresso_registrations&action=contact_list',
426
-            ),
427
-            1 => array(
428
-                'edit.php?post_type=' . $this->_cpt_object->name,
429
-                'admin.php?page=' . $this->_cpt_object->name,
430
-            ),
431
-        );
432
-        foreach ($routes_to_match as $route_matches) {
433
-            if (strpos($good_protocol_url, $route_matches[0]) !== false) {
434
-                return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
435
-            }
436
-        }
437
-        return $good_protocol_url;
438
-    }
439
-
440
-
441
-
442
-    /**
443
-     * Determine whether the current cpt supports page templates or not.
444
-     *
445
-     * @since %VER%
446
-     * @param string $cpt_name The cpt slug we're checking on.
447
-     * @return bool True supported, false not.
448
-     */
449
-    private function _supports_page_templates($cpt_name)
450
-    {
451
-
452
-        $cpt_args = EE_Register_CPTs::get_CPTs();
453
-        $cpt_args = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : array();
454
-        $cpt_has_support = ! empty($cpt_args['page_templates']);
455
-
456
-        //if the installed version of WP is > 4.7 we do some additional checks.
457
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
458
-            $post_templates = wp_get_theme()->get_post_templates();
459
-            //if there are $post_templates for this cpt, then we return false for this method because
460
-            //that means we aren't going to load our page template manager and leave that up to the native
461
-            //cpt template manager.
462
-            $cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
463
-        }
464
-
465
-        return $cpt_has_support;
466
-    }
467
-
468
-
469
-    /**
470
-     * Callback for the page_templates metabox selector.
471
-     *
472
-     * @since %VER%
473
-     * @return void
474
-     */
475
-    public function page_template_meta_box()
476
-    {
477
-        global $post;
478
-        $template = '';
479
-
480
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
481
-            $page_template_count = count(get_page_templates());
482
-        } else {
483
-            $page_template_count = count(get_page_templates($post));
484
-        };
485
-
486
-        if ($page_template_count) {
487
-            $page_template = get_post_meta($post->ID, '_wp_page_template', true);
488
-            $template      = ! empty($page_template) ? $page_template : '';
489
-        }
490
-        ?>
282
+		//filter _autosave_containers
283
+		$containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
284
+			$this->_autosave_containers, $this);
285
+		$containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
286
+			$containers, $this);
287
+
288
+		wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
289
+			$containers); //todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
290
+
291
+		$unsaved_data_msg = array(
292
+			'eventmsg'     => sprintf(__("The changes you made to this %s will be lost if you navigate away from this page.",
293
+				'event_espresso'), $this->_cpt_object->labels->singular_name),
294
+			'inputChanged' => 0,
295
+		);
296
+		wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
297
+	}
298
+
299
+
300
+
301
+	public function load_page_dependencies()
302
+	{
303
+		try {
304
+			$this->_load_page_dependencies();
305
+		} catch (EE_Error $e) {
306
+			$e->get_error();
307
+		}
308
+	}
309
+
310
+
311
+
312
+	/**
313
+	 * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
314
+	 *
315
+	 * @access protected
316
+	 * @return void
317
+	 */
318
+	protected function _load_page_dependencies()
319
+	{
320
+		//we only add stuff if this is a cpt_route!
321
+		if ( ! $this->_cpt_route) {
322
+			parent::_load_page_dependencies();
323
+			return;
324
+		}
325
+		// now let's do some automatic filters into the wp_system
326
+		// and we'll check to make sure the CHILD class
327
+		// automatically has the required methods in place.
328
+		// the following filters are for setting all the redirects
329
+		// on DEFAULT WP custom post type actions
330
+		// let's add a hidden input to the post-edit form
331
+		// so we know when we have to trigger our custom redirects!
332
+		// Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
333
+		add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
334
+		// inject our Admin page nav tabs...
335
+		// let's make sure the nav tabs are set if they aren't already
336
+		// if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
337
+		add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
338
+		// modify the post_updated messages array
339
+		add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
340
+		// add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE,
341
+		// cpts use the same format for shortlinks as posts!
342
+		add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
343
+		// This basically allows us to change the title of the "publish" metabox area
344
+		// on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
345
+		if ( ! empty($this->_labels['publishbox'])) {
346
+			$box_label = is_array($this->_labels['publishbox'])
347
+						 && isset($this->_labels['publishbox'][$this->_req_action])
348
+					? $this->_labels['publishbox'][$this->_req_action]
349
+					: $this->_labels['publishbox'];
350
+			add_meta_box(
351
+				'submitdiv',
352
+				$box_label,
353
+				'post_submit_meta_box',
354
+				$this->_cpt_routes[$this->_req_action],
355
+				'side',
356
+				'core'
357
+			);
358
+		}
359
+		//let's add page_templates metabox if this cpt added support for it.
360
+		if ($this->_supports_page_templates($this->_cpt_object->name)) {
361
+			add_meta_box(
362
+				'page_templates',
363
+				__('Page Template', 'event_espresso'),
364
+				array($this, 'page_template_meta_box'),
365
+				$this->_cpt_routes[$this->_req_action],
366
+				'side',
367
+				'default'
368
+			);
369
+		}
370
+		//this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
371
+		if (method_exists($this, 'extra_permalink_field_buttons')) {
372
+			add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
373
+		}
374
+		//add preview button
375
+		add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
376
+		//insert our own post_stati dropdown
377
+		add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
378
+		//This allows adding additional information to the publish post submitbox on the wp post edit form
379
+		if (method_exists($this, 'extra_misc_actions_publish_box')) {
380
+			add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
381
+		}
382
+		// This allows for adding additional stuff after the title field on the wp post edit form.
383
+		// This is also before the wp_editor for post description field.
384
+		if (method_exists($this, 'edit_form_after_title')) {
385
+			add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
386
+		}
387
+		/**
388
+		 * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
389
+		 */
390
+		add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
391
+		parent::_load_page_dependencies();
392
+		// notice we are ALSO going to load the pagenow hook set for this route
393
+		// (see _before_page_setup for the reset of the pagenow global ).
394
+		// This is for any plugins that are doing things properly
395
+		// and hooking into the load page hook for core wp cpt routes.
396
+		global $pagenow;
397
+		do_action('load-' . $pagenow);
398
+		$this->modify_current_screen();
399
+		add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
400
+		//we route REALLY early.
401
+		try {
402
+			$this->_route_admin_request();
403
+		} catch (EE_Error $e) {
404
+			$e->get_error();
405
+		}
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * Since we don't want users going to default core wp routes, this will check any wp urls run through the
412
+	 * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
413
+	 * route instead.
414
+	 *
415
+	 * @param string $good_protocol_url The escaped url.
416
+	 * @param string $original_url      The original url.
417
+	 * @param string $_context          The context sent to the esc_url method.
418
+	 * @return string possibly a new url for our route.
419
+	 */
420
+	public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
421
+	{
422
+		$routes_to_match = array(
423
+			0 => array(
424
+				'edit.php?post_type=espresso_attendees',
425
+				'admin.php?page=espresso_registrations&action=contact_list',
426
+			),
427
+			1 => array(
428
+				'edit.php?post_type=' . $this->_cpt_object->name,
429
+				'admin.php?page=' . $this->_cpt_object->name,
430
+			),
431
+		);
432
+		foreach ($routes_to_match as $route_matches) {
433
+			if (strpos($good_protocol_url, $route_matches[0]) !== false) {
434
+				return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
435
+			}
436
+		}
437
+		return $good_protocol_url;
438
+	}
439
+
440
+
441
+
442
+	/**
443
+	 * Determine whether the current cpt supports page templates or not.
444
+	 *
445
+	 * @since %VER%
446
+	 * @param string $cpt_name The cpt slug we're checking on.
447
+	 * @return bool True supported, false not.
448
+	 */
449
+	private function _supports_page_templates($cpt_name)
450
+	{
451
+
452
+		$cpt_args = EE_Register_CPTs::get_CPTs();
453
+		$cpt_args = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : array();
454
+		$cpt_has_support = ! empty($cpt_args['page_templates']);
455
+
456
+		//if the installed version of WP is > 4.7 we do some additional checks.
457
+		if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
458
+			$post_templates = wp_get_theme()->get_post_templates();
459
+			//if there are $post_templates for this cpt, then we return false for this method because
460
+			//that means we aren't going to load our page template manager and leave that up to the native
461
+			//cpt template manager.
462
+			$cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
463
+		}
464
+
465
+		return $cpt_has_support;
466
+	}
467
+
468
+
469
+	/**
470
+	 * Callback for the page_templates metabox selector.
471
+	 *
472
+	 * @since %VER%
473
+	 * @return void
474
+	 */
475
+	public function page_template_meta_box()
476
+	{
477
+		global $post;
478
+		$template = '';
479
+
480
+		if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
481
+			$page_template_count = count(get_page_templates());
482
+		} else {
483
+			$page_template_count = count(get_page_templates($post));
484
+		};
485
+
486
+		if ($page_template_count) {
487
+			$page_template = get_post_meta($post->ID, '_wp_page_template', true);
488
+			$template      = ! empty($page_template) ? $page_template : '';
489
+		}
490
+		?>
491 491
         <p><strong><?php _e('Template') ?></strong></p>
492 492
         <label class="screen-reader-text" for="page_template"><?php _e('Page Template') ?></label><select
493 493
             name="page_template" id="page_template">
@@ -495,450 +495,450 @@  discard block
 block discarded – undo
495 495
         <?php page_template_dropdown($template); ?>
496 496
     </select>
497 497
         <?php
498
-    }
499
-
500
-
501
-
502
-    /**
503
-     * if this post is a draft or scheduled post then we provide a preview button for user to click
504
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
505
-     *
506
-     * @param  string $return    the current html
507
-     * @param  int    $id        the post id for the page
508
-     * @param  string $new_title What the title is
509
-     * @param  string $new_slug  what the slug is
510
-     * @return string            The new html string for the permalink area
511
-     */
512
-    public function preview_button_html($return, $id, $new_title, $new_slug)
513
-    {
514
-        $post = get_post($id);
515
-        if ('publish' !== get_post_status($post)) {
516
-            //include shims for the `get_preview_post_link` function
517
-            require_once( EE_CORE . 'wordpress-shims.php' );
518
-            $return .= '<span_id="view-post-btn"><a target="_blank" href="'
519
-                       . get_preview_post_link($id)
520
-                       . '" class="button button-small">'
521
-                       . __('Preview', 'event_espresso')
522
-                       . '</a></span>'
523
-                       . "\n";
524
-        }
525
-        return $return;
526
-    }
527
-
528
-
529
-
530
-    /**
531
-     * add our custom post stati dropdown on the wp post page for this cpt
532
-     *
533
-     * @return void
534
-     */
535
-    public function custom_post_stati_dropdown()
536
-    {
537
-
538
-        $statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
539
-        $cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
540
-            ? $statuses[$this->_cpt_model_obj->status()]
541
-            : '';
542
-        $template_args    = array(
543
-            'cur_status'            => $this->_cpt_model_obj->status(),
544
-            'statuses'              => $statuses,
545
-            'cur_status_label'      => $cur_status_label,
546
-            'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
547
-        );
548
-        //we'll add a trash post status (WP doesn't add one for some reason)
549
-        if ($this->_cpt_model_obj->status() === 'trash') {
550
-            $template_args['cur_status_label'] = __('Trashed', 'event_espresso');
551
-            $statuses['trash']                 = __('Trashed', 'event_espresso');
552
-            $template_args['statuses']         = $statuses;
553
-        }
554
-
555
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
556
-        EEH_Template::display_template($template, $template_args);
557
-    }
558
-
559
-
560
-
561
-    public function setup_autosave_hooks()
562
-    {
563
-        $this->_set_autosave_containers();
564
-        $this->_load_autosave_scripts_styles();
565
-    }
566
-
567
-
568
-
569
-    /**
570
-     * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
571
-     * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
572
-     * for the nonce in here, but then this method looks for two things:
573
-     * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
574
-     * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
575
-     * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
576
-     * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
577
-     * template args.
578
-     *    1. $template_args['error'] = IF there is an error you can add the message in here.
579
-     *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
580
-     *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
581
-     *    $this->_template_args['data']['items'] = array(
582
-     *        'event-datetime-ids' => '1,2,3';
583
-     *    );
584
-     *    Keep in mind the following things:
585
-     *    - "where" index is for the input with the id as that string.
586
-     *    - "what" index is what will be used for the value of that input.
587
-     *
588
-     * @return void
589
-     */
590
-    public function do_extra_autosave_stuff()
591
-    {
592
-        //next let's check for the autosave nonce (we'll use _verify_nonce )
593
-        $nonce = isset($this->_req_data['autosavenonce'])
594
-                ? $this->_req_data['autosavenonce']
595
-                : null;
596
-        $this->_verify_nonce($nonce, 'autosave');
597
-        //make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
598
-        if ( ! defined('DOING_AUTOSAVE')) {
599
-            define('DOING_AUTOSAVE', true);
600
-        }
601
-        //if we made it here then the nonce checked out.  Let's run our methods and actions
602
-        $autosave = "_ee_autosave_{$this->_current_view}";
603
-        if (method_exists($this, $autosave)) {
604
-            $this->$autosave();
605
-        } else {
606
-            $this->_template_args['success'] = true;
607
-        }
608
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
609
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
610
-        //now let's return json
611
-        $this->_return_json();
612
-    }
613
-
614
-
615
-
616
-    /**
617
-     * This takes care of setting up default routes and pages that utilize the core WP admin pages.
618
-     * Child classes can override the defaults (in cases for adding metaboxes etc.)
619
-     * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
620
-     *
621
-     * @access protected
622
-     * @throws EE_Error
623
-     * @return void
624
-     */
625
-    protected function _extend_page_config_for_cpt()
626
-    {
627
-        //before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
628
-        if (isset($this->_req_data['page']) && $this->_req_data['page'] !== $this->page_slug) {
629
-            return;
630
-        }
631
-        //set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
632
-        if ( ! empty($this->_cpt_object)) {
633
-            $this->_page_routes = array_merge(array(
634
-                'create_new' => '_create_new_cpt_item',
635
-                'edit'       => '_edit_cpt_item',
636
-            ), $this->_page_routes);
637
-            $this->_page_config = array_merge(array(
638
-                'create_new' => array(
639
-                    'nav'           => array(
640
-                        'label' => $this->_cpt_object->labels->add_new_item,
641
-                        'order' => 5,
642
-                    ),
643
-                    'require_nonce' => false,
644
-                ),
645
-                'edit'       => array(
646
-                    'nav'           => array(
647
-                        'label'      => $this->_cpt_object->labels->edit_item,
648
-                        'order'      => 5,
649
-                        'persistent' => false,
650
-                        'url'        => '',
651
-                    ),
652
-                    'require_nonce' => false,
653
-                ),
654
-            ),
655
-                $this->_page_config
656
-            );
657
-        }
658
-        //load the next section only if this is a matching cpt route as set in the cpt routes array.
659
-        if ( ! isset($this->_cpt_routes[$this->_req_action])) {
660
-            return;
661
-        }
662
-        $this->_cpt_route = isset($this->_cpt_routes[$this->_req_action]) ? true : false;
663
-        //add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
664
-        if (empty($this->_cpt_object)) {
665
-            $msg = sprintf(__('This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).'),
666
-                $this->page_slug, $this->_req_action, get_class($this));
667
-            throw new EE_Error($msg);
668
-        }
669
-        if ($this->_cpt_route) {
670
-            $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
671
-            $this->_set_model_object($id);
672
-        }
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
679
-     *
680
-     * @access protected
681
-     * @param int  $id The id to retrieve the model object for. If empty we set a default object.
682
-     * @param bool $ignore_route_check
683
-     * @param string $req_type whether the current route is for inserting, updating, or deleting the CPT
684
-     * @throws EE_Error
685
-     */
686
-    protected function _set_model_object($id = null, $ignore_route_check = false, $req_type = '')
687
-    {
688
-        $model = null;
689
-        if (
690
-            empty($this->_cpt_model_names)
691
-            || (
692
-                ! $ignore_route_check
693
-                && ! isset($this->_cpt_routes[$this->_req_action])
694
-            ) || (
695
-                $this->_cpt_model_obj instanceof EE_CPT_Base
696
-                && $this->_cpt_model_obj->ID() === $id
697
-            )
698
-        ) {
699
-            //get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
700
-            return;
701
-        }
702
-        //if ignore_route_check is true, then get the model name via EE_Register_CPTs
703
-        if ($ignore_route_check) {
704
-            $model_names = EE_Register_CPTs::get_cpt_model_names();
705
-            $post_type   = get_post_type($id);
706
-            if (isset($model_names[$post_type])) {
707
-                $model = EE_Registry::instance()->load_model($model_names[$post_type]);
708
-            }
709
-        } else {
710
-            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
711
-        }
712
-        if ($model instanceof EEM_Base) {
713
-            $this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
714
-        }
715
-        do_action(
716
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
717
-            $this->_cpt_model_obj,
718
-            $req_type
719
-        );
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * admin_init_global
726
-     * This runs all the code that we want executed within the WP admin_init hook.
727
-     * This method executes for ALL EE Admin pages.
728
-     *
729
-     * @access public
730
-     * @return void
731
-     */
732
-    public function admin_init_global()
733
-    {
734
-        $post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
735
-        //its possible this is a new save so let's catch that instead
736
-        $post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
737
-        $post_type = $post ? $post->post_type : false;
738
-        $current_route = isset($this->_req_data['current_route'])
739
-            ? $this->_req_data['current_route']
740
-            : 'shouldneverwork';
741
-        $route_to_check = $post_type && isset($this->_cpt_routes[$current_route])
742
-            ? $this->_cpt_routes[$current_route]
743
-            : '';
744
-        add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
745
-        add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
746
-        if ($post_type === $route_to_check) {
747
-            add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
748
-        }
749
-        //now let's filter redirect if we're on a revision page and the revision is for an event CPT.
750
-        $revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
751
-        if ( ! empty($revision)) {
752
-            $action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
753
-            //doing a restore?
754
-            if ( ! empty($action) && $action === 'restore') {
755
-                //get post for revision
756
-                $rev_post = get_post($revision);
757
-                $rev_parent = get_post($rev_post->post_parent);
758
-                //only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
759
-                if ($rev_parent && $rev_parent->post_type === $this->page_slug) {
760
-                    add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
761
-                    //restores of revisions
762
-                    add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
763
-                }
764
-            }
765
-        }
766
-        //NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
767
-        if ($post_type && $post_type === $route_to_check) {
768
-            //$post_id, $post
769
-            add_action('save_post', array($this, 'insert_update'), 10, 3);
770
-            //$post_id
771
-            add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
772
-            add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
773
-            add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
774
-            add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
775
-        }
776
-    }
777
-
778
-
779
-
780
-    /**
781
-     * Callback for the WordPress trashed_post hook.
782
-     * Execute some basic checks before calling the trash_cpt_item declared in the child class.
783
-     *
784
-     * @param int $post_id
785
-     * @throws \EE_Error
786
-     */
787
-    public function before_trash_cpt_item($post_id)
788
-    {
789
-        $this->_set_model_object($post_id, true, 'trash');
790
-        //if our cpt object isn't existent then get out immediately.
791
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
792
-            return;
793
-        }
794
-        $this->trash_cpt_item($post_id);
795
-    }
796
-
797
-
798
-
799
-    /**
800
-     * Callback for the WordPress untrashed_post hook.
801
-     * Execute some basic checks before calling the restore_cpt_method in the child class.
802
-     *
803
-     * @param $post_id
804
-     * @throws \EE_Error
805
-     */
806
-    public function before_restore_cpt_item($post_id)
807
-    {
808
-        $this->_set_model_object($post_id, true, 'restore');
809
-        //if our cpt object isn't existent then get out immediately.
810
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
811
-            return;
812
-        }
813
-        $this->restore_cpt_item($post_id);
814
-    }
815
-
816
-
817
-
818
-    /**
819
-     * Callback for the WordPress after_delete_post hook.
820
-     * Execute some basic checks before calling the delete_cpt_item method in the child class.
821
-     *
822
-     * @param $post_id
823
-     * @throws \EE_Error
824
-     */
825
-    public function before_delete_cpt_item($post_id)
826
-    {
827
-        $this->_set_model_object($post_id, true, 'delete');
828
-        //if our cpt object isn't existent then get out immediately.
829
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
830
-            return;
831
-        }
832
-        $this->delete_cpt_item($post_id);
833
-    }
834
-
835
-
836
-
837
-    /**
838
-     * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
839
-     * accordingly.
840
-     *
841
-     * @access public
842
-     * @throws EE_Error
843
-     * @return void
844
-     */
845
-    public function verify_cpt_object()
846
-    {
847
-        $label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
848
-        // verify event object
849
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
850
-            throw new EE_Error(sprintf(__('Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
851
-                    'event_espresso'), $label));
852
-        }
853
-        //if auto-draft then throw an error
854
-        if ($this->_cpt_model_obj->get('status') === 'auto-draft') {
855
-            EE_Error::overwrite_errors();
856
-            EE_Error::add_error(sprintf(__('This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.'),
857
-                    $label), __FILE__, __FUNCTION__, __LINE__);
858
-        }
859
-    }
860
-
861
-
862
-
863
-    /**
864
-     * admin_footer_scripts_global
865
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
866
-     * will apply on ALL EE_Admin pages.
867
-     *
868
-     * @access public
869
-     * @return void
870
-     */
871
-    public function admin_footer_scripts_global()
872
-    {
873
-        $this->_add_admin_page_ajax_loading_img();
874
-        $this->_add_admin_page_overlay();
875
-    }
876
-
877
-
878
-
879
-    /**
880
-     * add in any global scripts for cpt routes
881
-     *
882
-     * @return void
883
-     */
884
-    public function load_global_scripts_styles()
885
-    {
886
-        parent::load_global_scripts_styles();
887
-        if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
888
-            //setup custom post status object for localize script but only if we've got a cpt object
889
-            $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
890
-            if ( ! empty($statuses)) {
891
-                //get ALL statuses!
892
-                $statuses = $this->_cpt_model_obj->get_all_post_statuses();
893
-                //setup object
894
-                $ee_cpt_statuses = array();
895
-                foreach ($statuses as $status => $label) {
896
-                    $ee_cpt_statuses[$status] = array(
897
-                        'label'      => $label,
898
-                        'save_label' => sprintf(__('Save as %s', 'event_espresso'), $label),
899
-                    );
900
-                }
901
-                wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
902
-            }
903
-        }
904
-    }
905
-
906
-
907
-
908
-    /**
909
-     * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
910
-     * insert/updates
911
-     *
912
-     * @param  int     $post_id ID of post being updated
913
-     * @param  WP_Post $post    Post object from WP
914
-     * @param  bool    $update  Whether this is an update or a new save.
915
-     * @return void
916
-     * @throws \EE_Error
917
-     */
918
-    public function insert_update($post_id, $post, $update)
919
-    {
920
-        //make sure that if this is a revision OR trash action that we don't do any updates!
921
-        if (
922
-            isset($this->_req_data['action'])
923
-            && (
924
-                $this->_req_data['action'] === 'restore'
925
-                || $this->_req_data['action'] === 'trash'
926
-            )
927
-        ) {
928
-            return;
929
-        }
930
-        $this->_set_model_object($post_id, true, 'insert_update');
931
-        //if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
932
-        if ($update
933
-            && (
934
-                ! $this->_cpt_model_obj instanceof EE_CPT_Base
935
-                || $this->_cpt_model_obj->ID() !== $post_id
936
-            )
937
-        ) {
938
-            return;
939
-        }
940
-        //check for autosave and update our req_data property accordingly.
941
-        /*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
498
+	}
499
+
500
+
501
+
502
+	/**
503
+	 * if this post is a draft or scheduled post then we provide a preview button for user to click
504
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
505
+	 *
506
+	 * @param  string $return    the current html
507
+	 * @param  int    $id        the post id for the page
508
+	 * @param  string $new_title What the title is
509
+	 * @param  string $new_slug  what the slug is
510
+	 * @return string            The new html string for the permalink area
511
+	 */
512
+	public function preview_button_html($return, $id, $new_title, $new_slug)
513
+	{
514
+		$post = get_post($id);
515
+		if ('publish' !== get_post_status($post)) {
516
+			//include shims for the `get_preview_post_link` function
517
+			require_once( EE_CORE . 'wordpress-shims.php' );
518
+			$return .= '<span_id="view-post-btn"><a target="_blank" href="'
519
+					   . get_preview_post_link($id)
520
+					   . '" class="button button-small">'
521
+					   . __('Preview', 'event_espresso')
522
+					   . '</a></span>'
523
+					   . "\n";
524
+		}
525
+		return $return;
526
+	}
527
+
528
+
529
+
530
+	/**
531
+	 * add our custom post stati dropdown on the wp post page for this cpt
532
+	 *
533
+	 * @return void
534
+	 */
535
+	public function custom_post_stati_dropdown()
536
+	{
537
+
538
+		$statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
539
+		$cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
540
+			? $statuses[$this->_cpt_model_obj->status()]
541
+			: '';
542
+		$template_args    = array(
543
+			'cur_status'            => $this->_cpt_model_obj->status(),
544
+			'statuses'              => $statuses,
545
+			'cur_status_label'      => $cur_status_label,
546
+			'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
547
+		);
548
+		//we'll add a trash post status (WP doesn't add one for some reason)
549
+		if ($this->_cpt_model_obj->status() === 'trash') {
550
+			$template_args['cur_status_label'] = __('Trashed', 'event_espresso');
551
+			$statuses['trash']                 = __('Trashed', 'event_espresso');
552
+			$template_args['statuses']         = $statuses;
553
+		}
554
+
555
+		$template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
556
+		EEH_Template::display_template($template, $template_args);
557
+	}
558
+
559
+
560
+
561
+	public function setup_autosave_hooks()
562
+	{
563
+		$this->_set_autosave_containers();
564
+		$this->_load_autosave_scripts_styles();
565
+	}
566
+
567
+
568
+
569
+	/**
570
+	 * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
571
+	 * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
572
+	 * for the nonce in here, but then this method looks for two things:
573
+	 * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
574
+	 * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
575
+	 * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
576
+	 * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
577
+	 * template args.
578
+	 *    1. $template_args['error'] = IF there is an error you can add the message in here.
579
+	 *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
580
+	 *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
581
+	 *    $this->_template_args['data']['items'] = array(
582
+	 *        'event-datetime-ids' => '1,2,3';
583
+	 *    );
584
+	 *    Keep in mind the following things:
585
+	 *    - "where" index is for the input with the id as that string.
586
+	 *    - "what" index is what will be used for the value of that input.
587
+	 *
588
+	 * @return void
589
+	 */
590
+	public function do_extra_autosave_stuff()
591
+	{
592
+		//next let's check for the autosave nonce (we'll use _verify_nonce )
593
+		$nonce = isset($this->_req_data['autosavenonce'])
594
+				? $this->_req_data['autosavenonce']
595
+				: null;
596
+		$this->_verify_nonce($nonce, 'autosave');
597
+		//make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
598
+		if ( ! defined('DOING_AUTOSAVE')) {
599
+			define('DOING_AUTOSAVE', true);
600
+		}
601
+		//if we made it here then the nonce checked out.  Let's run our methods and actions
602
+		$autosave = "_ee_autosave_{$this->_current_view}";
603
+		if (method_exists($this, $autosave)) {
604
+			$this->$autosave();
605
+		} else {
606
+			$this->_template_args['success'] = true;
607
+		}
608
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
609
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
610
+		//now let's return json
611
+		$this->_return_json();
612
+	}
613
+
614
+
615
+
616
+	/**
617
+	 * This takes care of setting up default routes and pages that utilize the core WP admin pages.
618
+	 * Child classes can override the defaults (in cases for adding metaboxes etc.)
619
+	 * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
620
+	 *
621
+	 * @access protected
622
+	 * @throws EE_Error
623
+	 * @return void
624
+	 */
625
+	protected function _extend_page_config_for_cpt()
626
+	{
627
+		//before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
628
+		if (isset($this->_req_data['page']) && $this->_req_data['page'] !== $this->page_slug) {
629
+			return;
630
+		}
631
+		//set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
632
+		if ( ! empty($this->_cpt_object)) {
633
+			$this->_page_routes = array_merge(array(
634
+				'create_new' => '_create_new_cpt_item',
635
+				'edit'       => '_edit_cpt_item',
636
+			), $this->_page_routes);
637
+			$this->_page_config = array_merge(array(
638
+				'create_new' => array(
639
+					'nav'           => array(
640
+						'label' => $this->_cpt_object->labels->add_new_item,
641
+						'order' => 5,
642
+					),
643
+					'require_nonce' => false,
644
+				),
645
+				'edit'       => array(
646
+					'nav'           => array(
647
+						'label'      => $this->_cpt_object->labels->edit_item,
648
+						'order'      => 5,
649
+						'persistent' => false,
650
+						'url'        => '',
651
+					),
652
+					'require_nonce' => false,
653
+				),
654
+			),
655
+				$this->_page_config
656
+			);
657
+		}
658
+		//load the next section only if this is a matching cpt route as set in the cpt routes array.
659
+		if ( ! isset($this->_cpt_routes[$this->_req_action])) {
660
+			return;
661
+		}
662
+		$this->_cpt_route = isset($this->_cpt_routes[$this->_req_action]) ? true : false;
663
+		//add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
664
+		if (empty($this->_cpt_object)) {
665
+			$msg = sprintf(__('This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).'),
666
+				$this->page_slug, $this->_req_action, get_class($this));
667
+			throw new EE_Error($msg);
668
+		}
669
+		if ($this->_cpt_route) {
670
+			$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
671
+			$this->_set_model_object($id);
672
+		}
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
679
+	 *
680
+	 * @access protected
681
+	 * @param int  $id The id to retrieve the model object for. If empty we set a default object.
682
+	 * @param bool $ignore_route_check
683
+	 * @param string $req_type whether the current route is for inserting, updating, or deleting the CPT
684
+	 * @throws EE_Error
685
+	 */
686
+	protected function _set_model_object($id = null, $ignore_route_check = false, $req_type = '')
687
+	{
688
+		$model = null;
689
+		if (
690
+			empty($this->_cpt_model_names)
691
+			|| (
692
+				! $ignore_route_check
693
+				&& ! isset($this->_cpt_routes[$this->_req_action])
694
+			) || (
695
+				$this->_cpt_model_obj instanceof EE_CPT_Base
696
+				&& $this->_cpt_model_obj->ID() === $id
697
+			)
698
+		) {
699
+			//get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
700
+			return;
701
+		}
702
+		//if ignore_route_check is true, then get the model name via EE_Register_CPTs
703
+		if ($ignore_route_check) {
704
+			$model_names = EE_Register_CPTs::get_cpt_model_names();
705
+			$post_type   = get_post_type($id);
706
+			if (isset($model_names[$post_type])) {
707
+				$model = EE_Registry::instance()->load_model($model_names[$post_type]);
708
+			}
709
+		} else {
710
+			$model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
711
+		}
712
+		if ($model instanceof EEM_Base) {
713
+			$this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
714
+		}
715
+		do_action(
716
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
717
+			$this->_cpt_model_obj,
718
+			$req_type
719
+		);
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * admin_init_global
726
+	 * This runs all the code that we want executed within the WP admin_init hook.
727
+	 * This method executes for ALL EE Admin pages.
728
+	 *
729
+	 * @access public
730
+	 * @return void
731
+	 */
732
+	public function admin_init_global()
733
+	{
734
+		$post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
735
+		//its possible this is a new save so let's catch that instead
736
+		$post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
737
+		$post_type = $post ? $post->post_type : false;
738
+		$current_route = isset($this->_req_data['current_route'])
739
+			? $this->_req_data['current_route']
740
+			: 'shouldneverwork';
741
+		$route_to_check = $post_type && isset($this->_cpt_routes[$current_route])
742
+			? $this->_cpt_routes[$current_route]
743
+			: '';
744
+		add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
745
+		add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
746
+		if ($post_type === $route_to_check) {
747
+			add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
748
+		}
749
+		//now let's filter redirect if we're on a revision page and the revision is for an event CPT.
750
+		$revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
751
+		if ( ! empty($revision)) {
752
+			$action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
753
+			//doing a restore?
754
+			if ( ! empty($action) && $action === 'restore') {
755
+				//get post for revision
756
+				$rev_post = get_post($revision);
757
+				$rev_parent = get_post($rev_post->post_parent);
758
+				//only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
759
+				if ($rev_parent && $rev_parent->post_type === $this->page_slug) {
760
+					add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
761
+					//restores of revisions
762
+					add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
763
+				}
764
+			}
765
+		}
766
+		//NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
767
+		if ($post_type && $post_type === $route_to_check) {
768
+			//$post_id, $post
769
+			add_action('save_post', array($this, 'insert_update'), 10, 3);
770
+			//$post_id
771
+			add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
772
+			add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
773
+			add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
774
+			add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
775
+		}
776
+	}
777
+
778
+
779
+
780
+	/**
781
+	 * Callback for the WordPress trashed_post hook.
782
+	 * Execute some basic checks before calling the trash_cpt_item declared in the child class.
783
+	 *
784
+	 * @param int $post_id
785
+	 * @throws \EE_Error
786
+	 */
787
+	public function before_trash_cpt_item($post_id)
788
+	{
789
+		$this->_set_model_object($post_id, true, 'trash');
790
+		//if our cpt object isn't existent then get out immediately.
791
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
792
+			return;
793
+		}
794
+		$this->trash_cpt_item($post_id);
795
+	}
796
+
797
+
798
+
799
+	/**
800
+	 * Callback for the WordPress untrashed_post hook.
801
+	 * Execute some basic checks before calling the restore_cpt_method in the child class.
802
+	 *
803
+	 * @param $post_id
804
+	 * @throws \EE_Error
805
+	 */
806
+	public function before_restore_cpt_item($post_id)
807
+	{
808
+		$this->_set_model_object($post_id, true, 'restore');
809
+		//if our cpt object isn't existent then get out immediately.
810
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
811
+			return;
812
+		}
813
+		$this->restore_cpt_item($post_id);
814
+	}
815
+
816
+
817
+
818
+	/**
819
+	 * Callback for the WordPress after_delete_post hook.
820
+	 * Execute some basic checks before calling the delete_cpt_item method in the child class.
821
+	 *
822
+	 * @param $post_id
823
+	 * @throws \EE_Error
824
+	 */
825
+	public function before_delete_cpt_item($post_id)
826
+	{
827
+		$this->_set_model_object($post_id, true, 'delete');
828
+		//if our cpt object isn't existent then get out immediately.
829
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
830
+			return;
831
+		}
832
+		$this->delete_cpt_item($post_id);
833
+	}
834
+
835
+
836
+
837
+	/**
838
+	 * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
839
+	 * accordingly.
840
+	 *
841
+	 * @access public
842
+	 * @throws EE_Error
843
+	 * @return void
844
+	 */
845
+	public function verify_cpt_object()
846
+	{
847
+		$label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
848
+		// verify event object
849
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
850
+			throw new EE_Error(sprintf(__('Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
851
+					'event_espresso'), $label));
852
+		}
853
+		//if auto-draft then throw an error
854
+		if ($this->_cpt_model_obj->get('status') === 'auto-draft') {
855
+			EE_Error::overwrite_errors();
856
+			EE_Error::add_error(sprintf(__('This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.'),
857
+					$label), __FILE__, __FUNCTION__, __LINE__);
858
+		}
859
+	}
860
+
861
+
862
+
863
+	/**
864
+	 * admin_footer_scripts_global
865
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
866
+	 * will apply on ALL EE_Admin pages.
867
+	 *
868
+	 * @access public
869
+	 * @return void
870
+	 */
871
+	public function admin_footer_scripts_global()
872
+	{
873
+		$this->_add_admin_page_ajax_loading_img();
874
+		$this->_add_admin_page_overlay();
875
+	}
876
+
877
+
878
+
879
+	/**
880
+	 * add in any global scripts for cpt routes
881
+	 *
882
+	 * @return void
883
+	 */
884
+	public function load_global_scripts_styles()
885
+	{
886
+		parent::load_global_scripts_styles();
887
+		if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
888
+			//setup custom post status object for localize script but only if we've got a cpt object
889
+			$statuses = $this->_cpt_model_obj->get_custom_post_statuses();
890
+			if ( ! empty($statuses)) {
891
+				//get ALL statuses!
892
+				$statuses = $this->_cpt_model_obj->get_all_post_statuses();
893
+				//setup object
894
+				$ee_cpt_statuses = array();
895
+				foreach ($statuses as $status => $label) {
896
+					$ee_cpt_statuses[$status] = array(
897
+						'label'      => $label,
898
+						'save_label' => sprintf(__('Save as %s', 'event_espresso'), $label),
899
+					);
900
+				}
901
+				wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
902
+			}
903
+		}
904
+	}
905
+
906
+
907
+
908
+	/**
909
+	 * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
910
+	 * insert/updates
911
+	 *
912
+	 * @param  int     $post_id ID of post being updated
913
+	 * @param  WP_Post $post    Post object from WP
914
+	 * @param  bool    $update  Whether this is an update or a new save.
915
+	 * @return void
916
+	 * @throws \EE_Error
917
+	 */
918
+	public function insert_update($post_id, $post, $update)
919
+	{
920
+		//make sure that if this is a revision OR trash action that we don't do any updates!
921
+		if (
922
+			isset($this->_req_data['action'])
923
+			&& (
924
+				$this->_req_data['action'] === 'restore'
925
+				|| $this->_req_data['action'] === 'trash'
926
+			)
927
+		) {
928
+			return;
929
+		}
930
+		$this->_set_model_object($post_id, true, 'insert_update');
931
+		//if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
932
+		if ($update
933
+			&& (
934
+				! $this->_cpt_model_obj instanceof EE_CPT_Base
935
+				|| $this->_cpt_model_obj->ID() !== $post_id
936
+			)
937
+		) {
938
+			return;
939
+		}
940
+		//check for autosave and update our req_data property accordingly.
941
+		/*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
942 942
             foreach( (array) $this->_req_data['ee_autosave_data'] as $id => $values ) {
943 943
 
944 944
                 foreach ( (array) $values as $key => $value ) {
@@ -948,526 +948,526 @@  discard block
 block discarded – undo
948 948
 
949 949
         }/**/ //TODO reactivate after autosave is implemented in 4.2
950 950
 
951
-        //take care of updating any selected page_template IF this cpt supports it.
952
-        if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
953
-            //wp version aware.
954
-            if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
955
-                $page_templates = wp_get_theme()->get_page_templates();
956
-            } else {
957
-                $post->page_template = $this->_req_data['page_template'];
958
-                $page_templates      = wp_get_theme()->get_page_templates($post);
959
-            }
960
-            if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[$this->_req_data['page_template']])) {
961
-                EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
962
-            } else {
963
-                update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
964
-            }
965
-        }
966
-        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
967
-            return;
968
-        } //TODO we'll remove this after reimplementing autosave in 4.2
969
-        $this->_insert_update_cpt_item($post_id, $post);
970
-    }
971
-
972
-
973
-
974
-    /**
975
-     * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
976
-     * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
977
-     * so we don't have to check for our CPT.
978
-     *
979
-     * @param  int $post_id ID of the post
980
-     * @return void
981
-     */
982
-    public function dont_permanently_delete_ee_cpts($post_id)
983
-    {
984
-        //only do this if we're actually processing one of our CPTs
985
-        //if our cpt object isn't existent then get out immediately.
986
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
987
-            return;
988
-        }
989
-        delete_post_meta($post_id, '_wp_trash_meta_status');
990
-        delete_post_meta($post_id, '_wp_trash_meta_time');
991
-        //our cpts may have comments so let's take care of that too
992
-        delete_post_meta($post_id, '_wp_trash_meta_comments_status');
993
-    }
994
-
995
-
996
-
997
-    /**
998
-     * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
999
-     * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
1000
-     * in them. We also have our OWN action in here so addons can hook into the restore process easily.
1001
-     *
1002
-     * @param  int $post_id     ID of cpt item
1003
-     * @param  int $revision_id ID of revision being restored
1004
-     * @return void
1005
-     */
1006
-    public function restore_revision($post_id, $revision_id)
1007
-    {
1008
-        $this->_restore_cpt_item($post_id, $revision_id);
1009
-        //global action
1010
-        do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1011
-        //class specific action so you can limit hooking into a specific page.
1012
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1013
-    }
1014
-
1015
-
1016
-
1017
-    /**
1018
-     * @see restore_revision() for details
1019
-     * @param  int $post_id     ID of cpt item
1020
-     * @param  int $revision_id ID of revision for item
1021
-     * @return void
1022
-     */
1023
-    abstract protected function _restore_cpt_item($post_id, $revision_id);
1024
-
1025
-
1026
-
1027
-    /**
1028
-     * Execution of this method is added to the end of the load_page_dependencies method in the parent
1029
-     * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
1030
-     * To fix we have to reset the current_screen using the page_slug
1031
-     * (which is identical - or should be - to our registered_post_type id.)
1032
-     * Also, since the core WP file loads the admin_header.php for WP
1033
-     * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
1034
-     * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
1035
-     *
1036
-     * @return void
1037
-     */
1038
-    public function modify_current_screen()
1039
-    {
1040
-        //ONLY do this if the current page_route IS a cpt route
1041
-        if ( ! $this->_cpt_route) {
1042
-            return;
1043
-        }
1044
-        //routing things REALLY early b/c this is a cpt admin page
1045
-        set_current_screen($this->_cpt_routes[$this->_req_action]);
1046
-        $this->_current_screen       = get_current_screen();
1047
-        $this->_current_screen->base = 'event-espresso';
1048
-        $this->_add_help_tabs(); //we make sure we add any help tabs back in!
1049
-        /*try {
951
+		//take care of updating any selected page_template IF this cpt supports it.
952
+		if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
953
+			//wp version aware.
954
+			if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
955
+				$page_templates = wp_get_theme()->get_page_templates();
956
+			} else {
957
+				$post->page_template = $this->_req_data['page_template'];
958
+				$page_templates      = wp_get_theme()->get_page_templates($post);
959
+			}
960
+			if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[$this->_req_data['page_template']])) {
961
+				EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
962
+			} else {
963
+				update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
964
+			}
965
+		}
966
+		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
967
+			return;
968
+		} //TODO we'll remove this after reimplementing autosave in 4.2
969
+		$this->_insert_update_cpt_item($post_id, $post);
970
+	}
971
+
972
+
973
+
974
+	/**
975
+	 * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
976
+	 * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
977
+	 * so we don't have to check for our CPT.
978
+	 *
979
+	 * @param  int $post_id ID of the post
980
+	 * @return void
981
+	 */
982
+	public function dont_permanently_delete_ee_cpts($post_id)
983
+	{
984
+		//only do this if we're actually processing one of our CPTs
985
+		//if our cpt object isn't existent then get out immediately.
986
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
987
+			return;
988
+		}
989
+		delete_post_meta($post_id, '_wp_trash_meta_status');
990
+		delete_post_meta($post_id, '_wp_trash_meta_time');
991
+		//our cpts may have comments so let's take care of that too
992
+		delete_post_meta($post_id, '_wp_trash_meta_comments_status');
993
+	}
994
+
995
+
996
+
997
+	/**
998
+	 * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
999
+	 * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
1000
+	 * in them. We also have our OWN action in here so addons can hook into the restore process easily.
1001
+	 *
1002
+	 * @param  int $post_id     ID of cpt item
1003
+	 * @param  int $revision_id ID of revision being restored
1004
+	 * @return void
1005
+	 */
1006
+	public function restore_revision($post_id, $revision_id)
1007
+	{
1008
+		$this->_restore_cpt_item($post_id, $revision_id);
1009
+		//global action
1010
+		do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1011
+		//class specific action so you can limit hooking into a specific page.
1012
+		do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1013
+	}
1014
+
1015
+
1016
+
1017
+	/**
1018
+	 * @see restore_revision() for details
1019
+	 * @param  int $post_id     ID of cpt item
1020
+	 * @param  int $revision_id ID of revision for item
1021
+	 * @return void
1022
+	 */
1023
+	abstract protected function _restore_cpt_item($post_id, $revision_id);
1024
+
1025
+
1026
+
1027
+	/**
1028
+	 * Execution of this method is added to the end of the load_page_dependencies method in the parent
1029
+	 * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
1030
+	 * To fix we have to reset the current_screen using the page_slug
1031
+	 * (which is identical - or should be - to our registered_post_type id.)
1032
+	 * Also, since the core WP file loads the admin_header.php for WP
1033
+	 * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
1034
+	 * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
1035
+	 *
1036
+	 * @return void
1037
+	 */
1038
+	public function modify_current_screen()
1039
+	{
1040
+		//ONLY do this if the current page_route IS a cpt route
1041
+		if ( ! $this->_cpt_route) {
1042
+			return;
1043
+		}
1044
+		//routing things REALLY early b/c this is a cpt admin page
1045
+		set_current_screen($this->_cpt_routes[$this->_req_action]);
1046
+		$this->_current_screen       = get_current_screen();
1047
+		$this->_current_screen->base = 'event-espresso';
1048
+		$this->_add_help_tabs(); //we make sure we add any help tabs back in!
1049
+		/*try {
1050 1050
             $this->_route_admin_request();
1051 1051
         } catch ( EE_Error $e ) {
1052 1052
             $e->get_error();
1053 1053
         }/**/
1054
-    }
1055
-
1056
-
1057
-
1058
-    /**
1059
-     * This allows child classes to modify the default editor title that appears when people add a new or edit an
1060
-     * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1061
-     * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1062
-     * default to be.
1063
-     *
1064
-     * @param string $title The new title (or existing if there is no editor_title defined)
1065
-     * @return string
1066
-     */
1067
-    public function add_custom_editor_default_title($title)
1068
-    {
1069
-        return isset($this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]])
1070
-            ? $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]]
1071
-            : $title;
1072
-    }
1073
-
1074
-
1075
-
1076
-    /**
1077
-     * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1078
-     *
1079
-     * @param string $shortlink   The already generated shortlink
1080
-     * @param int    $id          Post ID for this item
1081
-     * @param string $context     The context for the link
1082
-     * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1083
-     * @return string
1084
-     */
1085
-    public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1086
-    {
1087
-        if ( ! empty($id) && get_option('permalink_structure') !== '') {
1088
-            $post = get_post($id);
1089
-            if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1090
-                $shortlink = home_url('?p=' . $post->ID);
1091
-            }
1092
-        }
1093
-        return $shortlink;
1094
-    }
1095
-
1096
-
1097
-
1098
-    /**
1099
-     * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1100
-     * already run in modify_current_screen())
1101
-     *
1102
-     * @return void
1103
-     */
1104
-    public function route_admin_request()
1105
-    {
1106
-        if ($this->_cpt_route) {
1107
-            return;
1108
-        }
1109
-        try {
1110
-            $this->_route_admin_request();
1111
-        } catch (EE_Error $e) {
1112
-            $e->get_error();
1113
-        }
1114
-    }
1115
-
1116
-
1117
-
1118
-    /**
1119
-     * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1120
-     *
1121
-     * @return void
1122
-     */
1123
-    public function cpt_post_form_hidden_input()
1124
-    {
1125
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1126
-        //we're also going to add the route value and the current page so we can direct autosave parsing correctly
1127
-        echo '<div id="ee-cpt-hidden-inputs">';
1128
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1129
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1130
-        echo '</div>';
1131
-    }
1132
-
1133
-
1134
-
1135
-    /**
1136
-     * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1137
-     *
1138
-     * @param  string $location Original location url
1139
-     * @param  int    $status   Status for http header
1140
-     * @return string           new (or original) url to redirect to.
1141
-     */
1142
-    public function revision_redirect($location, $status)
1143
-    {
1144
-        //get revision
1145
-        $rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1146
-        //can't do anything without revision so let's get out if not present
1147
-        if (empty($rev_id)) {
1148
-            return $location;
1149
-        }
1150
-        //get rev_post_data
1151
-        $rev = get_post($rev_id);
1152
-        $admin_url = $this->_admin_base_url;
1153
-        $query_args = array(
1154
-            'action'   => 'edit',
1155
-            'post'     => $rev->post_parent,
1156
-            'revision' => $rev_id,
1157
-            'message'  => 5,
1158
-        );
1159
-        $this->_process_notices($query_args, true);
1160
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1161
-    }
1162
-
1163
-
1164
-
1165
-    /**
1166
-     * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1167
-     *
1168
-     * @param  string $link    the original generated link
1169
-     * @param  int    $id      post id
1170
-     * @param  string $context optional, defaults to display.  How to write the '&'
1171
-     * @return string          the link
1172
-     */
1173
-    public function modify_edit_post_link($link, $id, $context)
1174
-    {
1175
-        $post = get_post($id);
1176
-        if ( ! isset($this->_req_data['action'])
1177
-             || ! isset($this->_cpt_routes[$this->_req_data['action']])
1178
-             || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1179
-        ) {
1180
-            return $link;
1181
-        }
1182
-        $query_args = array(
1183
-            'action' => isset($this->_cpt_edit_routes[$post->post_type])
1184
-                ? $this->_cpt_edit_routes[$post->post_type]
1185
-                : 'edit',
1186
-            'post'   => $id,
1187
-        );
1188
-        return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1189
-    }
1190
-
1191
-
1192
-    /**
1193
-     * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1194
-     * our routes.
1195
-     *
1196
-     * @param  string $delete_link  original delete link
1197
-     * @param  int    $post_id      id of cpt object
1198
-     * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1199
-     * @return string new delete link
1200
-     * @throws EE_Error
1201
-     */
1202
-    public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1203
-    {
1204
-        $post = get_post($post_id);
1205
-
1206
-        if (! isset($this->_req_data['action'])
1207
-            || ! $post instanceof WP_Post
1208
-            || (isset($this->_cpt_routes[$this->_req_data['action']])
1209
-                 && $post->post_type !== $this->_cpt_routes[$this->_req_data['action']])
1210
-        ) {
1211
-            return $delete_link;
1212
-        }
1213
-        $this->_set_model_object($post->ID, true);
1214
-        //returns something like `trash_event` or `trash_attendee` or `trash_venue`
1215
-        $action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1216
-
1217
-        return EE_Admin_Page::add_query_args_and_nonce(
1218
-            array(
1219
-                'page' => $this->_req_data['page'],
1220
-                'action' => $action,
1221
-                $this->_cpt_model_obj->get_model()->get_primary_key_field()->get_name()
1222
-                    => $post->ID
1223
-            ),
1224
-            admin_url()
1225
-        );
1226
-    }
1227
-
1228
-
1229
-
1230
-    /**
1231
-     * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1232
-     * so that we can hijack the default redirect locations for wp custom post types
1233
-     * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1234
-     *
1235
-     * @param  string $location This is the incoming currently set redirect location
1236
-     * @param  string $post_id  This is the 'ID' value of the wp_posts table
1237
-     * @return string           the new location to redirect to
1238
-     */
1239
-    public function cpt_post_location_redirect($location, $post_id)
1240
-    {
1241
-        //we DO have a match so let's setup the url
1242
-        //we have to get the post to determine our route
1243
-        $post       = get_post($post_id);
1244
-        $edit_route = $this->_cpt_edit_routes[$post->post_type];
1245
-        //shared query_args
1246
-        $query_args = array('action' => $edit_route, 'post' => $post_id);
1247
-        $admin_url  = $this->_admin_base_url;
1248
-        if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1249
-            $status = get_post_status($post_id);
1250
-            if (isset($this->_req_data['publish'])) {
1251
-                switch ($status) {
1252
-                    case 'pending':
1253
-                        $message = 8;
1254
-                        break;
1255
-                    case 'future':
1256
-                        $message = 9;
1257
-                        break;
1258
-                    default:
1259
-                        $message = 6;
1260
-                }
1261
-            } else {
1262
-                $message = 'draft' === $status ? 10 : 1;
1263
-            }
1264
-        } else if (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1265
-            $message = 2;
1266
-            //			$append = '#postcustom';
1267
-        } else if (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1268
-            $message = 3;
1269
-            //			$append = '#postcustom';
1270
-        } elseif ($this->_req_data['action'] === 'post-quickpress-save-cont') {
1271
-            $message = 7;
1272
-        } else {
1273
-            $message = 4;
1274
-        }
1275
-        //change the message if the post type is not viewable on the frontend
1276
-        $this->_cpt_object = get_post_type_object($post->post_type);
1277
-        $message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1278
-        $query_args = array_merge(array('message' => $message), $query_args);
1279
-        $this->_process_notices($query_args, true);
1280
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * This method is called to inject nav tabs on core WP cpt pages
1287
-     *
1288
-     * @access public
1289
-     * @return void
1290
-     */
1291
-    public function inject_nav_tabs()
1292
-    {
1293
-        //can we hijack and insert the nav_tabs?
1294
-        $nav_tabs = $this->_get_main_nav_tabs();
1295
-        //first close off existing form tag
1296
-        $html = '>';
1297
-        $html .= $nav_tabs;
1298
-        //now let's handle the remaining tag ( missing ">" is CORRECT )
1299
-        $html .= '<span></span';
1300
-        echo $html;
1301
-    }
1302
-
1303
-
1304
-
1305
-    /**
1306
-     * This just sets up the post update messages when an update form is loaded
1307
-     *
1308
-     * @access public
1309
-     * @param  array $messages the original messages array
1310
-     * @return array           the new messages array
1311
-     */
1312
-    public function post_update_messages($messages)
1313
-    {
1314
-        global $post;
1315
-        $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1316
-        $id = empty($id) && is_object($post) ? $post->ID : null;
1317
-        //		$post_type = $post ? $post->post_type : false;
1318
-        /*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1054
+	}
1055
+
1056
+
1057
+
1058
+	/**
1059
+	 * This allows child classes to modify the default editor title that appears when people add a new or edit an
1060
+	 * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1061
+	 * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1062
+	 * default to be.
1063
+	 *
1064
+	 * @param string $title The new title (or existing if there is no editor_title defined)
1065
+	 * @return string
1066
+	 */
1067
+	public function add_custom_editor_default_title($title)
1068
+	{
1069
+		return isset($this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]])
1070
+			? $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]]
1071
+			: $title;
1072
+	}
1073
+
1074
+
1075
+
1076
+	/**
1077
+	 * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1078
+	 *
1079
+	 * @param string $shortlink   The already generated shortlink
1080
+	 * @param int    $id          Post ID for this item
1081
+	 * @param string $context     The context for the link
1082
+	 * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1083
+	 * @return string
1084
+	 */
1085
+	public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1086
+	{
1087
+		if ( ! empty($id) && get_option('permalink_structure') !== '') {
1088
+			$post = get_post($id);
1089
+			if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1090
+				$shortlink = home_url('?p=' . $post->ID);
1091
+			}
1092
+		}
1093
+		return $shortlink;
1094
+	}
1095
+
1096
+
1097
+
1098
+	/**
1099
+	 * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1100
+	 * already run in modify_current_screen())
1101
+	 *
1102
+	 * @return void
1103
+	 */
1104
+	public function route_admin_request()
1105
+	{
1106
+		if ($this->_cpt_route) {
1107
+			return;
1108
+		}
1109
+		try {
1110
+			$this->_route_admin_request();
1111
+		} catch (EE_Error $e) {
1112
+			$e->get_error();
1113
+		}
1114
+	}
1115
+
1116
+
1117
+
1118
+	/**
1119
+	 * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1120
+	 *
1121
+	 * @return void
1122
+	 */
1123
+	public function cpt_post_form_hidden_input()
1124
+	{
1125
+		echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1126
+		//we're also going to add the route value and the current page so we can direct autosave parsing correctly
1127
+		echo '<div id="ee-cpt-hidden-inputs">';
1128
+		echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1129
+		echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1130
+		echo '</div>';
1131
+	}
1132
+
1133
+
1134
+
1135
+	/**
1136
+	 * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1137
+	 *
1138
+	 * @param  string $location Original location url
1139
+	 * @param  int    $status   Status for http header
1140
+	 * @return string           new (or original) url to redirect to.
1141
+	 */
1142
+	public function revision_redirect($location, $status)
1143
+	{
1144
+		//get revision
1145
+		$rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1146
+		//can't do anything without revision so let's get out if not present
1147
+		if (empty($rev_id)) {
1148
+			return $location;
1149
+		}
1150
+		//get rev_post_data
1151
+		$rev = get_post($rev_id);
1152
+		$admin_url = $this->_admin_base_url;
1153
+		$query_args = array(
1154
+			'action'   => 'edit',
1155
+			'post'     => $rev->post_parent,
1156
+			'revision' => $rev_id,
1157
+			'message'  => 5,
1158
+		);
1159
+		$this->_process_notices($query_args, true);
1160
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1161
+	}
1162
+
1163
+
1164
+
1165
+	/**
1166
+	 * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1167
+	 *
1168
+	 * @param  string $link    the original generated link
1169
+	 * @param  int    $id      post id
1170
+	 * @param  string $context optional, defaults to display.  How to write the '&'
1171
+	 * @return string          the link
1172
+	 */
1173
+	public function modify_edit_post_link($link, $id, $context)
1174
+	{
1175
+		$post = get_post($id);
1176
+		if ( ! isset($this->_req_data['action'])
1177
+			 || ! isset($this->_cpt_routes[$this->_req_data['action']])
1178
+			 || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1179
+		) {
1180
+			return $link;
1181
+		}
1182
+		$query_args = array(
1183
+			'action' => isset($this->_cpt_edit_routes[$post->post_type])
1184
+				? $this->_cpt_edit_routes[$post->post_type]
1185
+				: 'edit',
1186
+			'post'   => $id,
1187
+		);
1188
+		return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1189
+	}
1190
+
1191
+
1192
+	/**
1193
+	 * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1194
+	 * our routes.
1195
+	 *
1196
+	 * @param  string $delete_link  original delete link
1197
+	 * @param  int    $post_id      id of cpt object
1198
+	 * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1199
+	 * @return string new delete link
1200
+	 * @throws EE_Error
1201
+	 */
1202
+	public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1203
+	{
1204
+		$post = get_post($post_id);
1205
+
1206
+		if (! isset($this->_req_data['action'])
1207
+			|| ! $post instanceof WP_Post
1208
+			|| (isset($this->_cpt_routes[$this->_req_data['action']])
1209
+				 && $post->post_type !== $this->_cpt_routes[$this->_req_data['action']])
1210
+		) {
1211
+			return $delete_link;
1212
+		}
1213
+		$this->_set_model_object($post->ID, true);
1214
+		//returns something like `trash_event` or `trash_attendee` or `trash_venue`
1215
+		$action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1216
+
1217
+		return EE_Admin_Page::add_query_args_and_nonce(
1218
+			array(
1219
+				'page' => $this->_req_data['page'],
1220
+				'action' => $action,
1221
+				$this->_cpt_model_obj->get_model()->get_primary_key_field()->get_name()
1222
+					=> $post->ID
1223
+			),
1224
+			admin_url()
1225
+		);
1226
+	}
1227
+
1228
+
1229
+
1230
+	/**
1231
+	 * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1232
+	 * so that we can hijack the default redirect locations for wp custom post types
1233
+	 * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1234
+	 *
1235
+	 * @param  string $location This is the incoming currently set redirect location
1236
+	 * @param  string $post_id  This is the 'ID' value of the wp_posts table
1237
+	 * @return string           the new location to redirect to
1238
+	 */
1239
+	public function cpt_post_location_redirect($location, $post_id)
1240
+	{
1241
+		//we DO have a match so let's setup the url
1242
+		//we have to get the post to determine our route
1243
+		$post       = get_post($post_id);
1244
+		$edit_route = $this->_cpt_edit_routes[$post->post_type];
1245
+		//shared query_args
1246
+		$query_args = array('action' => $edit_route, 'post' => $post_id);
1247
+		$admin_url  = $this->_admin_base_url;
1248
+		if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1249
+			$status = get_post_status($post_id);
1250
+			if (isset($this->_req_data['publish'])) {
1251
+				switch ($status) {
1252
+					case 'pending':
1253
+						$message = 8;
1254
+						break;
1255
+					case 'future':
1256
+						$message = 9;
1257
+						break;
1258
+					default:
1259
+						$message = 6;
1260
+				}
1261
+			} else {
1262
+				$message = 'draft' === $status ? 10 : 1;
1263
+			}
1264
+		} else if (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1265
+			$message = 2;
1266
+			//			$append = '#postcustom';
1267
+		} else if (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1268
+			$message = 3;
1269
+			//			$append = '#postcustom';
1270
+		} elseif ($this->_req_data['action'] === 'post-quickpress-save-cont') {
1271
+			$message = 7;
1272
+		} else {
1273
+			$message = 4;
1274
+		}
1275
+		//change the message if the post type is not viewable on the frontend
1276
+		$this->_cpt_object = get_post_type_object($post->post_type);
1277
+		$message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1278
+		$query_args = array_merge(array('message' => $message), $query_args);
1279
+		$this->_process_notices($query_args, true);
1280
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * This method is called to inject nav tabs on core WP cpt pages
1287
+	 *
1288
+	 * @access public
1289
+	 * @return void
1290
+	 */
1291
+	public function inject_nav_tabs()
1292
+	{
1293
+		//can we hijack and insert the nav_tabs?
1294
+		$nav_tabs = $this->_get_main_nav_tabs();
1295
+		//first close off existing form tag
1296
+		$html = '>';
1297
+		$html .= $nav_tabs;
1298
+		//now let's handle the remaining tag ( missing ">" is CORRECT )
1299
+		$html .= '<span></span';
1300
+		echo $html;
1301
+	}
1302
+
1303
+
1304
+
1305
+	/**
1306
+	 * This just sets up the post update messages when an update form is loaded
1307
+	 *
1308
+	 * @access public
1309
+	 * @param  array $messages the original messages array
1310
+	 * @return array           the new messages array
1311
+	 */
1312
+	public function post_update_messages($messages)
1313
+	{
1314
+		global $post;
1315
+		$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1316
+		$id = empty($id) && is_object($post) ? $post->ID : null;
1317
+		//		$post_type = $post ? $post->post_type : false;
1318
+		/*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1319 1319
 
1320 1320
         $route_to_check = $post_type && isset( $this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route] : '';/**/
1321
-        $messages[$post->post_type] = array(
1322
-            0 => '', //Unused. Messages start at index 1.
1323
-            1 => sprintf(
1324
-                __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1325
-                $this->_cpt_object->labels->singular_name,
1326
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1327
-                '</a>'
1328
-            ),
1329
-            2 => __('Custom field updated'),
1330
-            3 => __('Custom field deleted.'),
1331
-            4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1332
-            5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1333
-                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1334
-                : false,
1335
-            6 => sprintf(
1336
-                __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1337
-                $this->_cpt_object->labels->singular_name,
1338
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1339
-                '</a>'
1340
-            ),
1341
-            7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1342
-            8 => sprintf(
1343
-                __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1344
-                $this->_cpt_object->labels->singular_name,
1345
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1346
-                '</a>'
1347
-            ),
1348
-            9 => sprintf(
1349
-                __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1350
-                $this->_cpt_object->labels->singular_name,
1351
-                '<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1352
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1353
-                '</a>'
1354
-            ),
1355
-            10 => sprintf(
1356
-                __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1357
-                $this->_cpt_object->labels->singular_name,
1358
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1359
-                '</a>'
1360
-            ),
1361
-        );
1362
-        return $messages;
1363
-    }
1364
-
1365
-
1366
-
1367
-    /**
1368
-     * default method for the 'create_new' route for cpt admin pages.
1369
-     * For reference what to include in here, see wp-admin/post-new.php
1370
-     *
1371
-     * @access  protected
1372
-     * @return void
1373
-     */
1374
-    protected function _create_new_cpt_item()
1375
-    {
1376
-        // gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1377
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1378
-        $post_type        = $this->_cpt_routes[$this->_req_action];
1379
-        $post_type_object = $this->_cpt_object;
1380
-        $title            = $post_type_object->labels->add_new_item;
1381
-        $editing          = true;
1382
-        wp_enqueue_script('autosave');
1383
-        $post    = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1384
-        $post_ID = $post->ID;
1385
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1386
-        //modify the default editor title field with default title.
1387
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1388
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1389
-    }
1390
-
1391
-
1392
-
1393
-    public function add_new_admin_page_global()
1394
-    {
1395
-        $admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1396
-        ?>
1321
+		$messages[$post->post_type] = array(
1322
+			0 => '', //Unused. Messages start at index 1.
1323
+			1 => sprintf(
1324
+				__('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1325
+				$this->_cpt_object->labels->singular_name,
1326
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1327
+				'</a>'
1328
+			),
1329
+			2 => __('Custom field updated'),
1330
+			3 => __('Custom field deleted.'),
1331
+			4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1332
+			5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1333
+				$this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1334
+				: false,
1335
+			6 => sprintf(
1336
+				__('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1337
+				$this->_cpt_object->labels->singular_name,
1338
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1339
+				'</a>'
1340
+			),
1341
+			7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1342
+			8 => sprintf(
1343
+				__('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1344
+				$this->_cpt_object->labels->singular_name,
1345
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1346
+				'</a>'
1347
+			),
1348
+			9 => sprintf(
1349
+				__('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1350
+				$this->_cpt_object->labels->singular_name,
1351
+				'<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1352
+				'<a target="_blank" href="' . esc_url(get_permalink($id)),
1353
+				'</a>'
1354
+			),
1355
+			10 => sprintf(
1356
+				__('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1357
+				$this->_cpt_object->labels->singular_name,
1358
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1359
+				'</a>'
1360
+			),
1361
+		);
1362
+		return $messages;
1363
+	}
1364
+
1365
+
1366
+
1367
+	/**
1368
+	 * default method for the 'create_new' route for cpt admin pages.
1369
+	 * For reference what to include in here, see wp-admin/post-new.php
1370
+	 *
1371
+	 * @access  protected
1372
+	 * @return void
1373
+	 */
1374
+	protected function _create_new_cpt_item()
1375
+	{
1376
+		// gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1377
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1378
+		$post_type        = $this->_cpt_routes[$this->_req_action];
1379
+		$post_type_object = $this->_cpt_object;
1380
+		$title            = $post_type_object->labels->add_new_item;
1381
+		$editing          = true;
1382
+		wp_enqueue_script('autosave');
1383
+		$post    = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1384
+		$post_ID = $post->ID;
1385
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1386
+		//modify the default editor title field with default title.
1387
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1388
+		include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1389
+	}
1390
+
1391
+
1392
+
1393
+	public function add_new_admin_page_global()
1394
+	{
1395
+		$admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1396
+		?>
1397 1397
         <script type="text/javascript">
1398 1398
             adminpage = '<?php echo $admin_page; ?>';
1399 1399
         </script>
1400 1400
         <?php
1401
-    }
1402
-
1403
-
1404
-
1405
-    /**
1406
-     * default method for the 'edit' route for cpt admin pages
1407
-     * For reference on what to put in here, refer to wp-admin/post.php
1408
-     *
1409
-     * @access protected
1410
-     * @return string   template for edit cpt form
1411
-     */
1412
-    protected function _edit_cpt_item()
1413
-    {
1414
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1415
-        $post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1416
-        $post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1417
-        if (empty ($post)) {
1418
-            wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?'));
1419
-        }
1420
-        if ( ! empty($_GET['get-post-lock'])) {
1421
-            wp_set_post_lock($post_id);
1422
-            wp_redirect(get_edit_post_link($post_id, 'url'));
1423
-            exit();
1424
-        }
1425
-
1426
-        // template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1427
-        $editing          = true;
1428
-        $post_ID          = $post_id;
1429
-        $post_type        = $this->_cpt_routes[$this->_req_action];
1430
-        $post_type_object = $this->_cpt_object;
1431
-
1432
-        if ( ! wp_check_post_lock($post->ID)) {
1433
-            $active_post_lock = wp_set_post_lock($post->ID);
1434
-            //wp_enqueue_script('autosave');
1435
-        }
1436
-        $title = $this->_cpt_object->labels->edit_item;
1437
-        add_action('admin_footer', '_admin_notice_post_locked');
1438
-        if (isset($this->_cpt_routes[$this->_req_data['action']])
1439
-            && ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1440
-        ) {
1441
-            $create_new_action = apply_filters('FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1442
-                'create_new', $this);
1443
-            $post_new_file = EE_Admin_Page::add_query_args_and_nonce(array(
1444
-                'action' => $create_new_action,
1445
-                'page'   => $this->page_slug,
1446
-            ), 'admin.php');
1447
-        }
1448
-        if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1449
-            wp_enqueue_script('admin-comments');
1450
-            enqueue_comment_hotkeys_js();
1451
-        }
1452
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1453
-        //modify the default editor title field with default title.
1454
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1455
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * some getters
1462
-     */
1463
-    /**
1464
-     * This returns the protected _cpt_model_obj property
1465
-     *
1466
-     * @return EE_CPT_Base
1467
-     */
1468
-    public function get_cpt_model_obj()
1469
-    {
1470
-        return $this->_cpt_model_obj;
1471
-    }
1401
+	}
1402
+
1403
+
1404
+
1405
+	/**
1406
+	 * default method for the 'edit' route for cpt admin pages
1407
+	 * For reference on what to put in here, refer to wp-admin/post.php
1408
+	 *
1409
+	 * @access protected
1410
+	 * @return string   template for edit cpt form
1411
+	 */
1412
+	protected function _edit_cpt_item()
1413
+	{
1414
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1415
+		$post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1416
+		$post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1417
+		if (empty ($post)) {
1418
+			wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?'));
1419
+		}
1420
+		if ( ! empty($_GET['get-post-lock'])) {
1421
+			wp_set_post_lock($post_id);
1422
+			wp_redirect(get_edit_post_link($post_id, 'url'));
1423
+			exit();
1424
+		}
1425
+
1426
+		// template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1427
+		$editing          = true;
1428
+		$post_ID          = $post_id;
1429
+		$post_type        = $this->_cpt_routes[$this->_req_action];
1430
+		$post_type_object = $this->_cpt_object;
1431
+
1432
+		if ( ! wp_check_post_lock($post->ID)) {
1433
+			$active_post_lock = wp_set_post_lock($post->ID);
1434
+			//wp_enqueue_script('autosave');
1435
+		}
1436
+		$title = $this->_cpt_object->labels->edit_item;
1437
+		add_action('admin_footer', '_admin_notice_post_locked');
1438
+		if (isset($this->_cpt_routes[$this->_req_data['action']])
1439
+			&& ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1440
+		) {
1441
+			$create_new_action = apply_filters('FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1442
+				'create_new', $this);
1443
+			$post_new_file = EE_Admin_Page::add_query_args_and_nonce(array(
1444
+				'action' => $create_new_action,
1445
+				'page'   => $this->page_slug,
1446
+			), 'admin.php');
1447
+		}
1448
+		if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1449
+			wp_enqueue_script('admin-comments');
1450
+			enqueue_comment_hotkeys_js();
1451
+		}
1452
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1453
+		//modify the default editor title field with default title.
1454
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1455
+		include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * some getters
1462
+	 */
1463
+	/**
1464
+	 * This returns the protected _cpt_model_obj property
1465
+	 *
1466
+	 * @return EE_CPT_Base
1467
+	 */
1468
+	public function get_cpt_model_obj()
1469
+	{
1470
+		return $this->_cpt_model_obj;
1471
+	}
1472 1472
 
1473 1473
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
      */
236 236
     protected function _register_autosave_containers($ids)
237 237
     {
238
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
238
+        $this->_autosave_containers = array_merge($this->_autosave_fields, (array) $ids);
239 239
     }
240 240
 
241 241
 
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
         //filter _autosave_containers
283 283
         $containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
284 284
             $this->_autosave_containers, $this);
285
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
285
+        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__'.get_class($this).'___load_autosave_scripts_styles__containers',
286 286
             $containers, $this);
287 287
 
288 288
         wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
         // This is for any plugins that are doing things properly
395 395
         // and hooking into the load page hook for core wp cpt routes.
396 396
         global $pagenow;
397
-        do_action('load-' . $pagenow);
397
+        do_action('load-'.$pagenow);
398 398
         $this->modify_current_screen();
399 399
         add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
400 400
         //we route REALLY early.
@@ -425,8 +425,8 @@  discard block
 block discarded – undo
425 425
                 'admin.php?page=espresso_registrations&action=contact_list',
426 426
             ),
427 427
             1 => array(
428
-                'edit.php?post_type=' . $this->_cpt_object->name,
429
-                'admin.php?page=' . $this->_cpt_object->name,
428
+                'edit.php?post_type='.$this->_cpt_object->name,
429
+                'admin.php?page='.$this->_cpt_object->name,
430 430
             ),
431 431
         );
432 432
         foreach ($routes_to_match as $route_matches) {
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
         $cpt_has_support = ! empty($cpt_args['page_templates']);
455 455
 
456 456
         //if the installed version of WP is > 4.7 we do some additional checks.
457
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
457
+        if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
458 458
             $post_templates = wp_get_theme()->get_post_templates();
459 459
             //if there are $post_templates for this cpt, then we return false for this method because
460 460
             //that means we aren't going to load our page template manager and leave that up to the native
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
         global $post;
478 478
         $template = '';
479 479
 
480
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
480
+        if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
481 481
             $page_template_count = count(get_page_templates());
482 482
         } else {
483 483
             $page_template_count = count(get_page_templates($post));
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
         $post = get_post($id);
515 515
         if ('publish' !== get_post_status($post)) {
516 516
             //include shims for the `get_preview_post_link` function
517
-            require_once( EE_CORE . 'wordpress-shims.php' );
517
+            require_once(EE_CORE.'wordpress-shims.php');
518 518
             $return .= '<span_id="view-post-btn"><a target="_blank" href="'
519 519
                        . get_preview_post_link($id)
520 520
                        . '" class="button button-small">'
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
             $template_args['statuses']         = $statuses;
553 553
         }
554 554
 
555
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
555
+        $template = EE_ADMIN_TEMPLATE.'status_dropdown.template.php';
556 556
         EEH_Template::display_template($template, $template_args);
557 557
     }
558 558
 
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
             $this->_template_args['success'] = true;
607 607
         }
608 608
         do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
609
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
609
+        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_'.get_class($this), $this);
610 610
         //now let's return json
611 611
         $this->_return_json();
612 612
     }
@@ -1009,7 +1009,7 @@  discard block
 block discarded – undo
1009 1009
         //global action
1010 1010
         do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1011 1011
         //class specific action so you can limit hooking into a specific page.
1012
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1012
+        do_action('AHEE_EE_Admin_Page_CPT_'.get_class($this).'__restore_revision', $post_id, $revision_id);
1013 1013
     }
1014 1014
 
1015 1015
 
@@ -1087,7 +1087,7 @@  discard block
 block discarded – undo
1087 1087
         if ( ! empty($id) && get_option('permalink_structure') !== '') {
1088 1088
             $post = get_post($id);
1089 1089
             if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1090
-                $shortlink = home_url('?p=' . $post->ID);
1090
+                $shortlink = home_url('?p='.$post->ID);
1091 1091
             }
1092 1092
         }
1093 1093
         return $shortlink;
@@ -1122,11 +1122,11 @@  discard block
 block discarded – undo
1122 1122
      */
1123 1123
     public function cpt_post_form_hidden_input()
1124 1124
     {
1125
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1125
+        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="'.$this->_admin_base_url.'" />';
1126 1126
         //we're also going to add the route value and the current page so we can direct autosave parsing correctly
1127 1127
         echo '<div id="ee-cpt-hidden-inputs">';
1128
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1129
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1128
+        echo '<input type="hidden" id="current_route" name="current_route" value="'.$this->_current_view.'" />';
1129
+        echo '<input type="hidden" id="current_page" name="current_page" value="'.$this->page_slug.'" />';
1130 1130
         echo '</div>';
1131 1131
     }
1132 1132
 
@@ -1203,7 +1203,7 @@  discard block
 block discarded – undo
1203 1203
     {
1204 1204
         $post = get_post($post_id);
1205 1205
 
1206
-        if (! isset($this->_req_data['action'])
1206
+        if ( ! isset($this->_req_data['action'])
1207 1207
             || ! $post instanceof WP_Post
1208 1208
             || (isset($this->_cpt_routes[$this->_req_data['action']])
1209 1209
                  && $post->post_type !== $this->_cpt_routes[$this->_req_data['action']])
@@ -1212,7 +1212,7 @@  discard block
 block discarded – undo
1212 1212
         }
1213 1213
         $this->_set_model_object($post->ID, true);
1214 1214
         //returns something like `trash_event` or `trash_attendee` or `trash_venue`
1215
-        $action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1215
+        $action = 'trash_'.str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1216 1216
 
1217 1217
         return EE_Admin_Page::add_query_args_and_nonce(
1218 1218
             array(
@@ -1323,39 +1323,39 @@  discard block
 block discarded – undo
1323 1323
             1 => sprintf(
1324 1324
                 __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1325 1325
                 $this->_cpt_object->labels->singular_name,
1326
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1326
+                '<a href="'.esc_url(get_permalink($id)).'">',
1327 1327
                 '</a>'
1328 1328
             ),
1329 1329
             2 => __('Custom field updated'),
1330 1330
             3 => __('Custom field deleted.'),
1331 1331
             4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1332 1332
             5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1333
-                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1333
+                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int) $_GET['revision'], false))
1334 1334
                 : false,
1335 1335
             6 => sprintf(
1336 1336
                 __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1337 1337
                 $this->_cpt_object->labels->singular_name,
1338
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1338
+                '<a href="'.esc_url(get_permalink($id)).'">',
1339 1339
                 '</a>'
1340 1340
             ),
1341 1341
             7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1342 1342
             8 => sprintf(
1343 1343
                 __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1344 1344
                 $this->_cpt_object->labels->singular_name,
1345
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1345
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))).'">',
1346 1346
                 '</a>'
1347 1347
             ),
1348 1348
             9 => sprintf(
1349 1349
                 __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1350 1350
                 $this->_cpt_object->labels->singular_name,
1351
-                '<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1352
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1351
+                '<strong>'.date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)).'</strong>',
1352
+                '<a target="_blank" href="'.esc_url(get_permalink($id)),
1353 1353
                 '</a>'
1354 1354
             ),
1355 1355
             10 => sprintf(
1356 1356
                 __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1357 1357
                 $this->_cpt_object->labels->singular_name,
1358
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1358
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1359 1359
                 '</a>'
1360 1360
             ),
1361 1361
         );
@@ -1385,7 +1385,7 @@  discard block
 block discarded – undo
1385 1385
         add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1386 1386
         //modify the default editor title field with default title.
1387 1387
         add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1388
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1388
+        include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1389 1389
     }
1390 1390
 
1391 1391
 
@@ -1452,7 +1452,7 @@  discard block
 block discarded – undo
1452 1452
         add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1453 1453
         //modify the default editor title field with default title.
1454 1454
         add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1455
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1455
+        include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1456 1456
     }
1457 1457
 
1458 1458
 
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 1 patch
Indentation   +736 added lines, -736 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\services\loaders\LoaderInterface;
5 5
 
6 6
 if (! defined('EVENT_ESPRESSO_VERSION')) {
7
-    exit('No direct script access allowed');
7
+	exit('No direct script access allowed');
8 8
 }
9 9
 
10 10
 
@@ -21,741 +21,741 @@  discard block
 block discarded – undo
21 21
 class EE_Dependency_Map
22 22
 {
23 23
 
24
-    /**
25
-     * This means that the requested class dependency is not present in the dependency map
26
-     */
27
-    const not_registered = 0;
28
-
29
-    /**
30
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
31
-     */
32
-    const load_new_object = 1;
33
-
34
-    /**
35
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
36
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
37
-     */
38
-    const load_from_cache = 2;
39
-
40
-    /**
41
-     * When registering a dependency,
42
-     * this indicates to keep any existing dependencies that already exist,
43
-     * and simply discard any new dependencies declared in the incoming data
44
-     */
45
-    const KEEP_EXISTING_DEPENDENCIES = 0;
46
-
47
-    /**
48
-     * When registering a dependency,
49
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
50
-     */
51
-    const OVERWRITE_DEPENDENCIES = 1;
52
-
53
-
54
-
55
-    /**
56
-     * @type EE_Dependency_Map $_instance
57
-     */
58
-    protected static $_instance;
59
-
60
-    /**
61
-     * @type EE_Request $request
62
-     */
63
-    protected $_request;
64
-
65
-    /**
66
-     * @type EE_Response $response
67
-     */
68
-    protected $_response;
69
-
70
-    /**
71
-     * @type LoaderInterface $loader
72
-     */
73
-    protected $loader;
74
-
75
-    /**
76
-     * @type array $_dependency_map
77
-     */
78
-    protected $_dependency_map = array();
79
-
80
-    /**
81
-     * @type array $_class_loaders
82
-     */
83
-    protected $_class_loaders = array();
84
-
85
-    /**
86
-     * @type array $_aliases
87
-     */
88
-    protected $_aliases = array();
89
-
90
-
91
-
92
-    /**
93
-     * EE_Dependency_Map constructor.
94
-     *
95
-     * @param EE_Request  $request
96
-     * @param EE_Response $response
97
-     */
98
-    protected function __construct(EE_Request $request, EE_Response $response)
99
-    {
100
-        $this->_request = $request;
101
-        $this->_response = $response;
102
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
103
-        do_action('EE_Dependency_Map____construct');
104
-    }
105
-
106
-
107
-
108
-    /**
109
-     * @throws InvalidDataTypeException
110
-     * @throws InvalidInterfaceException
111
-     * @throws InvalidArgumentException
112
-     */
113
-    public function initialize()
114
-    {
115
-        $this->_register_core_dependencies();
116
-        $this->_register_core_class_loaders();
117
-        $this->_register_core_aliases();
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     * @singleton method used to instantiate class object
124
-     * @access    public
125
-     * @param EE_Request  $request
126
-     * @param EE_Response $response
127
-     * @return EE_Dependency_Map
128
-     */
129
-    public static function instance(EE_Request $request = null, EE_Response $response = null)
130
-    {
131
-        // check if class object is instantiated, and instantiated properly
132
-        if (! self::$_instance instanceof EE_Dependency_Map) {
133
-            self::$_instance = new EE_Dependency_Map($request, $response);
134
-        }
135
-        return self::$_instance;
136
-    }
137
-
138
-
139
-
140
-    /**
141
-     * @param LoaderInterface $loader
142
-     */
143
-    public function setLoader(LoaderInterface $loader)
144
-    {
145
-        $this->loader = $loader;
146
-    }
147
-
148
-
149
-
150
-    /**
151
-     * @param string $class
152
-     * @param array  $dependencies
153
-     * @param int    $overwrite
154
-     * @return bool
155
-     */
156
-    public static function register_dependencies(
157
-        $class,
158
-        array $dependencies,
159
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
160
-    ) {
161
-        return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
162
-    }
163
-
164
-
165
-
166
-    /**
167
-     * Assigns an array of class names and corresponding load sources (new or cached)
168
-     * to the class specified by the first parameter.
169
-     * IMPORTANT !!!
170
-     * The order of elements in the incoming $dependencies array MUST match
171
-     * the order of the constructor parameters for the class in question.
172
-     * This is especially important when overriding any existing dependencies that are registered.
173
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
174
-     *
175
-     * @param string $class
176
-     * @param array  $dependencies
177
-     * @param int    $overwrite
178
-     * @return bool
179
-     */
180
-    public function registerDependencies(
181
-        $class,
182
-        array $dependencies,
183
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
184
-    ) {
185
-        $class = trim($class, '\\');
186
-        $registered = false;
187
-        if (empty(self::$_instance->_dependency_map[ $class ])) {
188
-            self::$_instance->_dependency_map[ $class ] = array();
189
-        }
190
-        // we need to make sure that any aliases used when registering a dependency
191
-        // get resolved to the correct class name
192
-        foreach ((array)$dependencies as $dependency => $load_source) {
193
-            $alias = self::$_instance->get_alias($dependency);
194
-            if (
195
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
196
-                || ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
197
-            ) {
198
-                unset($dependencies[$dependency]);
199
-                $dependencies[$alias] = $load_source;
200
-                $registered = true;
201
-            }
202
-        }
203
-        // now add our two lists of dependencies together.
204
-        // using Union (+=) favours the arrays in precedence from left to right,
205
-        // so $dependencies is NOT overwritten because it is listed first
206
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
207
-        // Union is way faster than array_merge() but should be used with caution...
208
-        // especially with numerically indexed arrays
209
-        $dependencies += self::$_instance->_dependency_map[ $class ];
210
-        // now we need to ensure that the resulting dependencies
211
-        // array only has the entries that are required for the class
212
-        // so first count how many dependencies were originally registered for the class
213
-        $dependency_count = count(self::$_instance->_dependency_map[ $class ]);
214
-        // if that count is non-zero (meaning dependencies were already registered)
215
-        self::$_instance->_dependency_map[ $class ] = $dependency_count
216
-            // then truncate the  final array to match that count
217
-            ? array_slice($dependencies, 0, $dependency_count)
218
-            // otherwise just take the incoming array because nothing previously existed
219
-            : $dependencies;
220
-        return $registered;
221
-    }
222
-
223
-
224
-
225
-    /**
226
-     * @param string $class_name
227
-     * @param string $loader
228
-     * @return bool
229
-     * @throws DomainException
230
-     */
231
-    public static function register_class_loader($class_name, $loader = 'load_core')
232
-    {
233
-        if (strpos($class_name, '\\') !== false) {
234
-            throw new DomainException(
235
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
236
-            );
237
-        }
238
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
239
-        if (
240
-            ! is_callable($loader)
241
-            && (
242
-                strpos($loader, 'load_') !== 0
243
-                || ! method_exists('EE_Registry', $loader)
244
-            )
245
-        ) {
246
-            throw new DomainException(
247
-                sprintf(
248
-                    esc_html__(
249
-                        '"%1$s" is not a valid loader method on EE_Registry.',
250
-                        'event_espresso'
251
-                    ),
252
-                    $loader
253
-                )
254
-            );
255
-        }
256
-        $class_name = self::$_instance->get_alias($class_name);
257
-        if (! isset(self::$_instance->_class_loaders[$class_name])) {
258
-            self::$_instance->_class_loaders[$class_name] = $loader;
259
-            return true;
260
-        }
261
-        return false;
262
-    }
263
-
264
-
265
-
266
-    /**
267
-     * @return array
268
-     */
269
-    public function dependency_map()
270
-    {
271
-        return $this->_dependency_map;
272
-    }
273
-
274
-
275
-
276
-    /**
277
-     * returns TRUE if dependency map contains a listing for the provided class name
278
-     *
279
-     * @param string $class_name
280
-     * @return boolean
281
-     */
282
-    public function has($class_name = '')
283
-    {
284
-        return isset($this->_dependency_map[$class_name]) ? true : false;
285
-    }
286
-
287
-
288
-
289
-    /**
290
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
291
-     *
292
-     * @param string $class_name
293
-     * @param string $dependency
294
-     * @return bool
295
-     */
296
-    public function has_dependency_for_class($class_name = '', $dependency = '')
297
-    {
298
-        $dependency = $this->get_alias($dependency);
299
-        return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
300
-            ? true
301
-            : false;
302
-    }
303
-
304
-
305
-
306
-    /**
307
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
308
-     *
309
-     * @param string $class_name
310
-     * @param string $dependency
311
-     * @return int
312
-     */
313
-    public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
314
-    {
315
-        $dependency = $this->get_alias($dependency);
316
-        return $this->has_dependency_for_class($class_name, $dependency)
317
-            ? $this->_dependency_map[$class_name][$dependency]
318
-            : EE_Dependency_Map::not_registered;
319
-    }
320
-
321
-
322
-
323
-    /**
324
-     * @param string $class_name
325
-     * @return string | Closure
326
-     */
327
-    public function class_loader($class_name)
328
-    {
329
-        // don't use loaders for FQCNs
330
-        if(strpos($class_name, '\\') !== false){
331
-            return '';
332
-        }
333
-        $class_name = $this->get_alias($class_name);
334
-        return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * @return array
341
-     */
342
-    public function class_loaders()
343
-    {
344
-        return $this->_class_loaders;
345
-    }
346
-
347
-
348
-
349
-    /**
350
-     * adds an alias for a classname
351
-     *
352
-     * @param string $class_name the class name that should be used (concrete class to replace interface)
353
-     * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
354
-     * @param string $for_class  the class that has the dependency (is type hinting for the interface)
355
-     */
356
-    public function add_alias($class_name, $alias, $for_class = '')
357
-    {
358
-        if ($for_class !== '') {
359
-            if (! isset($this->_aliases[$for_class])) {
360
-                $this->_aliases[$for_class] = array();
361
-            }
362
-            $this->_aliases[$for_class][$class_name] = $alias;
363
-        }
364
-        $this->_aliases[$class_name] = $alias;
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * returns TRUE if the provided class name has an alias
371
-     *
372
-     * @param string $class_name
373
-     * @param string $for_class
374
-     * @return bool
375
-     */
376
-    public function has_alias($class_name = '', $for_class = '')
377
-    {
378
-        return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
379
-               || (
380
-                   isset($this->_aliases[$class_name])
381
-                   && ! is_array($this->_aliases[$class_name])
382
-               );
383
-    }
384
-
385
-
386
-
387
-    /**
388
-     * returns alias for class name if one exists, otherwise returns the original classname
389
-     * functions recursively, so that multiple aliases can be used to drill down to a classname
390
-     *  for example:
391
-     *      if the following two entries were added to the _aliases array:
392
-     *          array(
393
-     *              'interface_alias'           => 'some\namespace\interface'
394
-     *              'some\namespace\interface'  => 'some\namespace\classname'
395
-     *          )
396
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
397
-     *      to load an instance of 'some\namespace\classname'
398
-     *
399
-     * @param string $class_name
400
-     * @param string $for_class
401
-     * @return string
402
-     */
403
-    public function get_alias($class_name = '', $for_class = '')
404
-    {
405
-        if (! $this->has_alias($class_name, $for_class)) {
406
-            return $class_name;
407
-        }
408
-        if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
409
-            return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
410
-        }
411
-        return $this->get_alias($this->_aliases[$class_name]);
412
-    }
413
-
414
-
415
-
416
-    /**
417
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
418
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
419
-     * This is done by using the following class constants:
420
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
421
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
422
-     */
423
-    protected function _register_core_dependencies()
424
-    {
425
-        $this->_dependency_map = array(
426
-            'EE_Request_Handler'                                                                                          => array(
427
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
428
-            ),
429
-            'EE_System'                                                                                                   => array(
430
-                'EE_Registry' => EE_Dependency_Map::load_from_cache,
431
-            ),
432
-            'EE_Session'                                                                                                  => array(
433
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
434
-                'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
435
-            ),
436
-            'EE_Cart'                                                                                                     => array(
437
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
438
-            ),
439
-            'EE_Front_Controller'                                                                                         => array(
440
-                'EE_Registry'              => EE_Dependency_Map::load_from_cache,
441
-                'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
442
-                'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
443
-            ),
444
-            'EE_Messenger_Collection_Loader'                                                                              => array(
445
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
446
-            ),
447
-            'EE_Message_Type_Collection_Loader'                                                                           => array(
448
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
449
-            ),
450
-            'EE_Message_Resource_Manager'                                                                                 => array(
451
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
452
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
453
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
454
-            ),
455
-            'EE_Message_Factory'                                                                                          => array(
456
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
457
-            ),
458
-            'EE_messages'                                                                                                 => array(
459
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
460
-            ),
461
-            'EE_Messages_Generator'                                                                                       => array(
462
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
463
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
464
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
465
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
466
-            ),
467
-            'EE_Messages_Processor'                                                                                       => array(
468
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
469
-            ),
470
-            'EE_Messages_Queue'                                                                                           => array(
471
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
472
-            ),
473
-            'EE_Messages_Template_Defaults'                                                                               => array(
474
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
475
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
476
-            ),
477
-            'EE_Message_To_Generate_From_Request'                                                                         => array(
478
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
479
-                'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
480
-            ),
481
-            'EventEspresso\core\services\commands\CommandBus'                                                             => array(
482
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
483
-            ),
484
-            'EventEspresso\services\commands\CommandHandler'                                                              => array(
485
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
486
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
487
-            ),
488
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
489
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
490
-            ),
491
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
492
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
493
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
494
-            ),
495
-            'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
496
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
497
-            ),
498
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
499
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
500
-            ),
501
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
502
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
503
-            ),
504
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
505
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
506
-            ),
507
-            'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
508
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
509
-            ),
510
-            'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
511
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
512
-            ),
513
-            'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
514
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
515
-            ),
516
-            'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
517
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
518
-            ),
519
-            'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
520
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
521
-            ),
522
-            'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
523
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
524
-            ),
525
-            'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
526
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
527
-            ),
528
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
529
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
530
-            ),
531
-            'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
532
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
533
-            ),
534
-            'EventEspresso\core\services\database\TableManager'                                                           => array(
535
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
536
-            ),
537
-            'EE_Data_Migration_Class_Base'                                                                                => array(
538
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
539
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
540
-            ),
541
-            'EE_DMS_Core_4_1_0'                                                                                           => array(
542
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
543
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
544
-            ),
545
-            'EE_DMS_Core_4_2_0'                                                                                           => array(
546
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
547
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
548
-            ),
549
-            'EE_DMS_Core_4_3_0'                                                                                           => array(
550
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
551
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
552
-            ),
553
-            'EE_DMS_Core_4_4_0'                                                                                           => array(
554
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
555
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
556
-            ),
557
-            'EE_DMS_Core_4_5_0'                                                                                           => array(
558
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
559
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
560
-            ),
561
-            'EE_DMS_Core_4_6_0'                                                                                           => array(
562
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
563
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
564
-            ),
565
-            'EE_DMS_Core_4_7_0'                                                                                           => array(
566
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
567
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
568
-            ),
569
-            'EE_DMS_Core_4_8_0'                                                                                           => array(
570
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
571
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
572
-            ),
573
-            'EE_DMS_Core_4_9_0'                                                                                           => array(
574
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
575
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
576
-            ),
577
-            'EventEspresso\core\services\assets\Registry'                                                                 => array(
578
-                'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
579
-                'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
580
-            ),
581
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
582
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
583
-            ),
584
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
585
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
586
-            ),
587
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
588
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
589
-            ),
590
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
591
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
592
-            ),
593
-            'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
594
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
595
-            ),
596
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
597
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
598
-            ),
599
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
600
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
601
-            ),
602
-            'EventEspresso\core\services\cache\BasicCacheManager'                                                         => array(
603
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
604
-            ),
605
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => array(
606
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
607
-            ),
608
-        );
609
-    }
610
-
611
-
612
-
613
-    /**
614
-     * Registers how core classes are loaded.
615
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
616
-     *        'EE_Request_Handler' => 'load_core'
617
-     *        'EE_Messages_Queue'  => 'load_lib'
618
-     *        'EEH_Debug_Tools'    => 'load_helper'
619
-     * or, if greater control is required, by providing a custom closure. For example:
620
-     *        'Some_Class' => function () {
621
-     *            return new Some_Class();
622
-     *        },
623
-     * This is required for instantiating dependencies
624
-     * where an interface has been type hinted in a class constructor. For example:
625
-     *        'Required_Interface' => function () {
626
-     *            return new A_Class_That_Implements_Required_Interface();
627
-     *        },
628
-     */
629
-    protected function _register_core_class_loaders()
630
-    {
631
-        //for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
632
-        //be used in a closure.
633
-        $request = &$this->_request;
634
-        $response = &$this->_response;
635
-        $loader = &$this->loader;
636
-        $this->_class_loaders = array(
637
-            //load_core
638
-            'EE_Capabilities'                      => 'load_core',
639
-            'EE_Encryption'                        => 'load_core',
640
-            'EE_Front_Controller'                  => 'load_core',
641
-            'EE_Module_Request_Router'             => 'load_core',
642
-            'EE_Registry'                          => 'load_core',
643
-            'EE_Request'                           => function () use (&$request) {
644
-                return $request;
645
-            },
646
-            'EE_Response'                          => function () use (&$response) {
647
-                return $response;
648
-            },
649
-            'EE_Request_Handler'                   => 'load_core',
650
-            'EE_Session'                           => 'load_core',
651
-            //load_lib
652
-            'EE_Message_Resource_Manager'          => 'load_lib',
653
-            'EE_Message_Type_Collection'           => 'load_lib',
654
-            'EE_Message_Type_Collection_Loader'    => 'load_lib',
655
-            'EE_Messenger_Collection'              => 'load_lib',
656
-            'EE_Messenger_Collection_Loader'       => 'load_lib',
657
-            'EE_Messages_Processor'                => 'load_lib',
658
-            'EE_Message_Repository'                => 'load_lib',
659
-            'EE_Messages_Queue'                    => 'load_lib',
660
-            'EE_Messages_Data_Handler_Collection'  => 'load_lib',
661
-            'EE_Message_Template_Group_Collection' => 'load_lib',
662
-            'EE_Messages_Generator'                => function () {
663
-                return EE_Registry::instance()->load_lib(
664
-                    'Messages_Generator',
665
-                    array(),
666
-                    false,
667
-                    false
668
-                );
669
-            },
670
-            'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
671
-                return EE_Registry::instance()->load_lib(
672
-                    'Messages_Template_Defaults',
673
-                    $arguments,
674
-                    false,
675
-                    false
676
-                );
677
-            },
678
-            //load_model
679
-            'EEM_Attendee'                         => 'load_model',
680
-            'EEM_Message_Template_Group'           => 'load_model',
681
-            'EEM_Message_Template'                 => 'load_model',
682
-            //load_helper
683
-            'EEH_Parse_Shortcodes'                 => function () {
684
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
685
-                    return new EEH_Parse_Shortcodes();
686
-                }
687
-                return null;
688
-            },
689
-            'EE_Template_Config'                   => function () {
690
-                return EE_Config::instance()->template_settings;
691
-            },
692
-            'EE_Currency_Config'                   => function () {
693
-                return EE_Config::instance()->currency;
694
-            },
695
-            'EventEspresso\core\services\loaders\Loader' => function () use (&$loader) {
696
-                return $loader;
697
-            },
698
-        );
699
-    }
700
-
701
-
702
-
703
-    /**
704
-     * can be used for supplying alternate names for classes,
705
-     * or for connecting interface names to instantiable classes
706
-     */
707
-    protected function _register_core_aliases()
708
-    {
709
-        $this->_aliases = array(
710
-            'CommandBusInterface'                                                 => 'EventEspresso\core\services\commands\CommandBusInterface',
711
-            'EventEspresso\core\services\commands\CommandBusInterface'            => 'EventEspresso\core\services\commands\CommandBus',
712
-            'CommandHandlerManagerInterface'                                      => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
713
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface' => 'EventEspresso\core\services\commands\CommandHandlerManager',
714
-            'CapChecker'                                                          => 'EventEspresso\core\services\commands\middleware\CapChecker',
715
-            'AddActionHook'                                                       => 'EventEspresso\core\services\commands\middleware\AddActionHook',
716
-            'CapabilitiesChecker'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
717
-            'CapabilitiesCheckerInterface'                                        => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
718
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
719
-            'CreateRegistrationService'                                           => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
720
-            'CreateRegCodeCommandHandler'                                         => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
721
-            'CreateRegUrlLinkCommandHandler'                                      => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
722
-            'CreateRegistrationCommandHandler'                                    => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
723
-            'CopyRegistrationDetailsCommandHandler'                               => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
724
-            'CopyRegistrationPaymentsCommandHandler'                              => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
725
-            'CancelRegistrationAndTicketLineItemCommandHandler'                   => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
726
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'           => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
727
-            'CreateTicketLineItemCommandHandler'                                  => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
728
-            'TableManager'                                                        => 'EventEspresso\core\services\database\TableManager',
729
-            'TableAnalysis'                                                       => 'EventEspresso\core\services\database\TableAnalysis',
730
-            'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
731
-            'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
732
-            'EspressoShortcode'                                                   => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
733
-            'ShortcodeInterface'                                                  => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
734
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'           => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
735
-            'EventEspresso\core\services\cache\CacheStorageInterface'             => 'EventEspresso\core\services\cache\TransientCacheStorage',
736
-            'LoaderInterface'                                                     => 'EventEspresso\core\services\loaders\LoaderInterface',
737
-            'EventEspresso\core\services\loaders\LoaderInterface'                 => 'EventEspresso\core\services\loaders\Loader',
738
-            'CommandFactoryInterface'                                             => 'EventEspresso\core\services\commands\CommandFactoryInterface',
739
-            'EventEspresso\core\services\commands\CommandFactoryInterface'        => 'EventEspresso\core\services\commands\CommandFactory',
740
-            'EventEspresso\core\domain\services\session\SessionIdentifierInterface' => 'EE_Session',
741
-            'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
742
-            'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
743
-            'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
744
-            'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
745
-        );
746
-    }
747
-
748
-
749
-
750
-    /**
751
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
752
-     * request Primarily used by unit tests.
753
-     */
754
-    public function reset()
755
-    {
756
-        $this->_register_core_class_loaders();
757
-        $this->_register_core_dependencies();
758
-    }
24
+	/**
25
+	 * This means that the requested class dependency is not present in the dependency map
26
+	 */
27
+	const not_registered = 0;
28
+
29
+	/**
30
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
31
+	 */
32
+	const load_new_object = 1;
33
+
34
+	/**
35
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
36
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
37
+	 */
38
+	const load_from_cache = 2;
39
+
40
+	/**
41
+	 * When registering a dependency,
42
+	 * this indicates to keep any existing dependencies that already exist,
43
+	 * and simply discard any new dependencies declared in the incoming data
44
+	 */
45
+	const KEEP_EXISTING_DEPENDENCIES = 0;
46
+
47
+	/**
48
+	 * When registering a dependency,
49
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
50
+	 */
51
+	const OVERWRITE_DEPENDENCIES = 1;
52
+
53
+
54
+
55
+	/**
56
+	 * @type EE_Dependency_Map $_instance
57
+	 */
58
+	protected static $_instance;
59
+
60
+	/**
61
+	 * @type EE_Request $request
62
+	 */
63
+	protected $_request;
64
+
65
+	/**
66
+	 * @type EE_Response $response
67
+	 */
68
+	protected $_response;
69
+
70
+	/**
71
+	 * @type LoaderInterface $loader
72
+	 */
73
+	protected $loader;
74
+
75
+	/**
76
+	 * @type array $_dependency_map
77
+	 */
78
+	protected $_dependency_map = array();
79
+
80
+	/**
81
+	 * @type array $_class_loaders
82
+	 */
83
+	protected $_class_loaders = array();
84
+
85
+	/**
86
+	 * @type array $_aliases
87
+	 */
88
+	protected $_aliases = array();
89
+
90
+
91
+
92
+	/**
93
+	 * EE_Dependency_Map constructor.
94
+	 *
95
+	 * @param EE_Request  $request
96
+	 * @param EE_Response $response
97
+	 */
98
+	protected function __construct(EE_Request $request, EE_Response $response)
99
+	{
100
+		$this->_request = $request;
101
+		$this->_response = $response;
102
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
103
+		do_action('EE_Dependency_Map____construct');
104
+	}
105
+
106
+
107
+
108
+	/**
109
+	 * @throws InvalidDataTypeException
110
+	 * @throws InvalidInterfaceException
111
+	 * @throws InvalidArgumentException
112
+	 */
113
+	public function initialize()
114
+	{
115
+		$this->_register_core_dependencies();
116
+		$this->_register_core_class_loaders();
117
+		$this->_register_core_aliases();
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 * @singleton method used to instantiate class object
124
+	 * @access    public
125
+	 * @param EE_Request  $request
126
+	 * @param EE_Response $response
127
+	 * @return EE_Dependency_Map
128
+	 */
129
+	public static function instance(EE_Request $request = null, EE_Response $response = null)
130
+	{
131
+		// check if class object is instantiated, and instantiated properly
132
+		if (! self::$_instance instanceof EE_Dependency_Map) {
133
+			self::$_instance = new EE_Dependency_Map($request, $response);
134
+		}
135
+		return self::$_instance;
136
+	}
137
+
138
+
139
+
140
+	/**
141
+	 * @param LoaderInterface $loader
142
+	 */
143
+	public function setLoader(LoaderInterface $loader)
144
+	{
145
+		$this->loader = $loader;
146
+	}
147
+
148
+
149
+
150
+	/**
151
+	 * @param string $class
152
+	 * @param array  $dependencies
153
+	 * @param int    $overwrite
154
+	 * @return bool
155
+	 */
156
+	public static function register_dependencies(
157
+		$class,
158
+		array $dependencies,
159
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
160
+	) {
161
+		return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
162
+	}
163
+
164
+
165
+
166
+	/**
167
+	 * Assigns an array of class names and corresponding load sources (new or cached)
168
+	 * to the class specified by the first parameter.
169
+	 * IMPORTANT !!!
170
+	 * The order of elements in the incoming $dependencies array MUST match
171
+	 * the order of the constructor parameters for the class in question.
172
+	 * This is especially important when overriding any existing dependencies that are registered.
173
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
174
+	 *
175
+	 * @param string $class
176
+	 * @param array  $dependencies
177
+	 * @param int    $overwrite
178
+	 * @return bool
179
+	 */
180
+	public function registerDependencies(
181
+		$class,
182
+		array $dependencies,
183
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
184
+	) {
185
+		$class = trim($class, '\\');
186
+		$registered = false;
187
+		if (empty(self::$_instance->_dependency_map[ $class ])) {
188
+			self::$_instance->_dependency_map[ $class ] = array();
189
+		}
190
+		// we need to make sure that any aliases used when registering a dependency
191
+		// get resolved to the correct class name
192
+		foreach ((array)$dependencies as $dependency => $load_source) {
193
+			$alias = self::$_instance->get_alias($dependency);
194
+			if (
195
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
196
+				|| ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
197
+			) {
198
+				unset($dependencies[$dependency]);
199
+				$dependencies[$alias] = $load_source;
200
+				$registered = true;
201
+			}
202
+		}
203
+		// now add our two lists of dependencies together.
204
+		// using Union (+=) favours the arrays in precedence from left to right,
205
+		// so $dependencies is NOT overwritten because it is listed first
206
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
207
+		// Union is way faster than array_merge() but should be used with caution...
208
+		// especially with numerically indexed arrays
209
+		$dependencies += self::$_instance->_dependency_map[ $class ];
210
+		// now we need to ensure that the resulting dependencies
211
+		// array only has the entries that are required for the class
212
+		// so first count how many dependencies were originally registered for the class
213
+		$dependency_count = count(self::$_instance->_dependency_map[ $class ]);
214
+		// if that count is non-zero (meaning dependencies were already registered)
215
+		self::$_instance->_dependency_map[ $class ] = $dependency_count
216
+			// then truncate the  final array to match that count
217
+			? array_slice($dependencies, 0, $dependency_count)
218
+			// otherwise just take the incoming array because nothing previously existed
219
+			: $dependencies;
220
+		return $registered;
221
+	}
222
+
223
+
224
+
225
+	/**
226
+	 * @param string $class_name
227
+	 * @param string $loader
228
+	 * @return bool
229
+	 * @throws DomainException
230
+	 */
231
+	public static function register_class_loader($class_name, $loader = 'load_core')
232
+	{
233
+		if (strpos($class_name, '\\') !== false) {
234
+			throw new DomainException(
235
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
236
+			);
237
+		}
238
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
239
+		if (
240
+			! is_callable($loader)
241
+			&& (
242
+				strpos($loader, 'load_') !== 0
243
+				|| ! method_exists('EE_Registry', $loader)
244
+			)
245
+		) {
246
+			throw new DomainException(
247
+				sprintf(
248
+					esc_html__(
249
+						'"%1$s" is not a valid loader method on EE_Registry.',
250
+						'event_espresso'
251
+					),
252
+					$loader
253
+				)
254
+			);
255
+		}
256
+		$class_name = self::$_instance->get_alias($class_name);
257
+		if (! isset(self::$_instance->_class_loaders[$class_name])) {
258
+			self::$_instance->_class_loaders[$class_name] = $loader;
259
+			return true;
260
+		}
261
+		return false;
262
+	}
263
+
264
+
265
+
266
+	/**
267
+	 * @return array
268
+	 */
269
+	public function dependency_map()
270
+	{
271
+		return $this->_dependency_map;
272
+	}
273
+
274
+
275
+
276
+	/**
277
+	 * returns TRUE if dependency map contains a listing for the provided class name
278
+	 *
279
+	 * @param string $class_name
280
+	 * @return boolean
281
+	 */
282
+	public function has($class_name = '')
283
+	{
284
+		return isset($this->_dependency_map[$class_name]) ? true : false;
285
+	}
286
+
287
+
288
+
289
+	/**
290
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
291
+	 *
292
+	 * @param string $class_name
293
+	 * @param string $dependency
294
+	 * @return bool
295
+	 */
296
+	public function has_dependency_for_class($class_name = '', $dependency = '')
297
+	{
298
+		$dependency = $this->get_alias($dependency);
299
+		return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
300
+			? true
301
+			: false;
302
+	}
303
+
304
+
305
+
306
+	/**
307
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
308
+	 *
309
+	 * @param string $class_name
310
+	 * @param string $dependency
311
+	 * @return int
312
+	 */
313
+	public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
314
+	{
315
+		$dependency = $this->get_alias($dependency);
316
+		return $this->has_dependency_for_class($class_name, $dependency)
317
+			? $this->_dependency_map[$class_name][$dependency]
318
+			: EE_Dependency_Map::not_registered;
319
+	}
320
+
321
+
322
+
323
+	/**
324
+	 * @param string $class_name
325
+	 * @return string | Closure
326
+	 */
327
+	public function class_loader($class_name)
328
+	{
329
+		// don't use loaders for FQCNs
330
+		if(strpos($class_name, '\\') !== false){
331
+			return '';
332
+		}
333
+		$class_name = $this->get_alias($class_name);
334
+		return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * @return array
341
+	 */
342
+	public function class_loaders()
343
+	{
344
+		return $this->_class_loaders;
345
+	}
346
+
347
+
348
+
349
+	/**
350
+	 * adds an alias for a classname
351
+	 *
352
+	 * @param string $class_name the class name that should be used (concrete class to replace interface)
353
+	 * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
354
+	 * @param string $for_class  the class that has the dependency (is type hinting for the interface)
355
+	 */
356
+	public function add_alias($class_name, $alias, $for_class = '')
357
+	{
358
+		if ($for_class !== '') {
359
+			if (! isset($this->_aliases[$for_class])) {
360
+				$this->_aliases[$for_class] = array();
361
+			}
362
+			$this->_aliases[$for_class][$class_name] = $alias;
363
+		}
364
+		$this->_aliases[$class_name] = $alias;
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * returns TRUE if the provided class name has an alias
371
+	 *
372
+	 * @param string $class_name
373
+	 * @param string $for_class
374
+	 * @return bool
375
+	 */
376
+	public function has_alias($class_name = '', $for_class = '')
377
+	{
378
+		return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
379
+			   || (
380
+				   isset($this->_aliases[$class_name])
381
+				   && ! is_array($this->_aliases[$class_name])
382
+			   );
383
+	}
384
+
385
+
386
+
387
+	/**
388
+	 * returns alias for class name if one exists, otherwise returns the original classname
389
+	 * functions recursively, so that multiple aliases can be used to drill down to a classname
390
+	 *  for example:
391
+	 *      if the following two entries were added to the _aliases array:
392
+	 *          array(
393
+	 *              'interface_alias'           => 'some\namespace\interface'
394
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
395
+	 *          )
396
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
397
+	 *      to load an instance of 'some\namespace\classname'
398
+	 *
399
+	 * @param string $class_name
400
+	 * @param string $for_class
401
+	 * @return string
402
+	 */
403
+	public function get_alias($class_name = '', $for_class = '')
404
+	{
405
+		if (! $this->has_alias($class_name, $for_class)) {
406
+			return $class_name;
407
+		}
408
+		if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
409
+			return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
410
+		}
411
+		return $this->get_alias($this->_aliases[$class_name]);
412
+	}
413
+
414
+
415
+
416
+	/**
417
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
418
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
419
+	 * This is done by using the following class constants:
420
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
421
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
422
+	 */
423
+	protected function _register_core_dependencies()
424
+	{
425
+		$this->_dependency_map = array(
426
+			'EE_Request_Handler'                                                                                          => array(
427
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
428
+			),
429
+			'EE_System'                                                                                                   => array(
430
+				'EE_Registry' => EE_Dependency_Map::load_from_cache,
431
+			),
432
+			'EE_Session'                                                                                                  => array(
433
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
434
+				'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
435
+			),
436
+			'EE_Cart'                                                                                                     => array(
437
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
438
+			),
439
+			'EE_Front_Controller'                                                                                         => array(
440
+				'EE_Registry'              => EE_Dependency_Map::load_from_cache,
441
+				'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
442
+				'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
443
+			),
444
+			'EE_Messenger_Collection_Loader'                                                                              => array(
445
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
446
+			),
447
+			'EE_Message_Type_Collection_Loader'                                                                           => array(
448
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
449
+			),
450
+			'EE_Message_Resource_Manager'                                                                                 => array(
451
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
452
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
453
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
454
+			),
455
+			'EE_Message_Factory'                                                                                          => array(
456
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
457
+			),
458
+			'EE_messages'                                                                                                 => array(
459
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
460
+			),
461
+			'EE_Messages_Generator'                                                                                       => array(
462
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
463
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
464
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
465
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
466
+			),
467
+			'EE_Messages_Processor'                                                                                       => array(
468
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
469
+			),
470
+			'EE_Messages_Queue'                                                                                           => array(
471
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
472
+			),
473
+			'EE_Messages_Template_Defaults'                                                                               => array(
474
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
475
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
476
+			),
477
+			'EE_Message_To_Generate_From_Request'                                                                         => array(
478
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
479
+				'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
480
+			),
481
+			'EventEspresso\core\services\commands\CommandBus'                                                             => array(
482
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
483
+			),
484
+			'EventEspresso\services\commands\CommandHandler'                                                              => array(
485
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
486
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
487
+			),
488
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
489
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
490
+			),
491
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
492
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
493
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
494
+			),
495
+			'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
496
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
497
+			),
498
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
499
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
500
+			),
501
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
502
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
503
+			),
504
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
505
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
506
+			),
507
+			'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
508
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
509
+			),
510
+			'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
511
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
512
+			),
513
+			'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
514
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
515
+			),
516
+			'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
517
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
518
+			),
519
+			'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
520
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
521
+			),
522
+			'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
523
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
524
+			),
525
+			'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
526
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
527
+			),
528
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
529
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
530
+			),
531
+			'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
532
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
533
+			),
534
+			'EventEspresso\core\services\database\TableManager'                                                           => array(
535
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
536
+			),
537
+			'EE_Data_Migration_Class_Base'                                                                                => array(
538
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
539
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
540
+			),
541
+			'EE_DMS_Core_4_1_0'                                                                                           => array(
542
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
543
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
544
+			),
545
+			'EE_DMS_Core_4_2_0'                                                                                           => array(
546
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
547
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
548
+			),
549
+			'EE_DMS_Core_4_3_0'                                                                                           => array(
550
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
551
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
552
+			),
553
+			'EE_DMS_Core_4_4_0'                                                                                           => array(
554
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
555
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
556
+			),
557
+			'EE_DMS_Core_4_5_0'                                                                                           => array(
558
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
559
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
560
+			),
561
+			'EE_DMS_Core_4_6_0'                                                                                           => array(
562
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
563
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
564
+			),
565
+			'EE_DMS_Core_4_7_0'                                                                                           => array(
566
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
567
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
568
+			),
569
+			'EE_DMS_Core_4_8_0'                                                                                           => array(
570
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
571
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
572
+			),
573
+			'EE_DMS_Core_4_9_0'                                                                                           => array(
574
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
575
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
576
+			),
577
+			'EventEspresso\core\services\assets\Registry'                                                                 => array(
578
+				'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
579
+				'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
580
+			),
581
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
582
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
583
+			),
584
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
585
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
586
+			),
587
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
588
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
589
+			),
590
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
591
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
592
+			),
593
+			'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
594
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
595
+			),
596
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
597
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
598
+			),
599
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
600
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
601
+			),
602
+			'EventEspresso\core\services\cache\BasicCacheManager'                                                         => array(
603
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
604
+			),
605
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => array(
606
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
607
+			),
608
+		);
609
+	}
610
+
611
+
612
+
613
+	/**
614
+	 * Registers how core classes are loaded.
615
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
616
+	 *        'EE_Request_Handler' => 'load_core'
617
+	 *        'EE_Messages_Queue'  => 'load_lib'
618
+	 *        'EEH_Debug_Tools'    => 'load_helper'
619
+	 * or, if greater control is required, by providing a custom closure. For example:
620
+	 *        'Some_Class' => function () {
621
+	 *            return new Some_Class();
622
+	 *        },
623
+	 * This is required for instantiating dependencies
624
+	 * where an interface has been type hinted in a class constructor. For example:
625
+	 *        'Required_Interface' => function () {
626
+	 *            return new A_Class_That_Implements_Required_Interface();
627
+	 *        },
628
+	 */
629
+	protected function _register_core_class_loaders()
630
+	{
631
+		//for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
632
+		//be used in a closure.
633
+		$request = &$this->_request;
634
+		$response = &$this->_response;
635
+		$loader = &$this->loader;
636
+		$this->_class_loaders = array(
637
+			//load_core
638
+			'EE_Capabilities'                      => 'load_core',
639
+			'EE_Encryption'                        => 'load_core',
640
+			'EE_Front_Controller'                  => 'load_core',
641
+			'EE_Module_Request_Router'             => 'load_core',
642
+			'EE_Registry'                          => 'load_core',
643
+			'EE_Request'                           => function () use (&$request) {
644
+				return $request;
645
+			},
646
+			'EE_Response'                          => function () use (&$response) {
647
+				return $response;
648
+			},
649
+			'EE_Request_Handler'                   => 'load_core',
650
+			'EE_Session'                           => 'load_core',
651
+			//load_lib
652
+			'EE_Message_Resource_Manager'          => 'load_lib',
653
+			'EE_Message_Type_Collection'           => 'load_lib',
654
+			'EE_Message_Type_Collection_Loader'    => 'load_lib',
655
+			'EE_Messenger_Collection'              => 'load_lib',
656
+			'EE_Messenger_Collection_Loader'       => 'load_lib',
657
+			'EE_Messages_Processor'                => 'load_lib',
658
+			'EE_Message_Repository'                => 'load_lib',
659
+			'EE_Messages_Queue'                    => 'load_lib',
660
+			'EE_Messages_Data_Handler_Collection'  => 'load_lib',
661
+			'EE_Message_Template_Group_Collection' => 'load_lib',
662
+			'EE_Messages_Generator'                => function () {
663
+				return EE_Registry::instance()->load_lib(
664
+					'Messages_Generator',
665
+					array(),
666
+					false,
667
+					false
668
+				);
669
+			},
670
+			'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
671
+				return EE_Registry::instance()->load_lib(
672
+					'Messages_Template_Defaults',
673
+					$arguments,
674
+					false,
675
+					false
676
+				);
677
+			},
678
+			//load_model
679
+			'EEM_Attendee'                         => 'load_model',
680
+			'EEM_Message_Template_Group'           => 'load_model',
681
+			'EEM_Message_Template'                 => 'load_model',
682
+			//load_helper
683
+			'EEH_Parse_Shortcodes'                 => function () {
684
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
685
+					return new EEH_Parse_Shortcodes();
686
+				}
687
+				return null;
688
+			},
689
+			'EE_Template_Config'                   => function () {
690
+				return EE_Config::instance()->template_settings;
691
+			},
692
+			'EE_Currency_Config'                   => function () {
693
+				return EE_Config::instance()->currency;
694
+			},
695
+			'EventEspresso\core\services\loaders\Loader' => function () use (&$loader) {
696
+				return $loader;
697
+			},
698
+		);
699
+	}
700
+
701
+
702
+
703
+	/**
704
+	 * can be used for supplying alternate names for classes,
705
+	 * or for connecting interface names to instantiable classes
706
+	 */
707
+	protected function _register_core_aliases()
708
+	{
709
+		$this->_aliases = array(
710
+			'CommandBusInterface'                                                 => 'EventEspresso\core\services\commands\CommandBusInterface',
711
+			'EventEspresso\core\services\commands\CommandBusInterface'            => 'EventEspresso\core\services\commands\CommandBus',
712
+			'CommandHandlerManagerInterface'                                      => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
713
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface' => 'EventEspresso\core\services\commands\CommandHandlerManager',
714
+			'CapChecker'                                                          => 'EventEspresso\core\services\commands\middleware\CapChecker',
715
+			'AddActionHook'                                                       => 'EventEspresso\core\services\commands\middleware\AddActionHook',
716
+			'CapabilitiesChecker'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
717
+			'CapabilitiesCheckerInterface'                                        => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
718
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
719
+			'CreateRegistrationService'                                           => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
720
+			'CreateRegCodeCommandHandler'                                         => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
721
+			'CreateRegUrlLinkCommandHandler'                                      => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
722
+			'CreateRegistrationCommandHandler'                                    => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
723
+			'CopyRegistrationDetailsCommandHandler'                               => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
724
+			'CopyRegistrationPaymentsCommandHandler'                              => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
725
+			'CancelRegistrationAndTicketLineItemCommandHandler'                   => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
726
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'           => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
727
+			'CreateTicketLineItemCommandHandler'                                  => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
728
+			'TableManager'                                                        => 'EventEspresso\core\services\database\TableManager',
729
+			'TableAnalysis'                                                       => 'EventEspresso\core\services\database\TableAnalysis',
730
+			'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
731
+			'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
732
+			'EspressoShortcode'                                                   => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
733
+			'ShortcodeInterface'                                                  => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
734
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'           => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
735
+			'EventEspresso\core\services\cache\CacheStorageInterface'             => 'EventEspresso\core\services\cache\TransientCacheStorage',
736
+			'LoaderInterface'                                                     => 'EventEspresso\core\services\loaders\LoaderInterface',
737
+			'EventEspresso\core\services\loaders\LoaderInterface'                 => 'EventEspresso\core\services\loaders\Loader',
738
+			'CommandFactoryInterface'                                             => 'EventEspresso\core\services\commands\CommandFactoryInterface',
739
+			'EventEspresso\core\services\commands\CommandFactoryInterface'        => 'EventEspresso\core\services\commands\CommandFactory',
740
+			'EventEspresso\core\domain\services\session\SessionIdentifierInterface' => 'EE_Session',
741
+			'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
742
+			'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
743
+			'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
744
+			'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
745
+		);
746
+	}
747
+
748
+
749
+
750
+	/**
751
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
752
+	 * request Primarily used by unit tests.
753
+	 */
754
+	public function reset()
755
+	{
756
+		$this->_register_core_class_loaders();
757
+		$this->_register_core_dependencies();
758
+	}
759 759
 
760 760
 
761 761
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,243 +40,243 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.44.rc.023');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.44.rc.023');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.