Completed
Branch FET/reg-form-builder/extract-a... (6e8a58)
by
unknown
35:36 queued 25:38
created
core/db_models/fields/EE_Field_With_Model_Name.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -79,10 +79,10 @@
 block discarded – undo
79 79
         $model_names = [];
80 80
         if (is_array($this->_model_name_pointed_to)) {
81 81
             foreach ($this->_model_name_pointed_to as $model_name) {
82
-                $model_names[] = "EE_" . $model_name;
82
+                $model_names[] = "EE_".$model_name;
83 83
             }
84 84
         } else {
85
-            $model_names = ["EE_" . $this->_model_name_pointed_to];
85
+            $model_names = ["EE_".$this->_model_name_pointed_to];
86 86
         }
87 87
         return $model_names;
88 88
     }
Please login to merge, or discard this patch.
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -8,94 +8,94 @@
 block discarded – undo
8 8
  */
9 9
 abstract class EE_Field_With_Model_Name extends EE_Model_Field_Base
10 10
 {
11
-    /**
12
-     * Usually the name of a single model. However, as in the case for custom post types,
13
-     * it can actually be an array of models
14
-     *
15
-     * @var string[]
16
-     */
17
-    protected $_model_name_pointed_to;
11
+	/**
12
+	 * Usually the name of a single model. However, as in the case for custom post types,
13
+	 * it can actually be an array of models
14
+	 *
15
+	 * @var string[]
16
+	 */
17
+	protected $_model_name_pointed_to;
18 18
 
19 19
 
20
-    /**
21
-     * @param string          $table_column  name of column for field
22
-     * @param string          $nicename      should be internationalized with __('blah','event_espresso')
23
-     * @param boolean         $nullable
24
-     * @param int|string      $default_value data type should match field type
25
-     * @param string|string[] $model_name    eg 'Event','Answer','Term', etc.
26
-     *                                       Basically its the model class's name without the "EEM_"
27
-     */
28
-    public function __construct($table_column, $nicename, $nullable, $default_value, $model_name)
29
-    {
30
-        $this->_model_name_pointed_to = (array) $model_name;
31
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
32
-    }
20
+	/**
21
+	 * @param string          $table_column  name of column for field
22
+	 * @param string          $nicename      should be internationalized with __('blah','event_espresso')
23
+	 * @param boolean         $nullable
24
+	 * @param int|string      $default_value data type should match field type
25
+	 * @param string|string[] $model_name    eg 'Event','Answer','Term', etc.
26
+	 *                                       Basically its the model class's name without the "EEM_"
27
+	 */
28
+	public function __construct($table_column, $nicename, $nullable, $default_value, $model_name)
29
+	{
30
+		$this->_model_name_pointed_to = (array) $model_name;
31
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
32
+	}
33 33
 
34 34
 
35
-    /**
36
-     * Returns the name of the model(s) pointed to
37
-     *
38
-     * @return string[] string or array of strings
39
-     * @deprecated since version 4.6.7
40
-     */
41
-    public function get_model_name_pointed_to(): array
42
-    {
43
-        EE_Error::doing_it_wrong(
44
-            'get_model_name_pointed_to',
45
-            __(
46
-                'This method has been deprecated in favour of instead using get_model_names_pointed_to, which consistently returns an array',
47
-                'event_espresso'
48
-            ),
49
-            '4.6.7'
50
-        );
51
-        return $this->_model_name_pointed_to;
52
-    }
35
+	/**
36
+	 * Returns the name of the model(s) pointed to
37
+	 *
38
+	 * @return string[] string or array of strings
39
+	 * @deprecated since version 4.6.7
40
+	 */
41
+	public function get_model_name_pointed_to(): array
42
+	{
43
+		EE_Error::doing_it_wrong(
44
+			'get_model_name_pointed_to',
45
+			__(
46
+				'This method has been deprecated in favour of instead using get_model_names_pointed_to, which consistently returns an array',
47
+				'event_espresso'
48
+			),
49
+			'4.6.7'
50
+		);
51
+		return $this->_model_name_pointed_to;
52
+	}
53 53
 
54 54
 
55
-    /**
56
-     * Gets the model names pointed to by this field, always as an array
57
-     * (even if there's only one)
58
-     *
59
-     * @return string[] of model names pointed to by this field
60
-     */
61
-    public function get_model_names_pointed_to(): array
62
-    {
63
-        return is_array($this->_model_name_pointed_to)
64
-            ? $this->_model_name_pointed_to
65
-            : [$this->_model_name_pointed_to];
66
-    }
55
+	/**
56
+	 * Gets the model names pointed to by this field, always as an array
57
+	 * (even if there's only one)
58
+	 *
59
+	 * @return string[] of model names pointed to by this field
60
+	 */
61
+	public function get_model_names_pointed_to(): array
62
+	{
63
+		return is_array($this->_model_name_pointed_to)
64
+			? $this->_model_name_pointed_to
65
+			: [$this->_model_name_pointed_to];
66
+	}
67 67
 
68 68
 
69
-    /**
70
-     * Returns the model's classname (eg EE_Event instead of just Event)
71
-     *
72
-     * @return string[]
73
-     */
74
-    public function get_model_class_names_pointed_to(): array
75
-    {
76
-        $model_names = [];
77
-        if (is_array($this->_model_name_pointed_to)) {
78
-            foreach ($this->_model_name_pointed_to as $model_name) {
79
-                $model_names[] = "EE_" . $model_name;
80
-            }
81
-        } else {
82
-            $model_names = ["EE_" . $this->_model_name_pointed_to];
83
-        }
84
-        return $model_names;
85
-    }
69
+	/**
70
+	 * Returns the model's classname (eg EE_Event instead of just Event)
71
+	 *
72
+	 * @return string[]
73
+	 */
74
+	public function get_model_class_names_pointed_to(): array
75
+	{
76
+		$model_names = [];
77
+		if (is_array($this->_model_name_pointed_to)) {
78
+			foreach ($this->_model_name_pointed_to as $model_name) {
79
+				$model_names[] = "EE_" . $model_name;
80
+			}
81
+		} else {
82
+			$model_names = ["EE_" . $this->_model_name_pointed_to];
83
+		}
84
+		return $model_names;
85
+	}
86 86
 
87 87
 
88
-    /**
89
-     * @param int|EE_Base_Class $model_obj
90
-     * @return bool
91
-     */
92
-    public function is_model_obj_of_type_pointed_to($model_obj): bool
93
-    {
94
-        foreach ($this->get_model_class_names_pointed_to() as $model_obj_classname) {
95
-            if ($model_obj instanceof $model_obj_classname) {
96
-                return true;
97
-            }
98
-        }
99
-        return false;
100
-    }
88
+	/**
89
+	 * @param int|EE_Base_Class $model_obj
90
+	 * @return bool
91
+	 */
92
+	public function is_model_obj_of_type_pointed_to($model_obj): bool
93
+	{
94
+		foreach ($this->get_model_class_names_pointed_to() as $model_obj_classname) {
95
+			if ($model_obj instanceof $model_obj_classname) {
96
+				return true;
97
+			}
98
+		}
99
+		return false;
100
+	}
101 101
 }
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_DMS_Core_4_12_0.dms.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@
 block discarded – undo
57 57
      */
58 58
     public function schema_changes_before_migration()
59 59
     {
60
-        require_once EE_HELPERS . 'EEH_Activation.helper.php';
60
+        require_once EE_HELPERS.'EEH_Activation.helper.php';
61 61
 
62 62
         $table_name = 'esp_answer';
63 63
         $sql        = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
Please login to merge, or discard this patch.
Indentation   +196 added lines, -196 removed lines patch added patch discarded remove patch
@@ -13,63 +13,63 @@  discard block
 block discarded – undo
13 13
  */
14 14
 class EE_DMS_Core_4_12_0 extends EE_Data_Migration_Script_Base
15 15
 {
16
-    /**
17
-     *
18
-     * @param EE_DMS_Core_4_11_0 $dms_4_11
19
-     * @param TableManager|null  $table_manager
20
-     * @param TableAnalysis|null $table_analysis
21
-     */
22
-    public function __construct(
23
-        EE_DMS_Core_4_11_0 $dms_4_11,
24
-        TableManager $table_manager = null,
25
-        TableAnalysis $table_analysis = null
26
-    ) {
27
-        $this->previous_dms      = $dms_4_11;
28
-        $this->_pretty_name      = esc_html__("Data Update to Event Espresso 4.12.0", "event_espresso");
29
-        $this->_priority         = 10;
30
-        $this->_migration_stages = [
31
-
32
-        ];
33
-        parent::__construct($table_manager, $table_analysis);
34
-    }
35
-
36
-
37
-    /**
38
-     * Whether to migrate or not.
39
-     *
40
-     * @param array $version_array
41
-     * @return bool
42
-     */
43
-    public function can_migrate_from_version($version_array)
44
-    {
45
-        $version_string = $version_array['Core'];
46
-        return $version_string
47
-               && version_compare($version_string, '4.12.0.decaf', '<')
48
-               && version_compare($version_string, '4.11.0.decaf', '>=');
49
-    }
50
-
51
-
52
-    /**
53
-     * @return bool
54
-     * @throws EE_Error
55
-     * @throws ReflectionException
56
-     */
57
-    public function schema_changes_before_migration()
58
-    {
59
-        require_once EE_HELPERS . 'EEH_Activation.helper.php';
60
-
61
-        $table_name = 'esp_answer';
62
-        $sql        = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
16
+	/**
17
+	 *
18
+	 * @param EE_DMS_Core_4_11_0 $dms_4_11
19
+	 * @param TableManager|null  $table_manager
20
+	 * @param TableAnalysis|null $table_analysis
21
+	 */
22
+	public function __construct(
23
+		EE_DMS_Core_4_11_0 $dms_4_11,
24
+		TableManager $table_manager = null,
25
+		TableAnalysis $table_analysis = null
26
+	) {
27
+		$this->previous_dms      = $dms_4_11;
28
+		$this->_pretty_name      = esc_html__("Data Update to Event Espresso 4.12.0", "event_espresso");
29
+		$this->_priority         = 10;
30
+		$this->_migration_stages = [
31
+
32
+		];
33
+		parent::__construct($table_manager, $table_analysis);
34
+	}
35
+
36
+
37
+	/**
38
+	 * Whether to migrate or not.
39
+	 *
40
+	 * @param array $version_array
41
+	 * @return bool
42
+	 */
43
+	public function can_migrate_from_version($version_array)
44
+	{
45
+		$version_string = $version_array['Core'];
46
+		return $version_string
47
+			   && version_compare($version_string, '4.12.0.decaf', '<')
48
+			   && version_compare($version_string, '4.11.0.decaf', '>=');
49
+	}
50
+
51
+
52
+	/**
53
+	 * @return bool
54
+	 * @throws EE_Error
55
+	 * @throws ReflectionException
56
+	 */
57
+	public function schema_changes_before_migration()
58
+	{
59
+		require_once EE_HELPERS . 'EEH_Activation.helper.php';
60
+
61
+		$table_name = 'esp_answer';
62
+		$sql        = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
63 63
 					REG_ID int(10) unsigned NOT NULL,
64 64
 					QST_ID int(10) unsigned NOT NULL,
65 65
 					ANS_value text NOT NULL,
66 66
 					PRIMARY KEY  (ANS_ID),
67 67
 					KEY REG_ID (REG_ID),
68 68
 					KEY QST_ID (QST_ID)";
69
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
69
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
70 70
 
71
-        $table_name = 'esp_attendee_meta';
72
-        $sql        = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
71
+		$table_name = 'esp_attendee_meta';
72
+		$sql        = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
73 73
 				ATT_ID bigint(20) unsigned NOT NULL,
74 74
 				ATT_fname varchar(45) NOT NULL,
75 75
 				ATT_lname varchar(45) NOT NULL,
@@ -86,10 +86,10 @@  discard block
 block discarded – undo
86 86
 				KEY ATT_email (ATT_email(191)),
87 87
 				KEY ATT_lname (ATT_lname),
88 88
 				KEY ATT_fname (ATT_fname)";
89
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
89
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
90 90
 
91
-        $table_name = 'esp_checkin';
92
-        $sql        = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
91
+		$table_name = 'esp_checkin';
92
+		$sql        = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
93 93
 				REG_ID int(10) unsigned NOT NULL,
94 94
 				DTT_ID int(10) unsigned NOT NULL,
95 95
 				CHK_in tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -97,10 +97,10 @@  discard block
 block discarded – undo
97 97
 				PRIMARY KEY  (CHK_ID),
98 98
 				KEY REG_ID (REG_ID),
99 99
 				KEY DTT_ID (DTT_ID)";
100
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
100
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
101 101
 
102
-        $table_name = 'esp_country';
103
-        $sql        = "CNT_ISO varchar(2) NOT NULL,
102
+		$table_name = 'esp_country';
103
+		$sql        = "CNT_ISO varchar(2) NOT NULL,
104 104
 				CNT_ISO3 varchar(3) NOT NULL,
105 105
 				RGN_ID tinyint(3) unsigned DEFAULT NULL,
106 106
 				CNT_name varchar(45) NOT NULL,
@@ -116,32 +116,32 @@  discard block
 block discarded – undo
116 116
 				CNT_is_EU tinyint(1) DEFAULT '0',
117 117
 				CNT_active tinyint(1) DEFAULT '0',
118 118
 				PRIMARY KEY  (CNT_ISO)";
119
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
119
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
120 120
 
121
-        $table_name = 'esp_currency';
122
-        $sql        = "CUR_code varchar(6) NOT NULL,
121
+		$table_name = 'esp_currency';
122
+		$sql        = "CUR_code varchar(6) NOT NULL,
123 123
 				CUR_single varchar(45) DEFAULT 'dollar',
124 124
 				CUR_plural varchar(45) DEFAULT 'dollars',
125 125
 				CUR_sign varchar(45) DEFAULT '$',
126 126
 				CUR_dec_plc varchar(1) NOT NULL DEFAULT '2',
127 127
 				CUR_active tinyint(1) DEFAULT '0',
128 128
 				PRIMARY KEY  (CUR_code)";
129
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
130
-
131
-        // note: although this table is no longer in use,
132
-        // it hasn't been removed because then queries to the model will have errors.
133
-        // but you should expect this table and its corresponding model to be removed in
134
-        // the next few months
135
-        $table_name = 'esp_currency_payment_method';
136
-        $sql        = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
129
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
130
+
131
+		// note: although this table is no longer in use,
132
+		// it hasn't been removed because then queries to the model will have errors.
133
+		// but you should expect this table and its corresponding model to be removed in
134
+		// the next few months
135
+		$table_name = 'esp_currency_payment_method';
136
+		$sql        = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
137 137
 				CUR_code varchar(6) NOT NULL,
138 138
 				PMD_ID int(11) NOT NULL,
139 139
 				PRIMARY KEY  (CPM_ID),
140 140
 				KEY PMD_ID (PMD_ID)";
141
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
141
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
142 142
 
143
-        $table_name = 'esp_datetime';
144
-        $sql        = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
143
+		$table_name = 'esp_datetime';
144
+		$sql        = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
145 145
 				EVT_ID bigint(20) unsigned NOT NULL,
146 146
 				DTT_name varchar(255) NOT NULL DEFAULT '',
147 147
 				DTT_description text NOT NULL,
@@ -158,28 +158,28 @@  discard block
 block discarded – undo
158 158
 				KEY DTT_EVT_start (DTT_EVT_start),
159 159
 				KEY EVT_ID (EVT_ID),
160 160
 				KEY DTT_is_primary (DTT_is_primary)";
161
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
161
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
162 162
 
163
-        $table_name = "esp_datetime_ticket";
164
-        $sql        = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
163
+		$table_name = "esp_datetime_ticket";
164
+		$sql        = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
165 165
 				DTT_ID int(10) unsigned NOT NULL,
166 166
 				TKT_ID int(10) unsigned NOT NULL,
167 167
 				PRIMARY KEY  (DTK_ID),
168 168
 				KEY DTT_ID (DTT_ID),
169 169
 				KEY TKT_ID (TKT_ID)";
170
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
170
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
171 171
 
172
-        $table_name = 'esp_event_message_template';
173
-        $sql        = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
172
+		$table_name = 'esp_event_message_template';
173
+		$sql        = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
174 174
 				EVT_ID bigint(20) unsigned NOT NULL DEFAULT 0,
175 175
 				GRP_ID int(10) unsigned NOT NULL DEFAULT 0,
176 176
 				PRIMARY KEY  (EMT_ID),
177 177
 				KEY EVT_ID (EVT_ID),
178 178
 				KEY GRP_ID (GRP_ID)";
179
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
179
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
180 180
 
181
-        $table_name = 'esp_event_meta';
182
-        $sql        = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
181
+		$table_name = 'esp_event_meta';
182
+		$sql        = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
183 183
 				EVT_ID bigint(20) unsigned NOT NULL,
184 184
 				EVT_display_desc tinyint(1) unsigned NOT NULL DEFAULT 1,
185 185
 				EVT_display_ticket_selector tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -194,10 +194,10 @@  discard block
 block discarded – undo
194 194
 				EVT_donations tinyint(1) NULL,
195 195
 				PRIMARY KEY  (EVTM_ID),
196 196
 				KEY EVT_ID (EVT_ID)";
197
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
197
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
198 198
 
199
-        $table_name = 'esp_event_question_group';
200
-        $sql        = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
199
+		$table_name = 'esp_event_question_group';
200
+		$sql        = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
201 201
 				EVT_ID bigint(20) unsigned NOT NULL,
202 202
 				QSG_ID int(10) unsigned NOT NULL,
203 203
 				EQG_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
@@ -205,28 +205,28 @@  discard block
 block discarded – undo
205 205
 				PRIMARY KEY  (EQG_ID),
206 206
 				KEY EVT_ID (EVT_ID),
207 207
 				KEY QSG_ID (QSG_ID)";
208
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
208
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
209 209
 
210
-        $table_name = 'esp_event_venue';
211
-        $sql        = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
210
+		$table_name = 'esp_event_venue';
211
+		$sql        = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
212 212
 				EVT_ID bigint(20) unsigned NOT NULL,
213 213
 				VNU_ID bigint(20) unsigned NOT NULL,
214 214
 				EVV_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
215 215
 				PRIMARY KEY  (EVV_ID)";
216
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
216
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
217 217
 
218
-        $table_name = 'esp_extra_meta';
219
-        $sql        = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
218
+		$table_name = 'esp_extra_meta';
219
+		$sql        = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
220 220
 				OBJ_ID int(11) DEFAULT NULL,
221 221
 				EXM_type varchar(45) DEFAULT NULL,
222 222
 				EXM_key varchar(45) DEFAULT NULL,
223 223
 				EXM_value text,
224 224
 				PRIMARY KEY  (EXM_ID),
225 225
 				KEY EXM_type (EXM_type,OBJ_ID,EXM_key)";
226
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
226
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
227 227
 
228
-        $table_name = 'esp_extra_join';
229
-        $sql        = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
228
+		$table_name = 'esp_extra_join';
229
+		$sql        = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
230 230
 				EXJ_first_model_id varchar(6) NOT NULL,
231 231
 				EXJ_first_model_name varchar(20) NOT NULL,
232 232
 				EXJ_second_model_id varchar(6) NOT NULL,
@@ -234,10 +234,10 @@  discard block
 block discarded – undo
234 234
 				PRIMARY KEY  (EXJ_ID),
235 235
 				KEY first_model (EXJ_first_model_name,EXJ_first_model_id),
236 236
 				KEY second_model (EXJ_second_model_name,EXJ_second_model_id)";
237
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
237
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
238 238
 
239
-        $table_name = 'esp_form_section';
240
-        $sql        = 'FSC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
239
+		$table_name = 'esp_form_section';
240
+		$sql        = 'FSC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
241 241
                 FSC_UUID binary(16) NOT NULL,
242 242
 				FSC_appliesTo tinytext NOT NULL,
243 243
 				FSC_belongsTo binary(16) NULL,
@@ -251,10 +251,10 @@  discard block
 block discarded – undo
251 251
 				KEY FSC_belongsTo (FSC_belongsTo),
252 252
 				KEY FSC_order (FSC_order),
253 253
 				KEY FSC_status (FSC_status)';
254
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
254
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
255 255
 
256
-        $table_name = 'esp_form_input';
257
-        $sql        = 'FIN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
256
+		$table_name = 'esp_form_input';
257
+		$sql        = 'FIN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
258 258
                 FIN_UUID binary(16) NOT NULL,
259 259
 				FIN_adminLabel tinytext NOT NULL,
260 260
 				FIN_adminOnly tinyint(1) unsigned NOT NULL DEFAULT 0,
@@ -277,11 +277,11 @@  discard block
 block discarded – undo
277 277
 				KEY FIN_belongsTo (FIN_belongsTo),
278 278
 				KEY FIN_order (FIN_order),
279 279
 				KEY FIN_status (FIN_status)';
280
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
280
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
281 281
 
282
-        $now_in_mysql = current_time('mysql', true);
283
-        $table_name   = 'esp_line_item';
284
-        $sql          = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
282
+		$now_in_mysql = current_time('mysql', true);
283
+		$table_name   = 'esp_line_item';
284
+		$sql          = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
285 285
 				LIN_code varchar(245) NOT NULL DEFAULT '',
286 286
 				TXN_ID int(11) DEFAULT NULL,
287 287
 				LIN_name varchar(245) NOT NULL DEFAULT '',
@@ -302,10 +302,10 @@  discard block
 block discarded – undo
302 302
 				KEY txn_type_timestamp (TXN_ID,LIN_type,LIN_timestamp),
303 303
 				KEY txn_obj_id_obj_type (TXN_ID,OBJ_ID,OBJ_type),
304 304
 				KEY obj_id_obj_type (OBJ_ID,OBJ_type)";
305
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
305
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
306 306
 
307
-        $table_name = 'esp_log';
308
-        $sql        = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
307
+		$table_name = 'esp_log';
308
+		$sql        = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
309 309
 				LOG_time datetime DEFAULT NULL,
310 310
 				OBJ_ID varchar(45) DEFAULT NULL,
311 311
 				OBJ_type varchar(45) DEFAULT NULL,
@@ -316,10 +316,10 @@  discard block
 block discarded – undo
316 316
 				KEY LOG_time (LOG_time),
317 317
 				KEY OBJ (OBJ_type,OBJ_ID),
318 318
 				KEY LOG_type (LOG_type)";
319
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
319
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
320 320
 
321
-        $table_name = 'esp_message';
322
-        $sql        = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
321
+		$table_name = 'esp_message';
322
+		$sql        = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
323 323
 				GRP_ID int(10) unsigned NULL,
324 324
 				MSG_token varchar(255) NULL,
325 325
 				TXN_ID int(10) unsigned NULL,
@@ -351,20 +351,20 @@  discard block
 block discarded – undo
351 351
 				KEY STS_ID (STS_ID),
352 352
 				KEY MSG_created (MSG_created),
353 353
 				KEY MSG_modified (MSG_modified)";
354
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
354
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
355 355
 
356
-        $table_name = 'esp_message_template';
357
-        $sql        = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
356
+		$table_name = 'esp_message_template';
357
+		$sql        = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
358 358
 				GRP_ID int(10) unsigned NOT NULL,
359 359
 				MTP_context varchar(50) NOT NULL,
360 360
 				MTP_template_field varchar(30) NOT NULL,
361 361
 				MTP_content text NOT NULL,
362 362
 				PRIMARY KEY  (MTP_ID),
363 363
 				KEY GRP_ID (GRP_ID)";
364
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
364
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
365 365
 
366
-        $table_name = 'esp_message_template_group';
367
-        $sql        = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
366
+		$table_name = 'esp_message_template_group';
367
+		$sql        = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
368 368
 				MTP_user_id int(10) NOT NULL DEFAULT '1',
369 369
 				MTP_name varchar(245) NOT NULL DEFAULT '',
370 370
 				MTP_description varchar(245) NOT NULL DEFAULT '',
@@ -376,10 +376,10 @@  discard block
 block discarded – undo
376 376
 				MTP_is_active tinyint(1) NOT NULL DEFAULT '1',
377 377
 				PRIMARY KEY  (GRP_ID),
378 378
 				KEY MTP_user_id (MTP_user_id)";
379
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
379
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
380 380
 
381
-        $table_name = 'esp_payment';
382
-        $sql        = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
381
+		$table_name = 'esp_payment';
382
+		$sql        = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
383 383
 				TXN_ID int(10) unsigned DEFAULT NULL,
384 384
 				STS_ID varchar(3) DEFAULT NULL,
385 385
 				PAY_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -396,10 +396,10 @@  discard block
 block discarded – undo
396 396
 				PRIMARY KEY  (PAY_ID),
397 397
 				KEY PAY_timestamp (PAY_timestamp),
398 398
 				KEY TXN_ID (TXN_ID)";
399
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
399
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
400 400
 
401
-        $table_name = 'esp_payment_method';
402
-        $sql        = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
401
+		$table_name = 'esp_payment_method';
402
+		$sql        = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
403 403
 				PMD_type varchar(124) DEFAULT NULL,
404 404
 				PMD_name varchar(255) DEFAULT NULL,
405 405
 				PMD_desc text,
@@ -415,10 +415,10 @@  discard block
 block discarded – undo
415 415
 				PRIMARY KEY  (PMD_ID),
416 416
 				UNIQUE KEY PMD_slug_UNIQUE (PMD_slug),
417 417
 				KEY PMD_type (PMD_type)";
418
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
418
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
419 419
 
420
-        $table_name = "esp_price";
421
-        $sql        = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
420
+		$table_name = "esp_price";
421
+		$sql        = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
422 422
 				PRT_ID tinyint(3) unsigned NOT NULL,
423 423
 				PRC_amount decimal(12,3) NOT NULL DEFAULT '0.00',
424 424
 				PRC_name varchar(245) NOT NULL,
@@ -431,10 +431,10 @@  discard block
 block discarded – undo
431 431
 				PRC_parent int(10) unsigned DEFAULT 0,
432 432
 				PRIMARY KEY  (PRC_ID),
433 433
 				KEY PRT_ID (PRT_ID)";
434
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
434
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
435 435
 
436
-        $table_name = "esp_price_type";
437
-        $sql        = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
436
+		$table_name = "esp_price_type";
437
+		$sql        = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
438 438
 				PRT_name varchar(45) NOT NULL,
439 439
 				PBT_ID tinyint(3) unsigned NOT NULL DEFAULT '1',
440 440
 				PRT_is_percent tinyint(1) NOT NULL DEFAULT '0',
@@ -443,27 +443,27 @@  discard block
 block discarded – undo
443 443
 				PRT_deleted tinyint(1) NOT NULL DEFAULT '0',
444 444
 				UNIQUE KEY PRT_name_UNIQUE (PRT_name),
445 445
 				PRIMARY KEY  (PRT_ID)";
446
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
446
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
447 447
 
448
-        $table_name = "esp_ticket_price";
449
-        $sql        = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
448
+		$table_name = "esp_ticket_price";
449
+		$sql        = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
450 450
 				TKT_ID int(10) unsigned NOT NULL,
451 451
 				PRC_ID int(10) unsigned NOT NULL,
452 452
 				PRIMARY KEY  (TKP_ID),
453 453
 				KEY TKT_ID (TKT_ID),
454 454
 				KEY PRC_ID (PRC_ID)";
455
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
455
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
456 456
 
457
-        $table_name = "esp_ticket_template";
458
-        $sql        = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
457
+		$table_name = "esp_ticket_template";
458
+		$sql        = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
459 459
 				TTM_name varchar(45) NOT NULL,
460 460
 				TTM_description text,
461 461
 				TTM_file varchar(45),
462 462
 				PRIMARY KEY  (TTM_ID)";
463
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
463
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
464 464
 
465
-        $table_name = 'esp_question';
466
-        $sql        = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
465
+		$table_name = 'esp_question';
466
+		$sql        = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
467 467
 				QST_display_text text NOT NULL,
468 468
 				QST_admin_label varchar(255) NOT NULL,
469 469
 				QST_system varchar(25) DEFAULT NULL,
@@ -477,10 +477,10 @@  discard block
 block discarded – undo
477 477
 				QST_deleted tinyint(2) unsigned NOT NULL DEFAULT 0,
478 478
 				PRIMARY KEY  (QST_ID),
479 479
 				KEY QST_order (QST_order)';
480
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
480
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
481 481
 
482
-        $table_name = 'esp_question_group';
483
-        $sql        = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
482
+		$table_name = 'esp_question_group';
483
+		$sql        = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
484 484
 				QSG_name varchar(255) NOT NULL,
485 485
 				QSG_identifier varchar(100) NOT NULL,
486 486
 				QSG_desc text NULL,
@@ -493,20 +493,20 @@  discard block
 block discarded – undo
493 493
 				PRIMARY KEY  (QSG_ID),
494 494
 				UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier),
495 495
 				KEY QSG_order (QSG_order)';
496
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
496
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
497 497
 
498
-        $table_name = 'esp_question_group_question';
499
-        $sql        = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
498
+		$table_name = 'esp_question_group_question';
499
+		$sql        = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
500 500
 				QSG_ID int(10) unsigned NOT NULL,
501 501
 				QST_ID int(10) unsigned NOT NULL,
502 502
 				QGQ_order int(10) unsigned NOT NULL DEFAULT 0,
503 503
 				PRIMARY KEY  (QGQ_ID),
504 504
 				KEY QST_ID (QST_ID),
505 505
 				KEY QSG_ID_order (QSG_ID,QGQ_order)";
506
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
506
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
507 507
 
508
-        $table_name = 'esp_question_option';
509
-        $sql        = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
508
+		$table_name = 'esp_question_option';
509
+		$sql        = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
510 510
 				QSO_value varchar(255) NOT NULL,
511 511
 				QSO_desc text NOT NULL,
512 512
 				QST_ID int(10) unsigned NOT NULL,
@@ -516,10 +516,10 @@  discard block
 block discarded – undo
516 516
 				PRIMARY KEY  (QSO_ID),
517 517
 				KEY QST_ID (QST_ID),
518 518
 				KEY QSO_order (QSO_order)";
519
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
519
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
520 520
 
521
-        $table_name = 'esp_registration';
522
-        $sql        = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
521
+		$table_name = 'esp_registration';
522
+		$sql        = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
523 523
 				EVT_ID bigint(20) unsigned NOT NULL,
524 524
 				ATT_ID bigint(20) unsigned NOT NULL,
525 525
 				TXN_ID int(10) unsigned NOT NULL,
@@ -543,20 +543,20 @@  discard block
 block discarded – undo
543 543
 				KEY TKT_ID (TKT_ID),
544 544
 				KEY EVT_ID (EVT_ID),
545 545
 				KEY STS_ID (STS_ID)";
546
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
546
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
547 547
 
548
-        $table_name = 'esp_registration_payment';
549
-        $sql        = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
548
+		$table_name = 'esp_registration_payment';
549
+		$sql        = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
550 550
 					  REG_ID int(10) unsigned NOT NULL,
551 551
 					  PAY_ID int(10) unsigned NULL,
552 552
 					  RPY_amount decimal(12,3) NOT NULL DEFAULT '0.00',
553 553
 					  PRIMARY KEY  (RPY_ID),
554 554
 					  KEY REG_ID (REG_ID),
555 555
 					  KEY PAY_ID (PAY_ID)";
556
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
556
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
557 557
 
558
-        $table_name = 'esp_state';
559
-        $sql        = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
558
+		$table_name = 'esp_state';
559
+		$sql        = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
560 560
 				CNT_ISO varchar(2) NOT NULL,
561 561
 				STA_abbrev varchar(24) NOT NULL,
562 562
 				STA_name varchar(100) NOT NULL,
@@ -564,10 +564,10 @@  discard block
 block discarded – undo
564 564
 				PRIMARY KEY  (STA_ID),
565 565
 				KEY STA_abbrev (STA_abbrev),
566 566
 				KEY CNT_ISO (CNT_ISO)";
567
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
567
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
568 568
 
569
-        $table_name = 'esp_status';
570
-        $sql        = "STS_ID varchar(3) NOT NULL,
569
+		$table_name = 'esp_status';
570
+		$sql        = "STS_ID varchar(3) NOT NULL,
571 571
 				STS_code varchar(45) NOT NULL,
572 572
 				STS_type varchar(45) NOT NULL,
573 573
 				STS_can_edit tinyint(1) NOT NULL DEFAULT 0,
@@ -575,10 +575,10 @@  discard block
 block discarded – undo
575 575
 				STS_open tinyint(1) NOT NULL DEFAULT 1,
576 576
 				UNIQUE KEY STS_ID_UNIQUE (STS_ID),
577 577
 				KEY STS_type (STS_type)";
578
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
578
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
579 579
 
580
-        $table_name = "esp_ticket";
581
-        $sql        = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
580
+		$table_name = "esp_ticket";
581
+		$sql        = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
582 582
 				TTM_ID int(10) unsigned NOT NULL,
583 583
 				TKT_name varchar(245) NOT NULL DEFAULT '',
584 584
 				TKT_description text NOT NULL,
@@ -603,10 +603,10 @@  discard block
 block discarded – undo
603 603
 				TKT_visibility smallint(6) unsigned NOT NULL DEFAULT 100,
604 604
 				PRIMARY KEY  (TKT_ID),
605 605
 				KEY TKT_start_date (TKT_start_date)";
606
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
606
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
607 607
 
608
-        $table_name = 'esp_transaction';
609
-        $sql        = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
608
+		$table_name = 'esp_transaction';
609
+		$sql        = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
610 610
 				TXN_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
611 611
 				TXN_total decimal(12,3) DEFAULT '0.00',
612 612
 				TXN_paid decimal(12,3) NOT NULL DEFAULT '0.00',
@@ -618,10 +618,10 @@  discard block
 block discarded – undo
618 618
 				PRIMARY KEY  (TXN_ID),
619 619
 				KEY TXN_timestamp (TXN_timestamp),
620 620
 				KEY STS_ID (STS_ID)";
621
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
621
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
622 622
 
623
-        $table_name = 'esp_venue_meta';
624
-        $sql        = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
623
+		$table_name = 'esp_venue_meta';
624
+		$sql        = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
625 625
 			VNU_ID bigint(20) unsigned NOT NULL DEFAULT 0,
626 626
 			VNU_address varchar(255) DEFAULT NULL,
627 627
 			VNU_address2 varchar(255) DEFAULT NULL,
@@ -640,36 +640,36 @@  discard block
 block discarded – undo
640 640
 			KEY VNU_ID (VNU_ID),
641 641
 			KEY STA_ID (STA_ID),
642 642
 			KEY CNT_ISO (CNT_ISO)";
643
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
644
-
645
-        $this->insert_default_data();
646
-        return true;
647
-    }
648
-
649
-
650
-    /**
651
-     * Inserts default data on new installs
652
-     *
653
-     * @throws EE_Error
654
-     * @throws ReflectionException
655
-     * @since 4.10.0.p
656
-     */
657
-    public function insert_default_data()
658
-    {
659
-        $this->previous_dms->insert_default_data();
660
-    }
661
-
662
-
663
-    /**
664
-     * @return boolean
665
-     */
666
-    public function schema_changes_after_migration()
667
-    {
668
-        return true;
669
-    }
670
-
671
-
672
-    public function migration_page_hooks()
673
-    {
674
-    }
643
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
644
+
645
+		$this->insert_default_data();
646
+		return true;
647
+	}
648
+
649
+
650
+	/**
651
+	 * Inserts default data on new installs
652
+	 *
653
+	 * @throws EE_Error
654
+	 * @throws ReflectionException
655
+	 * @since 4.10.0.p
656
+	 */
657
+	public function insert_default_data()
658
+	{
659
+		$this->previous_dms->insert_default_data();
660
+	}
661
+
662
+
663
+	/**
664
+	 * @return boolean
665
+	 */
666
+	public function schema_changes_after_migration()
667
+	{
668
+		return true;
669
+	}
670
+
671
+
672
+	public function migration_page_hooks()
673
+	{
674
+	}
675 675
 }
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 2 patches
Spacing   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -205,8 +205,8 @@  discard block
 block discarded – undo
205 205
     ) {
206 206
         $class      = trim($class, '\\');
207 207
         $registered = false;
208
-        if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
209
-            EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
208
+        if (empty(EE_Dependency_Map::$_instance->_dependency_map[$class])) {
209
+            EE_Dependency_Map::$_instance->_dependency_map[$class] = [];
210 210
         }
211 211
         // we need to make sure that any aliases used when registering a dependency
212 212
         // get resolved to the correct class name
@@ -214,10 +214,10 @@  discard block
 block discarded – undo
214 214
             $alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
215 215
             if (
216 216
                 $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
217
-                || ! isset(EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ])
217
+                || ! isset(EE_Dependency_Map::$_instance->_dependency_map[$class][$alias])
218 218
             ) {
219
-                unset($dependencies[ $dependency ]);
220
-                $dependencies[ $alias ] = $load_source;
219
+                unset($dependencies[$dependency]);
220
+                $dependencies[$alias] = $load_source;
221 221
                 $registered             = true;
222 222
             }
223 223
         }
@@ -227,13 +227,13 @@  discard block
 block discarded – undo
227 227
         // ie: with A = B + C, entries in B take precedence over duplicate entries in C
228 228
         // Union is way faster than array_merge() but should be used with caution...
229 229
         // especially with numerically indexed arrays
230
-        $dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
230
+        $dependencies += EE_Dependency_Map::$_instance->_dependency_map[$class];
231 231
         // now we need to ensure that the resulting dependencies
232 232
         // array only has the entries that are required for the class
233 233
         // so first count how many dependencies were originally registered for the class
234
-        $dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
234
+        $dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[$class]);
235 235
         // if that count is non-zero (meaning dependencies were already registered)
236
-        EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
236
+        EE_Dependency_Map::$_instance->_dependency_map[$class] = $dependency_count
237 237
             // then truncate the  final array to match that count
238 238
             ? array_slice($dependencies, 0, $dependency_count)
239 239
             // otherwise just take the incoming array because nothing previously existed
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
      */
263 263
     public function registerClassLoader($class_name, $loader = 'load_core')
264 264
     {
265
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
265
+        if ( ! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
266 266
             throw new DomainException(
267 267
                 esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
268 268
             );
@@ -286,8 +286,8 @@  discard block
 block discarded – undo
286 286
             );
287 287
         }
288 288
         $class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
289
-        if (! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
290
-            EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
289
+        if ( ! isset(EE_Dependency_Map::$_instance->_class_loaders[$class_name])) {
290
+            EE_Dependency_Map::$_instance->_class_loaders[$class_name] = $loader;
291 291
             return true;
292 292
         }
293 293
         return false;
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
         if (strpos($class_name, 'EEM_') === 0) {
316 316
             $class_name = 'LEGACY_MODELS';
317 317
         }
318
-        return isset($this->_dependency_map[ $class_name ]);
318
+        return isset($this->_dependency_map[$class_name]);
319 319
     }
320 320
 
321 321
 
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
             $class_name = 'LEGACY_MODELS';
334 334
         }
335 335
         $dependency = $this->getFqnForAlias($dependency, $class_name);
336
-        return isset($this->_dependency_map[ $class_name ][ $dependency ]);
336
+        return isset($this->_dependency_map[$class_name][$dependency]);
337 337
     }
338 338
 
339 339
 
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
         }
353 353
         $dependency = $this->getFqnForAlias($dependency);
354 354
         return $this->has_dependency_for_class($class_name, $dependency)
355
-            ? $this->_dependency_map[ $class_name ][ $dependency ]
355
+            ? $this->_dependency_map[$class_name][$dependency]
356 356
             : EE_Dependency_Map::not_registered;
357 357
     }
358 358
 
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
             return 'load_core';
377 377
         }
378 378
         $class_name = $this->getFqnForAlias($class_name);
379
-        return isset($this->_class_loaders[ $class_name ]) ? $this->_class_loaders[ $class_name ] : '';
379
+        return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
380 380
     }
381 381
 
382 382
 
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
     {
817 817
         $this->_class_loaders = [
818 818
             // load_core
819
-            'EE_Dependency_Map'                            => function () {
819
+            'EE_Dependency_Map'                            => function() {
820 820
                 return $this;
821 821
             },
822 822
             'EE_Capabilities'                              => 'load_core',
@@ -824,13 +824,13 @@  discard block
 block discarded – undo
824 824
             'EE_Front_Controller'                          => 'load_core',
825 825
             'EE_Module_Request_Router'                     => 'load_core',
826 826
             'EE_Registry'                                  => 'load_core',
827
-            'EE_Request'                                   => function () {
827
+            'EE_Request'                                   => function() {
828 828
                 return $this->legacy_request;
829 829
             },
830
-            'EventEspresso\core\services\request\Request'  => function () {
830
+            'EventEspresso\core\services\request\Request'  => function() {
831 831
                 return $this->request;
832 832
             },
833
-            'EventEspresso\core\services\request\Response' => function () {
833
+            'EventEspresso\core\services\request\Response' => function() {
834 834
                 return $this->response;
835 835
             },
836 836
             'EE_Base'                                      => 'load_core',
@@ -867,7 +867,7 @@  discard block
 block discarded – undo
867 867
             'EE_DMS_Core_4_10_0'                           => 'load_dms',
868 868
             'EE_DMS_Core_4_11_0'                           => 'load_dms',
869 869
             'EE_DMS_Core_4_12_0'                           => 'load_dms',
870
-            'EE_Messages_Generator'                        => static function () {
870
+            'EE_Messages_Generator'                        => static function() {
871 871
                 return EE_Registry::instance()->load_lib(
872 872
                     'Messages_Generator',
873 873
                     [],
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
                     false
876 876
                 );
877 877
             },
878
-            'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
878
+            'EE_Messages_Template_Defaults'                => static function($arguments = []) {
879 879
                 return EE_Registry::instance()->load_lib(
880 880
                     'Messages_Template_Defaults',
881 881
                     $arguments,
@@ -884,55 +884,55 @@  discard block
 block discarded – undo
884 884
                 );
885 885
             },
886 886
             // load_helper
887
-            'EEH_Parse_Shortcodes'                         => static function () {
887
+            'EEH_Parse_Shortcodes'                         => static function() {
888 888
                 if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
889 889
                     return new EEH_Parse_Shortcodes();
890 890
                 }
891 891
                 return null;
892 892
             },
893
-            'EE_Template_Config'                           => static function () {
893
+            'EE_Template_Config'                           => static function() {
894 894
                 return EE_Config::instance()->template_settings;
895 895
             },
896
-            'EE_Currency_Config'                           => static function () {
896
+            'EE_Currency_Config'                           => static function() {
897 897
                 return EE_Config::instance()->currency;
898 898
             },
899
-            'EE_Registration_Config'                       => static function () {
899
+            'EE_Registration_Config'                       => static function() {
900 900
                 return EE_Config::instance()->registration;
901 901
             },
902
-            'EE_Core_Config'                               => static function () {
902
+            'EE_Core_Config'                               => static function() {
903 903
                 return EE_Config::instance()->core;
904 904
             },
905
-            'EventEspresso\core\services\loaders\Loader'   => static function () {
905
+            'EventEspresso\core\services\loaders\Loader'   => static function() {
906 906
                 return LoaderFactory::getLoader();
907 907
             },
908
-            'EE_Network_Config'                            => static function () {
908
+            'EE_Network_Config'                            => static function() {
909 909
                 return EE_Network_Config::instance();
910 910
             },
911
-            'EE_Config'                                    => static function () {
911
+            'EE_Config'                                    => static function() {
912 912
                 return EE_Config::instance();
913 913
             },
914
-            'EventEspresso\core\domain\Domain'             => static function () {
914
+            'EventEspresso\core\domain\Domain'             => static function() {
915 915
                 return DomainFactory::getEventEspressoCoreDomain();
916 916
             },
917
-            'EE_Admin_Config'                              => static function () {
917
+            'EE_Admin_Config'                              => static function() {
918 918
                 return EE_Config::instance()->admin;
919 919
             },
920
-            'EE_Organization_Config'                       => static function () {
920
+            'EE_Organization_Config'                       => static function() {
921 921
                 return EE_Config::instance()->organization;
922 922
             },
923
-            'EE_Network_Core_Config'                       => static function () {
923
+            'EE_Network_Core_Config'                       => static function() {
924 924
                 return EE_Network_Config::instance()->core;
925 925
             },
926
-            'EE_Environment_Config'                        => static function () {
926
+            'EE_Environment_Config'                        => static function() {
927 927
                 return EE_Config::instance()->environment;
928 928
             },
929
-            'EED_Core_Rest_Api'                            => static function () {
929
+            'EED_Core_Rest_Api'                            => static function() {
930 930
                 return EED_Core_Rest_Api::instance();
931 931
             },
932
-            'WP_REST_Server'                               => static function () {
932
+            'WP_REST_Server'                               => static function() {
933 933
                 return rest_get_server();
934 934
             },
935
-            'EventEspresso\core\Psr4Autoloader'            => static function () {
935
+            'EventEspresso\core\Psr4Autoloader'            => static function() {
936 936
                 return EE_Psr4AutoloaderInit::psr4_loader();
937 937
             },
938 938
         ];
@@ -997,7 +997,7 @@  discard block
 block discarded – undo
997 997
             }
998 998
             $this->class_cache->addAlias($fqn, $alias);
999 999
         }
1000
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1000
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1001 1001
             $this->class_cache->addAlias(
1002 1002
                 'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1003 1003
                 'EventEspresso\core\services\notices\NoticeConverterInterface'
Please login to merge, or discard this patch.
Indentation   +1056 added lines, -1056 removed lines patch added patch discarded remove patch
@@ -22,1060 +22,1060 @@
 block discarded – undo
22 22
 class EE_Dependency_Map
23 23
 {
24 24
 
25
-    /**
26
-     * This means that the requested class dependency is not present in the dependency map
27
-     */
28
-    const not_registered = 0;
29
-
30
-    /**
31
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
32
-     */
33
-    const load_new_object = 1;
34
-
35
-    /**
36
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
37
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
38
-     */
39
-    const load_from_cache = 2;
40
-
41
-    /**
42
-     * When registering a dependency,
43
-     * this indicates to keep any existing dependencies that already exist,
44
-     * and simply discard any new dependencies declared in the incoming data
45
-     */
46
-    const KEEP_EXISTING_DEPENDENCIES = 0;
47
-
48
-    /**
49
-     * When registering a dependency,
50
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
51
-     */
52
-    const OVERWRITE_DEPENDENCIES = 1;
53
-
54
-    /**
55
-     * @type EE_Dependency_Map $_instance
56
-     */
57
-    protected static $_instance;
58
-
59
-    /**
60
-     * @var ClassInterfaceCache $class_cache
61
-     */
62
-    private $class_cache;
63
-
64
-    /**
65
-     * @type RequestInterface $request
66
-     */
67
-    protected $request;
68
-
69
-    /**
70
-     * @type LegacyRequestInterface $legacy_request
71
-     */
72
-    protected $legacy_request;
73
-
74
-    /**
75
-     * @type ResponseInterface $response
76
-     */
77
-    protected $response;
78
-
79
-    /**
80
-     * @type LoaderInterface $loader
81
-     */
82
-    protected $loader;
83
-
84
-    /**
85
-     * @type array $_dependency_map
86
-     */
87
-    protected $_dependency_map = [];
88
-
89
-    /**
90
-     * @type array $_class_loaders
91
-     */
92
-    protected $_class_loaders = [];
93
-
94
-
95
-    /**
96
-     * EE_Dependency_Map constructor.
97
-     *
98
-     * @param ClassInterfaceCache $class_cache
99
-     */
100
-    protected function __construct(ClassInterfaceCache $class_cache)
101
-    {
102
-        $this->class_cache = $class_cache;
103
-        do_action('EE_Dependency_Map____construct', $this);
104
-    }
105
-
106
-
107
-    /**
108
-     * @return void
109
-     * @throws InvalidAliasException
110
-     */
111
-    public function initialize()
112
-    {
113
-        $this->_register_core_dependencies();
114
-        $this->_register_core_class_loaders();
115
-        $this->_register_core_aliases();
116
-    }
117
-
118
-
119
-    /**
120
-     * @singleton method used to instantiate class object
121
-     * @param ClassInterfaceCache|null $class_cache
122
-     * @return EE_Dependency_Map
123
-     */
124
-    public static function instance(ClassInterfaceCache $class_cache = null)
125
-    {
126
-        // check if class object is instantiated, and instantiated properly
127
-        if (
128
-            ! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
129
-            && $class_cache instanceof ClassInterfaceCache
130
-        ) {
131
-            EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
132
-        }
133
-        return EE_Dependency_Map::$_instance;
134
-    }
135
-
136
-
137
-    /**
138
-     * @param RequestInterface $request
139
-     */
140
-    public function setRequest(RequestInterface $request)
141
-    {
142
-        $this->request = $request;
143
-    }
144
-
145
-
146
-    /**
147
-     * @param LegacyRequestInterface $legacy_request
148
-     */
149
-    public function setLegacyRequest(LegacyRequestInterface $legacy_request)
150
-    {
151
-        $this->legacy_request = $legacy_request;
152
-    }
153
-
154
-
155
-    /**
156
-     * @param ResponseInterface $response
157
-     */
158
-    public function setResponse(ResponseInterface $response)
159
-    {
160
-        $this->response = $response;
161
-    }
162
-
163
-
164
-    /**
165
-     * @param LoaderInterface $loader
166
-     */
167
-    public function setLoader(LoaderInterface $loader)
168
-    {
169
-        $this->loader = $loader;
170
-    }
171
-
172
-
173
-    /**
174
-     * @param string $class
175
-     * @param array  $dependencies
176
-     * @param int    $overwrite
177
-     * @return bool
178
-     */
179
-    public static function register_dependencies(
180
-        $class,
181
-        array $dependencies,
182
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
183
-    ) {
184
-        return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
185
-    }
186
-
187
-
188
-    /**
189
-     * Assigns an array of class names and corresponding load sources (new or cached)
190
-     * to the class specified by the first parameter.
191
-     * IMPORTANT !!!
192
-     * The order of elements in the incoming $dependencies array MUST match
193
-     * the order of the constructor parameters for the class in question.
194
-     * This is especially important when overriding any existing dependencies that are registered.
195
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
196
-     *
197
-     * @param string $class
198
-     * @param array  $dependencies
199
-     * @param int    $overwrite
200
-     * @return bool
201
-     */
202
-    public function registerDependencies(
203
-        $class,
204
-        array $dependencies,
205
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
206
-    ) {
207
-        $class      = trim($class, '\\');
208
-        $registered = false;
209
-        if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
210
-            EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
211
-        }
212
-        // we need to make sure that any aliases used when registering a dependency
213
-        // get resolved to the correct class name
214
-        foreach ($dependencies as $dependency => $load_source) {
215
-            $alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
216
-            if (
217
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
218
-                || ! isset(EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ])
219
-            ) {
220
-                unset($dependencies[ $dependency ]);
221
-                $dependencies[ $alias ] = $load_source;
222
-                $registered             = true;
223
-            }
224
-        }
225
-        // now add our two lists of dependencies together.
226
-        // using Union (+=) favours the arrays in precedence from left to right,
227
-        // so $dependencies is NOT overwritten because it is listed first
228
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
229
-        // Union is way faster than array_merge() but should be used with caution...
230
-        // especially with numerically indexed arrays
231
-        $dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
232
-        // now we need to ensure that the resulting dependencies
233
-        // array only has the entries that are required for the class
234
-        // so first count how many dependencies were originally registered for the class
235
-        $dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
236
-        // if that count is non-zero (meaning dependencies were already registered)
237
-        EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
238
-            // then truncate the  final array to match that count
239
-            ? array_slice($dependencies, 0, $dependency_count)
240
-            // otherwise just take the incoming array because nothing previously existed
241
-            : $dependencies;
242
-        return $registered;
243
-    }
244
-
245
-
246
-    /**
247
-     * @param string $class_name
248
-     * @param string $loader
249
-     * @return bool
250
-     * @throws DomainException
251
-     */
252
-    public static function register_class_loader($class_name, $loader = 'load_core')
253
-    {
254
-        return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader);
255
-    }
256
-
257
-
258
-    /**
259
-     * @param string $class_name
260
-     * @param string $loader
261
-     * @return bool
262
-     * @throws DomainException
263
-     */
264
-    public function registerClassLoader($class_name, $loader = 'load_core')
265
-    {
266
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
267
-            throw new DomainException(
268
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
269
-            );
270
-        }
271
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
272
-        if (
273
-            ! is_callable($loader)
274
-            && (
275
-                strpos($loader, 'load_') !== 0
276
-                || ! method_exists('EE_Registry', $loader)
277
-            )
278
-        ) {
279
-            throw new DomainException(
280
-                sprintf(
281
-                    esc_html__(
282
-                        '"%1$s" is not a valid loader method on EE_Registry.',
283
-                        'event_espresso'
284
-                    ),
285
-                    $loader
286
-                )
287
-            );
288
-        }
289
-        $class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
290
-        if (! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
291
-            EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
292
-            return true;
293
-        }
294
-        return false;
295
-    }
296
-
297
-
298
-    /**
299
-     * @return array
300
-     */
301
-    public function dependency_map()
302
-    {
303
-        return $this->_dependency_map;
304
-    }
305
-
306
-
307
-    /**
308
-     * returns TRUE if dependency map contains a listing for the provided class name
309
-     *
310
-     * @param string $class_name
311
-     * @return boolean
312
-     */
313
-    public function has($class_name = '')
314
-    {
315
-        // all legacy models have the same dependencies
316
-        if (strpos($class_name, 'EEM_') === 0) {
317
-            $class_name = 'LEGACY_MODELS';
318
-        }
319
-        return isset($this->_dependency_map[ $class_name ]);
320
-    }
321
-
322
-
323
-    /**
324
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
325
-     *
326
-     * @param string $class_name
327
-     * @param string $dependency
328
-     * @return bool
329
-     */
330
-    public function has_dependency_for_class($class_name = '', $dependency = '')
331
-    {
332
-        // all legacy models have the same dependencies
333
-        if (strpos($class_name, 'EEM_') === 0) {
334
-            $class_name = 'LEGACY_MODELS';
335
-        }
336
-        $dependency = $this->getFqnForAlias($dependency, $class_name);
337
-        return isset($this->_dependency_map[ $class_name ][ $dependency ]);
338
-    }
339
-
340
-
341
-    /**
342
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
343
-     *
344
-     * @param string $class_name
345
-     * @param string $dependency
346
-     * @return int
347
-     */
348
-    public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
349
-    {
350
-        // all legacy models have the same dependencies
351
-        if (strpos($class_name, 'EEM_') === 0) {
352
-            $class_name = 'LEGACY_MODELS';
353
-        }
354
-        $dependency = $this->getFqnForAlias($dependency);
355
-        return $this->has_dependency_for_class($class_name, $dependency)
356
-            ? $this->_dependency_map[ $class_name ][ $dependency ]
357
-            : EE_Dependency_Map::not_registered;
358
-    }
359
-
360
-
361
-    /**
362
-     * @param string $class_name
363
-     * @return string | Closure
364
-     */
365
-    public function class_loader($class_name)
366
-    {
367
-        // all legacy models use load_model()
368
-        if (strpos($class_name, 'EEM_') === 0) {
369
-            return 'load_model';
370
-        }
371
-        // EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
372
-        // perform strpos() first to avoid loading regex every time we load a class
373
-        if (
374
-            strpos($class_name, 'EE_CPT_') === 0
375
-            && preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
376
-        ) {
377
-            return 'load_core';
378
-        }
379
-        $class_name = $this->getFqnForAlias($class_name);
380
-        return isset($this->_class_loaders[ $class_name ]) ? $this->_class_loaders[ $class_name ] : '';
381
-    }
382
-
383
-
384
-    /**
385
-     * @return array
386
-     */
387
-    public function class_loaders()
388
-    {
389
-        return $this->_class_loaders;
390
-    }
391
-
392
-
393
-    /**
394
-     * adds an alias for a classname
395
-     *
396
-     * @param string $fqcn      the class name that should be used (concrete class to replace interface)
397
-     * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
398
-     * @param string $for_class the class that has the dependency (is type hinting for the interface)
399
-     * @throws InvalidAliasException
400
-     */
401
-    public function add_alias($fqcn, $alias, $for_class = '')
402
-    {
403
-        $this->class_cache->addAlias($fqcn, $alias, $for_class);
404
-    }
405
-
406
-
407
-    /**
408
-     * Returns TRUE if the provided fully qualified name IS an alias
409
-     * WHY?
410
-     * Because if a class is type hinting for a concretion,
411
-     * then why would we need to find another class to supply it?
412
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
413
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
414
-     * Don't go looking for some substitute.
415
-     * Whereas if a class is type hinting for an interface...
416
-     * then we need to find an actual class to use.
417
-     * So the interface IS the alias for some other FQN,
418
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
419
-     * represents some other class.
420
-     *
421
-     * @param string $fqn
422
-     * @param string $for_class
423
-     * @return bool
424
-     */
425
-    public function isAlias($fqn = '', $for_class = '')
426
-    {
427
-        return $this->class_cache->isAlias($fqn, $for_class);
428
-    }
429
-
430
-
431
-    /**
432
-     * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
433
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
434
-     *  for example:
435
-     *      if the following two entries were added to the _aliases array:
436
-     *          array(
437
-     *              'interface_alias'           => 'some\namespace\interface'
438
-     *              'some\namespace\interface'  => 'some\namespace\classname'
439
-     *          )
440
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
441
-     *      to load an instance of 'some\namespace\classname'
442
-     *
443
-     * @param string $alias
444
-     * @param string $for_class
445
-     * @return string
446
-     */
447
-    public function getFqnForAlias($alias = '', $for_class = '')
448
-    {
449
-        return (string) $this->class_cache->getFqnForAlias($alias, $for_class);
450
-    }
451
-
452
-
453
-    /**
454
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
455
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
456
-     * This is done by using the following class constants:
457
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
458
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
459
-     */
460
-    protected function _register_core_dependencies()
461
-    {
462
-        $this->_dependency_map = [
463
-            'EE_Request_Handler'                                                                                          => [
464
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
465
-            ],
466
-            'EE_System'                                                                                                   => [
467
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
468
-                'EE_Maintenance_Mode'                         => EE_Dependency_Map::load_from_cache,
469
-                'EE_Registry'                                 => EE_Dependency_Map::load_from_cache,
470
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
471
-                'EventEspresso\core\services\routing\Router'  => EE_Dependency_Map::load_from_cache,
472
-            ],
473
-            'EE_Admin'                                                                                                    => [
474
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
475
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
476
-            ],
477
-            'EE_Cart'                                                                                                     => [
478
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
479
-            ],
480
-            'EE_Messenger_Collection_Loader'                                                                              => [
481
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
482
-            ],
483
-            'EE_Message_Type_Collection_Loader'                                                                           => [
484
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
485
-            ],
486
-            'EE_Message_Resource_Manager'                                                                                 => [
487
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
488
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
489
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
490
-            ],
491
-            'EE_Message_Factory'                                                                                          => [
492
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
493
-            ],
494
-            'EE_messages'                                                                                                 => [
495
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
496
-            ],
497
-            'EE_Messages_Generator'                                                                                       => [
498
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
499
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
500
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
501
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
502
-            ],
503
-            'EE_Messages_Processor'                                                                                       => [
504
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
505
-            ],
506
-            'EE_Messages_Queue'                                                                                           => [
507
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
508
-            ],
509
-            'EE_Messages_Template_Defaults'                                                                               => [
510
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
511
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
512
-            ],
513
-            'EE_Message_To_Generate_From_Request'                                                                         => [
514
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
515
-                'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
516
-            ],
517
-            'EventEspresso\core\services\commands\CommandBus'                                                             => [
518
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
519
-            ],
520
-            'EventEspresso\services\commands\CommandHandler'                                                              => [
521
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
522
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
523
-            ],
524
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => [
525
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
526
-            ],
527
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => [
528
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
529
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
530
-            ],
531
-            'EventEspresso\core\services\commands\CommandFactory'                                                         => [
532
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
533
-            ],
534
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => [
535
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
536
-            ],
537
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => [
538
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
539
-            ],
540
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => [
541
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
542
-            ],
543
-            'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => [
544
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
545
-            ],
546
-            'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
547
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
548
-            ],
549
-            'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
550
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
551
-            ],
552
-            'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
553
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
554
-            ],
555
-            'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
556
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
557
-            ],
558
-            'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
559
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
560
-            ],
561
-            'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
562
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
563
-            ],
564
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => [
565
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
566
-            ],
567
-            'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
568
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
569
-            ],
570
-            'EventEspresso\core\services\database\TableManager'                                                           => [
571
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
572
-            ],
573
-            'EE_Data_Migration_Class_Base'                                                                                => [
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
-            'EE_DMS_Core_4_1_0'                                                                                           => [
578
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
579
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
580
-            ],
581
-            'EE_DMS_Core_4_2_0'                                                                                           => [
582
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
583
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
584
-            ],
585
-            'EE_DMS_Core_4_3_0'                                                                                           => [
586
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
587
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
588
-            ],
589
-            'EE_DMS_Core_4_4_0'                                                                                           => [
590
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
591
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
592
-            ],
593
-            'EE_DMS_Core_4_5_0'                                                                                           => [
594
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
595
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
596
-            ],
597
-            'EE_DMS_Core_4_6_0'                                                                                           => [
598
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
599
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
600
-            ],
601
-            'EE_DMS_Core_4_7_0'                                                                                           => [
602
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
603
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
604
-            ],
605
-            'EE_DMS_Core_4_8_0'                                                                                           => [
606
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
607
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
608
-            ],
609
-            'EE_DMS_Core_4_9_0'                                                                                           => [
610
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
611
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
612
-            ],
613
-            'EE_DMS_Core_4_10_0'                                                                                          => [
614
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
615
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
616
-                'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
617
-            ],
618
-            'EE_DMS_Core_4_11_0'                                                                                          => [
619
-                'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
620
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
621
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
622
-            ],
623
-            'EE_DMS_Core_4_12_0' => [
624
-                'EE_DMS_Core_4_11_0'                                 => EE_Dependency_Map::load_from_cache,
625
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
626
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
627
-            ],
628
-            'EventEspresso\core\services\assets\Registry'                                                                 => [
629
-                'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_new_object,
630
-                'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
631
-            ],
632
-            'EventEspresso\core\services\cache\BasicCacheManager'                                                         => [
633
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
634
-            ],
635
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => [
636
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
637
-            ],
638
-            'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                  => [
639
-                'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
640
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
641
-            ],
642
-            'EventEspresso\core\domain\values\EmailAddress'                                                               => [
643
-                null,
644
-                'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
645
-            ],
646
-            'EventEspresso\core\services\orm\ModelFieldFactory'                                                           => [
647
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
648
-            ],
649
-            'LEGACY_MODELS'                                                                                               => [
650
-                null,
651
-                'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
652
-            ],
653
-            'EE_Module_Request_Router'                                                                                    => [
654
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
655
-            ],
656
-            'EE_Registration_Processor'                                                                                   => [
657
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
658
-            ],
659
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                      => [
660
-                null,
661
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
662
-                'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
663
-            ],
664
-            'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                    => [
665
-                'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
666
-                'EE_Session'             => EE_Dependency_Map::load_from_cache,
667
-            ],
668
-            'EventEspresso\modules\ticket_selector\DisplayTicketSelector'                                                 => [
669
-                'EventEspresso\core\domain\entities\users\CurrentUser' => EE_Dependency_Map::load_from_cache,
670
-            ],
671
-            'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                 => [
672
-                'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
673
-                'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
674
-                'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
675
-                'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
676
-                'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
677
-            ],
678
-            'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                     => [
679
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
680
-            ],
681
-            'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                              => [
682
-                'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
683
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
684
-            ],
685
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                => [
686
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
687
-            ],
688
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                               => [
689
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
690
-            ],
691
-            'EE_CPT_Strategy'                                                                                             => [
692
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
693
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
694
-            ],
695
-            'EventEspresso\core\services\loaders\ObjectIdentifier'                                                        => [
696
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
697
-            ],
698
-            'EventEspresso\core\CPTs\CptQueryModifier'                                                                    => [
699
-                null,
700
-                null,
701
-                null,
702
-                'EE_Request_Handler'                          => EE_Dependency_Map::load_from_cache,
703
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
704
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
705
-            ],
706
-            'EventEspresso\core\services\dependencies\DependencyResolver'                                                 => [
707
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
708
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
709
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
710
-            ],
711
-            'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                               => [
712
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
713
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
714
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
715
-            ],
716
-            'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                          => [
717
-                'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
718
-                'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
719
-            ],
720
-            'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                          => [
721
-                'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
722
-                'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
723
-            ],
724
-            'EE_URL_Validation_Strategy'                                                                                  => [
725
-                null,
726
-                null,
727
-                'EventEspresso\core\services\validators\URLValidator' => EE_Dependency_Map::load_from_cache,
728
-            ],
729
-            'EventEspresso\core\services\request\files\FilesDataHandler'                                                  => [
730
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
731
-            ],
732
-            'EventEspressoBatchRequest\BatchRequestProcessor'                                                             => [
733
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
734
-            ],
735
-            'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                => [
736
-                'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
737
-                'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
738
-                'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
739
-                null,
740
-            ],
741
-            'EventEspresso\core\services\routing\RouteHandler'                                                            => [
742
-                'EventEspresso\core\services\json\JsonDataNodeHandler' => EE_Dependency_Map::load_from_cache,
743
-                'EventEspresso\core\services\loaders\Loader'           => EE_Dependency_Map::load_from_cache,
744
-                'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
745
-                'EventEspresso\core\services\routing\RouteCollection'  => EE_Dependency_Map::load_from_cache,
746
-            ],
747
-            'EventEspresso\core\services\json\JsonDataNodeHandler'                                                        => [
748
-                'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
749
-            ],
750
-            'EventEspresso\core\services\routing\Router'                                                                  => [
751
-                'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
752
-                'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
753
-                'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
754
-            ],
755
-            'EventEspresso\core\services\assets\AssetManifest'                                                            => [
756
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
757
-            ],
758
-            'EventEspresso\core\services\assets\AssetManifestFactory'                                                     => [
759
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
760
-            ],
761
-            'EventEspresso\core\services\assets\BaristaFactory'                                                           => [
762
-                'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
763
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
764
-            ],
765
-            'EventEspresso\core\domain\services\capabilities\FeatureFlags'                                                => [
766
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
767
-            ],
768
-            'EventEspresso\core\services\addon\AddonManager' => [
769
-                'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
770
-                'EventEspresso\core\Psr4Autoloader'                              => EE_Dependency_Map::load_from_cache,
771
-                'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
772
-                'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
773
-                'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
774
-            ],
775
-            'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler' => [
776
-                'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
777
-            ],
778
-            'EventEspressoBatchRequest\JobHandlers\ExecuteBatchDeletion' => [
779
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
780
-            ],
781
-            'EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion' => [
782
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
783
-            ],
784
-            'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion' => [
785
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
786
-                'EEM_Event' => EE_Dependency_Map::load_from_cache,
787
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
788
-                'EEM_Registration' => EE_Dependency_Map::load_from_cache
789
-            ],
790
-            'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion' => [
791
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
792
-            ],
793
-            'EventEspresso\core\domain\entities\users\CurrentUser' => [
794
-                'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
795
-            ],
796
-            'EventEspresso\core\services\form\meta\InputTypes' => [
797
-                'EventEspresso\core\services\form\meta\inputs\Button'   => EE_Dependency_Map::load_from_cache,
798
-                'EventEspresso\core\services\form\meta\inputs\DateTime' => EE_Dependency_Map::load_from_cache,
799
-                'EventEspresso\core\services\form\meta\inputs\Input'    => EE_Dependency_Map::load_from_cache,
800
-                'EventEspresso\core\services\form\meta\inputs\Number'   => EE_Dependency_Map::load_from_cache,
801
-                'EventEspresso\core\services\form\meta\inputs\Phone'    => EE_Dependency_Map::load_from_cache,
802
-                'EventEspresso\core\services\form\meta\inputs\Select'   => EE_Dependency_Map::load_from_cache,
803
-                'EventEspresso\core\services\form\meta\inputs\Text'     => EE_Dependency_Map::load_from_cache,
804
-            ],
805
-            'EventEspresso\core\domain\services\registration\form\v1\RegFormDependencyHandler' => [
806
-                'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
807
-            ],
808
-        ];
809
-    }
810
-
811
-
812
-    /**
813
-     * Registers how core classes are loaded.
814
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
815
-     *        'EE_Request_Handler' => 'load_core'
816
-     *        'EE_Messages_Queue'  => 'load_lib'
817
-     *        'EEH_Debug_Tools'    => 'load_helper'
818
-     * or, if greater control is required, by providing a custom closure. For example:
819
-     *        'Some_Class' => function () {
820
-     *            return new Some_Class();
821
-     *        },
822
-     * This is required for instantiating dependencies
823
-     * where an interface has been type hinted in a class constructor. For example:
824
-     *        'Required_Interface' => function () {
825
-     *            return new A_Class_That_Implements_Required_Interface();
826
-     *        },
827
-     */
828
-    protected function _register_core_class_loaders()
829
-    {
830
-        $this->_class_loaders = [
831
-            // load_core
832
-            'EE_Dependency_Map'                            => function () {
833
-                return $this;
834
-            },
835
-            'EE_Capabilities'                              => 'load_core',
836
-            'EE_Encryption'                                => 'load_core',
837
-            'EE_Front_Controller'                          => 'load_core',
838
-            'EE_Module_Request_Router'                     => 'load_core',
839
-            'EE_Registry'                                  => 'load_core',
840
-            'EE_Request'                                   => function () {
841
-                return $this->legacy_request;
842
-            },
843
-            'EventEspresso\core\services\request\Request'  => function () {
844
-                return $this->request;
845
-            },
846
-            'EventEspresso\core\services\request\Response' => function () {
847
-                return $this->response;
848
-            },
849
-            'EE_Base'                                      => 'load_core',
850
-            'EE_Request_Handler'                           => 'load_core',
851
-            'EE_Session'                                   => 'load_core',
852
-            'EE_Cron_Tasks'                                => 'load_core',
853
-            'EE_System'                                    => 'load_core',
854
-            'EE_Maintenance_Mode'                          => 'load_core',
855
-            'EE_Register_CPTs'                             => 'load_core',
856
-            'EE_Admin'                                     => 'load_core',
857
-            'EE_CPT_Strategy'                              => 'load_core',
858
-            // load_class
859
-            'EE_Registration_Processor'                    => 'load_class',
860
-            // load_lib
861
-            'EE_Message_Resource_Manager'                  => 'load_lib',
862
-            'EE_Message_Type_Collection'                   => 'load_lib',
863
-            'EE_Message_Type_Collection_Loader'            => 'load_lib',
864
-            'EE_Messenger_Collection'                      => 'load_lib',
865
-            'EE_Messenger_Collection_Loader'               => 'load_lib',
866
-            'EE_Messages_Processor'                        => 'load_lib',
867
-            'EE_Message_Repository'                        => 'load_lib',
868
-            'EE_Messages_Queue'                            => 'load_lib',
869
-            'EE_Messages_Data_Handler_Collection'          => 'load_lib',
870
-            'EE_Message_Template_Group_Collection'         => 'load_lib',
871
-            'EE_Payment_Method_Manager'                    => 'load_lib',
872
-            'EE_DMS_Core_4_1_0'                            => 'load_dms',
873
-            'EE_DMS_Core_4_2_0'                            => 'load_dms',
874
-            'EE_DMS_Core_4_3_0'                            => 'load_dms',
875
-            'EE_DMS_Core_4_5_0'                            => 'load_dms',
876
-            'EE_DMS_Core_4_6_0'                            => 'load_dms',
877
-            'EE_DMS_Core_4_7_0'                            => 'load_dms',
878
-            'EE_DMS_Core_4_8_0'                            => 'load_dms',
879
-            'EE_DMS_Core_4_9_0'                            => 'load_dms',
880
-            'EE_DMS_Core_4_10_0'                           => 'load_dms',
881
-            'EE_DMS_Core_4_11_0'                           => 'load_dms',
882
-            'EE_DMS_Core_4_12_0'                           => 'load_dms',
883
-            'EE_Messages_Generator'                        => static function () {
884
-                return EE_Registry::instance()->load_lib(
885
-                    'Messages_Generator',
886
-                    [],
887
-                    false,
888
-                    false
889
-                );
890
-            },
891
-            'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
892
-                return EE_Registry::instance()->load_lib(
893
-                    'Messages_Template_Defaults',
894
-                    $arguments,
895
-                    false,
896
-                    false
897
-                );
898
-            },
899
-            // load_helper
900
-            'EEH_Parse_Shortcodes'                         => static function () {
901
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
902
-                    return new EEH_Parse_Shortcodes();
903
-                }
904
-                return null;
905
-            },
906
-            'EE_Template_Config'                           => static function () {
907
-                return EE_Config::instance()->template_settings;
908
-            },
909
-            'EE_Currency_Config'                           => static function () {
910
-                return EE_Config::instance()->currency;
911
-            },
912
-            'EE_Registration_Config'                       => static function () {
913
-                return EE_Config::instance()->registration;
914
-            },
915
-            'EE_Core_Config'                               => static function () {
916
-                return EE_Config::instance()->core;
917
-            },
918
-            'EventEspresso\core\services\loaders\Loader'   => static function () {
919
-                return LoaderFactory::getLoader();
920
-            },
921
-            'EE_Network_Config'                            => static function () {
922
-                return EE_Network_Config::instance();
923
-            },
924
-            'EE_Config'                                    => static function () {
925
-                return EE_Config::instance();
926
-            },
927
-            'EventEspresso\core\domain\Domain'             => static function () {
928
-                return DomainFactory::getEventEspressoCoreDomain();
929
-            },
930
-            'EE_Admin_Config'                              => static function () {
931
-                return EE_Config::instance()->admin;
932
-            },
933
-            'EE_Organization_Config'                       => static function () {
934
-                return EE_Config::instance()->organization;
935
-            },
936
-            'EE_Network_Core_Config'                       => static function () {
937
-                return EE_Network_Config::instance()->core;
938
-            },
939
-            'EE_Environment_Config'                        => static function () {
940
-                return EE_Config::instance()->environment;
941
-            },
942
-            'EED_Core_Rest_Api'                            => static function () {
943
-                return EED_Core_Rest_Api::instance();
944
-            },
945
-            'WP_REST_Server'                               => static function () {
946
-                return rest_get_server();
947
-            },
948
-            'EventEspresso\core\Psr4Autoloader'            => static function () {
949
-                return EE_Psr4AutoloaderInit::psr4_loader();
950
-            },
951
-        ];
952
-    }
953
-
954
-
955
-    /**
956
-     * can be used for supplying alternate names for classes,
957
-     * or for connecting interface names to instantiable classes
958
-     *
959
-     * @throws InvalidAliasException
960
-     */
961
-    protected function _register_core_aliases()
962
-    {
963
-        $aliases = [
964
-            'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
965
-            'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
966
-            'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
967
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
968
-            'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
969
-            'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
970
-            'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
971
-            'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
972
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
973
-            'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
974
-            'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
975
-            'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
976
-            'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
977
-            'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
978
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
979
-            'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
980
-            'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
981
-            'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
982
-            'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
983
-            'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
984
-            'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
985
-            'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
986
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
987
-            'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
988
-            'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
989
-            'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
990
-            'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
991
-            'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
992
-            'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
993
-            'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
994
-            'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
995
-            'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
996
-            'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
997
-            'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
998
-            'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
999
-            'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
1000
-            'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
1001
-            'Registration_Processor'                                                       => 'EE_Registration_Processor',
1002
-            'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
1003
-        ];
1004
-        foreach ($aliases as $alias => $fqn) {
1005
-            if (is_array($fqn)) {
1006
-                foreach ($fqn as $class => $for_class) {
1007
-                    $this->class_cache->addAlias($class, $alias, $for_class);
1008
-                }
1009
-                continue;
1010
-            }
1011
-            $this->class_cache->addAlias($fqn, $alias);
1012
-        }
1013
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1014
-            $this->class_cache->addAlias(
1015
-                'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1016
-                'EventEspresso\core\services\notices\NoticeConverterInterface'
1017
-            );
1018
-        }
1019
-    }
1020
-
1021
-
1022
-    /**
1023
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
1024
-     * request Primarily used by unit tests.
1025
-     */
1026
-    public function reset()
1027
-    {
1028
-        $this->_register_core_class_loaders();
1029
-        $this->_register_core_dependencies();
1030
-    }
1031
-
1032
-
1033
-    /**
1034
-     * PLZ NOTE: a better name for this method would be is_alias()
1035
-     * because it returns TRUE if the provided fully qualified name IS an alias
1036
-     * WHY?
1037
-     * Because if a class is type hinting for a concretion,
1038
-     * then why would we need to find another class to supply it?
1039
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1040
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1041
-     * Don't go looking for some substitute.
1042
-     * Whereas if a class is type hinting for an interface...
1043
-     * then we need to find an actual class to use.
1044
-     * So the interface IS the alias for some other FQN,
1045
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1046
-     * represents some other class.
1047
-     *
1048
-     * @param string $fqn
1049
-     * @param string $for_class
1050
-     * @return bool
1051
-     * @deprecated 4.9.62.p
1052
-     */
1053
-    public function has_alias($fqn = '', $for_class = '')
1054
-    {
1055
-        return $this->isAlias($fqn, $for_class);
1056
-    }
1057
-
1058
-
1059
-    /**
1060
-     * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1061
-     * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1062
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
1063
-     *  for example:
1064
-     *      if the following two entries were added to the _aliases array:
1065
-     *          array(
1066
-     *              'interface_alias'           => 'some\namespace\interface'
1067
-     *              'some\namespace\interface'  => 'some\namespace\classname'
1068
-     *          )
1069
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1070
-     *      to load an instance of 'some\namespace\classname'
1071
-     *
1072
-     * @param string $alias
1073
-     * @param string $for_class
1074
-     * @return string
1075
-     * @deprecated 4.9.62.p
1076
-     */
1077
-    public function get_alias($alias = '', $for_class = '')
1078
-    {
1079
-        return $this->getFqnForAlias($alias, $for_class);
1080
-    }
25
+	/**
26
+	 * This means that the requested class dependency is not present in the dependency map
27
+	 */
28
+	const not_registered = 0;
29
+
30
+	/**
31
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
32
+	 */
33
+	const load_new_object = 1;
34
+
35
+	/**
36
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
37
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
38
+	 */
39
+	const load_from_cache = 2;
40
+
41
+	/**
42
+	 * When registering a dependency,
43
+	 * this indicates to keep any existing dependencies that already exist,
44
+	 * and simply discard any new dependencies declared in the incoming data
45
+	 */
46
+	const KEEP_EXISTING_DEPENDENCIES = 0;
47
+
48
+	/**
49
+	 * When registering a dependency,
50
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
51
+	 */
52
+	const OVERWRITE_DEPENDENCIES = 1;
53
+
54
+	/**
55
+	 * @type EE_Dependency_Map $_instance
56
+	 */
57
+	protected static $_instance;
58
+
59
+	/**
60
+	 * @var ClassInterfaceCache $class_cache
61
+	 */
62
+	private $class_cache;
63
+
64
+	/**
65
+	 * @type RequestInterface $request
66
+	 */
67
+	protected $request;
68
+
69
+	/**
70
+	 * @type LegacyRequestInterface $legacy_request
71
+	 */
72
+	protected $legacy_request;
73
+
74
+	/**
75
+	 * @type ResponseInterface $response
76
+	 */
77
+	protected $response;
78
+
79
+	/**
80
+	 * @type LoaderInterface $loader
81
+	 */
82
+	protected $loader;
83
+
84
+	/**
85
+	 * @type array $_dependency_map
86
+	 */
87
+	protected $_dependency_map = [];
88
+
89
+	/**
90
+	 * @type array $_class_loaders
91
+	 */
92
+	protected $_class_loaders = [];
93
+
94
+
95
+	/**
96
+	 * EE_Dependency_Map constructor.
97
+	 *
98
+	 * @param ClassInterfaceCache $class_cache
99
+	 */
100
+	protected function __construct(ClassInterfaceCache $class_cache)
101
+	{
102
+		$this->class_cache = $class_cache;
103
+		do_action('EE_Dependency_Map____construct', $this);
104
+	}
105
+
106
+
107
+	/**
108
+	 * @return void
109
+	 * @throws InvalidAliasException
110
+	 */
111
+	public function initialize()
112
+	{
113
+		$this->_register_core_dependencies();
114
+		$this->_register_core_class_loaders();
115
+		$this->_register_core_aliases();
116
+	}
117
+
118
+
119
+	/**
120
+	 * @singleton method used to instantiate class object
121
+	 * @param ClassInterfaceCache|null $class_cache
122
+	 * @return EE_Dependency_Map
123
+	 */
124
+	public static function instance(ClassInterfaceCache $class_cache = null)
125
+	{
126
+		// check if class object is instantiated, and instantiated properly
127
+		if (
128
+			! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
129
+			&& $class_cache instanceof ClassInterfaceCache
130
+		) {
131
+			EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
132
+		}
133
+		return EE_Dependency_Map::$_instance;
134
+	}
135
+
136
+
137
+	/**
138
+	 * @param RequestInterface $request
139
+	 */
140
+	public function setRequest(RequestInterface $request)
141
+	{
142
+		$this->request = $request;
143
+	}
144
+
145
+
146
+	/**
147
+	 * @param LegacyRequestInterface $legacy_request
148
+	 */
149
+	public function setLegacyRequest(LegacyRequestInterface $legacy_request)
150
+	{
151
+		$this->legacy_request = $legacy_request;
152
+	}
153
+
154
+
155
+	/**
156
+	 * @param ResponseInterface $response
157
+	 */
158
+	public function setResponse(ResponseInterface $response)
159
+	{
160
+		$this->response = $response;
161
+	}
162
+
163
+
164
+	/**
165
+	 * @param LoaderInterface $loader
166
+	 */
167
+	public function setLoader(LoaderInterface $loader)
168
+	{
169
+		$this->loader = $loader;
170
+	}
171
+
172
+
173
+	/**
174
+	 * @param string $class
175
+	 * @param array  $dependencies
176
+	 * @param int    $overwrite
177
+	 * @return bool
178
+	 */
179
+	public static function register_dependencies(
180
+		$class,
181
+		array $dependencies,
182
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
183
+	) {
184
+		return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
185
+	}
186
+
187
+
188
+	/**
189
+	 * Assigns an array of class names and corresponding load sources (new or cached)
190
+	 * to the class specified by the first parameter.
191
+	 * IMPORTANT !!!
192
+	 * The order of elements in the incoming $dependencies array MUST match
193
+	 * the order of the constructor parameters for the class in question.
194
+	 * This is especially important when overriding any existing dependencies that are registered.
195
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
196
+	 *
197
+	 * @param string $class
198
+	 * @param array  $dependencies
199
+	 * @param int    $overwrite
200
+	 * @return bool
201
+	 */
202
+	public function registerDependencies(
203
+		$class,
204
+		array $dependencies,
205
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
206
+	) {
207
+		$class      = trim($class, '\\');
208
+		$registered = false;
209
+		if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
210
+			EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
211
+		}
212
+		// we need to make sure that any aliases used when registering a dependency
213
+		// get resolved to the correct class name
214
+		foreach ($dependencies as $dependency => $load_source) {
215
+			$alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
216
+			if (
217
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
218
+				|| ! isset(EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ])
219
+			) {
220
+				unset($dependencies[ $dependency ]);
221
+				$dependencies[ $alias ] = $load_source;
222
+				$registered             = true;
223
+			}
224
+		}
225
+		// now add our two lists of dependencies together.
226
+		// using Union (+=) favours the arrays in precedence from left to right,
227
+		// so $dependencies is NOT overwritten because it is listed first
228
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
229
+		// Union is way faster than array_merge() but should be used with caution...
230
+		// especially with numerically indexed arrays
231
+		$dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
232
+		// now we need to ensure that the resulting dependencies
233
+		// array only has the entries that are required for the class
234
+		// so first count how many dependencies were originally registered for the class
235
+		$dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
236
+		// if that count is non-zero (meaning dependencies were already registered)
237
+		EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
238
+			// then truncate the  final array to match that count
239
+			? array_slice($dependencies, 0, $dependency_count)
240
+			// otherwise just take the incoming array because nothing previously existed
241
+			: $dependencies;
242
+		return $registered;
243
+	}
244
+
245
+
246
+	/**
247
+	 * @param string $class_name
248
+	 * @param string $loader
249
+	 * @return bool
250
+	 * @throws DomainException
251
+	 */
252
+	public static function register_class_loader($class_name, $loader = 'load_core')
253
+	{
254
+		return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader);
255
+	}
256
+
257
+
258
+	/**
259
+	 * @param string $class_name
260
+	 * @param string $loader
261
+	 * @return bool
262
+	 * @throws DomainException
263
+	 */
264
+	public function registerClassLoader($class_name, $loader = 'load_core')
265
+	{
266
+		if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
267
+			throw new DomainException(
268
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
269
+			);
270
+		}
271
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
272
+		if (
273
+			! is_callable($loader)
274
+			&& (
275
+				strpos($loader, 'load_') !== 0
276
+				|| ! method_exists('EE_Registry', $loader)
277
+			)
278
+		) {
279
+			throw new DomainException(
280
+				sprintf(
281
+					esc_html__(
282
+						'"%1$s" is not a valid loader method on EE_Registry.',
283
+						'event_espresso'
284
+					),
285
+					$loader
286
+				)
287
+			);
288
+		}
289
+		$class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
290
+		if (! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
291
+			EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
292
+			return true;
293
+		}
294
+		return false;
295
+	}
296
+
297
+
298
+	/**
299
+	 * @return array
300
+	 */
301
+	public function dependency_map()
302
+	{
303
+		return $this->_dependency_map;
304
+	}
305
+
306
+
307
+	/**
308
+	 * returns TRUE if dependency map contains a listing for the provided class name
309
+	 *
310
+	 * @param string $class_name
311
+	 * @return boolean
312
+	 */
313
+	public function has($class_name = '')
314
+	{
315
+		// all legacy models have the same dependencies
316
+		if (strpos($class_name, 'EEM_') === 0) {
317
+			$class_name = 'LEGACY_MODELS';
318
+		}
319
+		return isset($this->_dependency_map[ $class_name ]);
320
+	}
321
+
322
+
323
+	/**
324
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
325
+	 *
326
+	 * @param string $class_name
327
+	 * @param string $dependency
328
+	 * @return bool
329
+	 */
330
+	public function has_dependency_for_class($class_name = '', $dependency = '')
331
+	{
332
+		// all legacy models have the same dependencies
333
+		if (strpos($class_name, 'EEM_') === 0) {
334
+			$class_name = 'LEGACY_MODELS';
335
+		}
336
+		$dependency = $this->getFqnForAlias($dependency, $class_name);
337
+		return isset($this->_dependency_map[ $class_name ][ $dependency ]);
338
+	}
339
+
340
+
341
+	/**
342
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
343
+	 *
344
+	 * @param string $class_name
345
+	 * @param string $dependency
346
+	 * @return int
347
+	 */
348
+	public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
349
+	{
350
+		// all legacy models have the same dependencies
351
+		if (strpos($class_name, 'EEM_') === 0) {
352
+			$class_name = 'LEGACY_MODELS';
353
+		}
354
+		$dependency = $this->getFqnForAlias($dependency);
355
+		return $this->has_dependency_for_class($class_name, $dependency)
356
+			? $this->_dependency_map[ $class_name ][ $dependency ]
357
+			: EE_Dependency_Map::not_registered;
358
+	}
359
+
360
+
361
+	/**
362
+	 * @param string $class_name
363
+	 * @return string | Closure
364
+	 */
365
+	public function class_loader($class_name)
366
+	{
367
+		// all legacy models use load_model()
368
+		if (strpos($class_name, 'EEM_') === 0) {
369
+			return 'load_model';
370
+		}
371
+		// EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
372
+		// perform strpos() first to avoid loading regex every time we load a class
373
+		if (
374
+			strpos($class_name, 'EE_CPT_') === 0
375
+			&& preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
376
+		) {
377
+			return 'load_core';
378
+		}
379
+		$class_name = $this->getFqnForAlias($class_name);
380
+		return isset($this->_class_loaders[ $class_name ]) ? $this->_class_loaders[ $class_name ] : '';
381
+	}
382
+
383
+
384
+	/**
385
+	 * @return array
386
+	 */
387
+	public function class_loaders()
388
+	{
389
+		return $this->_class_loaders;
390
+	}
391
+
392
+
393
+	/**
394
+	 * adds an alias for a classname
395
+	 *
396
+	 * @param string $fqcn      the class name that should be used (concrete class to replace interface)
397
+	 * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
398
+	 * @param string $for_class the class that has the dependency (is type hinting for the interface)
399
+	 * @throws InvalidAliasException
400
+	 */
401
+	public function add_alias($fqcn, $alias, $for_class = '')
402
+	{
403
+		$this->class_cache->addAlias($fqcn, $alias, $for_class);
404
+	}
405
+
406
+
407
+	/**
408
+	 * Returns TRUE if the provided fully qualified name IS an alias
409
+	 * WHY?
410
+	 * Because if a class is type hinting for a concretion,
411
+	 * then why would we need to find another class to supply it?
412
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
413
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
414
+	 * Don't go looking for some substitute.
415
+	 * Whereas if a class is type hinting for an interface...
416
+	 * then we need to find an actual class to use.
417
+	 * So the interface IS the alias for some other FQN,
418
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
419
+	 * represents some other class.
420
+	 *
421
+	 * @param string $fqn
422
+	 * @param string $for_class
423
+	 * @return bool
424
+	 */
425
+	public function isAlias($fqn = '', $for_class = '')
426
+	{
427
+		return $this->class_cache->isAlias($fqn, $for_class);
428
+	}
429
+
430
+
431
+	/**
432
+	 * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
433
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
434
+	 *  for example:
435
+	 *      if the following two entries were added to the _aliases array:
436
+	 *          array(
437
+	 *              'interface_alias'           => 'some\namespace\interface'
438
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
439
+	 *          )
440
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
441
+	 *      to load an instance of 'some\namespace\classname'
442
+	 *
443
+	 * @param string $alias
444
+	 * @param string $for_class
445
+	 * @return string
446
+	 */
447
+	public function getFqnForAlias($alias = '', $for_class = '')
448
+	{
449
+		return (string) $this->class_cache->getFqnForAlias($alias, $for_class);
450
+	}
451
+
452
+
453
+	/**
454
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
455
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
456
+	 * This is done by using the following class constants:
457
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
458
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
459
+	 */
460
+	protected function _register_core_dependencies()
461
+	{
462
+		$this->_dependency_map = [
463
+			'EE_Request_Handler'                                                                                          => [
464
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
465
+			],
466
+			'EE_System'                                                                                                   => [
467
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
468
+				'EE_Maintenance_Mode'                         => EE_Dependency_Map::load_from_cache,
469
+				'EE_Registry'                                 => EE_Dependency_Map::load_from_cache,
470
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
471
+				'EventEspresso\core\services\routing\Router'  => EE_Dependency_Map::load_from_cache,
472
+			],
473
+			'EE_Admin'                                                                                                    => [
474
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
475
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
476
+			],
477
+			'EE_Cart'                                                                                                     => [
478
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
479
+			],
480
+			'EE_Messenger_Collection_Loader'                                                                              => [
481
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
482
+			],
483
+			'EE_Message_Type_Collection_Loader'                                                                           => [
484
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
485
+			],
486
+			'EE_Message_Resource_Manager'                                                                                 => [
487
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
488
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
489
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
490
+			],
491
+			'EE_Message_Factory'                                                                                          => [
492
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
493
+			],
494
+			'EE_messages'                                                                                                 => [
495
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
496
+			],
497
+			'EE_Messages_Generator'                                                                                       => [
498
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
499
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
500
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
501
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
502
+			],
503
+			'EE_Messages_Processor'                                                                                       => [
504
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
505
+			],
506
+			'EE_Messages_Queue'                                                                                           => [
507
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
508
+			],
509
+			'EE_Messages_Template_Defaults'                                                                               => [
510
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
511
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
512
+			],
513
+			'EE_Message_To_Generate_From_Request'                                                                         => [
514
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
515
+				'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
516
+			],
517
+			'EventEspresso\core\services\commands\CommandBus'                                                             => [
518
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
519
+			],
520
+			'EventEspresso\services\commands\CommandHandler'                                                              => [
521
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
522
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
523
+			],
524
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => [
525
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
526
+			],
527
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => [
528
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
529
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
530
+			],
531
+			'EventEspresso\core\services\commands\CommandFactory'                                                         => [
532
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
533
+			],
534
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => [
535
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
536
+			],
537
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => [
538
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
539
+			],
540
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => [
541
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
542
+			],
543
+			'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => [
544
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
545
+			],
546
+			'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
547
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
548
+			],
549
+			'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
550
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
551
+			],
552
+			'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
553
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
554
+			],
555
+			'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
556
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
557
+			],
558
+			'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
559
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
560
+			],
561
+			'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
562
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
563
+			],
564
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => [
565
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
566
+			],
567
+			'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
568
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
569
+			],
570
+			'EventEspresso\core\services\database\TableManager'                                                           => [
571
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
572
+			],
573
+			'EE_Data_Migration_Class_Base'                                                                                => [
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
+			'EE_DMS_Core_4_1_0'                                                                                           => [
578
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
579
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
580
+			],
581
+			'EE_DMS_Core_4_2_0'                                                                                           => [
582
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
583
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
584
+			],
585
+			'EE_DMS_Core_4_3_0'                                                                                           => [
586
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
587
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
588
+			],
589
+			'EE_DMS_Core_4_4_0'                                                                                           => [
590
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
591
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
592
+			],
593
+			'EE_DMS_Core_4_5_0'                                                                                           => [
594
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
595
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
596
+			],
597
+			'EE_DMS_Core_4_6_0'                                                                                           => [
598
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
599
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
600
+			],
601
+			'EE_DMS_Core_4_7_0'                                                                                           => [
602
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
603
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
604
+			],
605
+			'EE_DMS_Core_4_8_0'                                                                                           => [
606
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
607
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
608
+			],
609
+			'EE_DMS_Core_4_9_0'                                                                                           => [
610
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
611
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
612
+			],
613
+			'EE_DMS_Core_4_10_0'                                                                                          => [
614
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
615
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
616
+				'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
617
+			],
618
+			'EE_DMS_Core_4_11_0'                                                                                          => [
619
+				'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
620
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
621
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
622
+			],
623
+			'EE_DMS_Core_4_12_0' => [
624
+				'EE_DMS_Core_4_11_0'                                 => EE_Dependency_Map::load_from_cache,
625
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
626
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
627
+			],
628
+			'EventEspresso\core\services\assets\Registry'                                                                 => [
629
+				'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_new_object,
630
+				'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
631
+			],
632
+			'EventEspresso\core\services\cache\BasicCacheManager'                                                         => [
633
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
634
+			],
635
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => [
636
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
637
+			],
638
+			'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                  => [
639
+				'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
640
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
641
+			],
642
+			'EventEspresso\core\domain\values\EmailAddress'                                                               => [
643
+				null,
644
+				'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
645
+			],
646
+			'EventEspresso\core\services\orm\ModelFieldFactory'                                                           => [
647
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
648
+			],
649
+			'LEGACY_MODELS'                                                                                               => [
650
+				null,
651
+				'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
652
+			],
653
+			'EE_Module_Request_Router'                                                                                    => [
654
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
655
+			],
656
+			'EE_Registration_Processor'                                                                                   => [
657
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
658
+			],
659
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                      => [
660
+				null,
661
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
662
+				'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
663
+			],
664
+			'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                    => [
665
+				'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
666
+				'EE_Session'             => EE_Dependency_Map::load_from_cache,
667
+			],
668
+			'EventEspresso\modules\ticket_selector\DisplayTicketSelector'                                                 => [
669
+				'EventEspresso\core\domain\entities\users\CurrentUser' => EE_Dependency_Map::load_from_cache,
670
+			],
671
+			'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                 => [
672
+				'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
673
+				'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
674
+				'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
675
+				'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
676
+				'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
677
+			],
678
+			'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                     => [
679
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
680
+			],
681
+			'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                              => [
682
+				'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
683
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
684
+			],
685
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                => [
686
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
687
+			],
688
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                               => [
689
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
690
+			],
691
+			'EE_CPT_Strategy'                                                                                             => [
692
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
693
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
694
+			],
695
+			'EventEspresso\core\services\loaders\ObjectIdentifier'                                                        => [
696
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
697
+			],
698
+			'EventEspresso\core\CPTs\CptQueryModifier'                                                                    => [
699
+				null,
700
+				null,
701
+				null,
702
+				'EE_Request_Handler'                          => EE_Dependency_Map::load_from_cache,
703
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
704
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
705
+			],
706
+			'EventEspresso\core\services\dependencies\DependencyResolver'                                                 => [
707
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
708
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
709
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
710
+			],
711
+			'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                               => [
712
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
713
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
714
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
715
+			],
716
+			'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                          => [
717
+				'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
718
+				'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
719
+			],
720
+			'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                          => [
721
+				'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
722
+				'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
723
+			],
724
+			'EE_URL_Validation_Strategy'                                                                                  => [
725
+				null,
726
+				null,
727
+				'EventEspresso\core\services\validators\URLValidator' => EE_Dependency_Map::load_from_cache,
728
+			],
729
+			'EventEspresso\core\services\request\files\FilesDataHandler'                                                  => [
730
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
731
+			],
732
+			'EventEspressoBatchRequest\BatchRequestProcessor'                                                             => [
733
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
734
+			],
735
+			'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                => [
736
+				'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
737
+				'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
738
+				'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
739
+				null,
740
+			],
741
+			'EventEspresso\core\services\routing\RouteHandler'                                                            => [
742
+				'EventEspresso\core\services\json\JsonDataNodeHandler' => EE_Dependency_Map::load_from_cache,
743
+				'EventEspresso\core\services\loaders\Loader'           => EE_Dependency_Map::load_from_cache,
744
+				'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
745
+				'EventEspresso\core\services\routing\RouteCollection'  => EE_Dependency_Map::load_from_cache,
746
+			],
747
+			'EventEspresso\core\services\json\JsonDataNodeHandler'                                                        => [
748
+				'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
749
+			],
750
+			'EventEspresso\core\services\routing\Router'                                                                  => [
751
+				'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
752
+				'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
753
+				'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
754
+			],
755
+			'EventEspresso\core\services\assets\AssetManifest'                                                            => [
756
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
757
+			],
758
+			'EventEspresso\core\services\assets\AssetManifestFactory'                                                     => [
759
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
760
+			],
761
+			'EventEspresso\core\services\assets\BaristaFactory'                                                           => [
762
+				'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
763
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
764
+			],
765
+			'EventEspresso\core\domain\services\capabilities\FeatureFlags'                                                => [
766
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
767
+			],
768
+			'EventEspresso\core\services\addon\AddonManager' => [
769
+				'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
770
+				'EventEspresso\core\Psr4Autoloader'                              => EE_Dependency_Map::load_from_cache,
771
+				'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
772
+				'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
773
+				'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
774
+			],
775
+			'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler' => [
776
+				'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
777
+			],
778
+			'EventEspressoBatchRequest\JobHandlers\ExecuteBatchDeletion' => [
779
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
780
+			],
781
+			'EventEspressoBatchRequest\JobHandlers\PreviewEventDeletion' => [
782
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache
783
+			],
784
+			'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion' => [
785
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
786
+				'EEM_Event' => EE_Dependency_Map::load_from_cache,
787
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
788
+				'EEM_Registration' => EE_Dependency_Map::load_from_cache
789
+			],
790
+			'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion' => [
791
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
792
+			],
793
+			'EventEspresso\core\domain\entities\users\CurrentUser' => [
794
+				'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
795
+			],
796
+			'EventEspresso\core\services\form\meta\InputTypes' => [
797
+				'EventEspresso\core\services\form\meta\inputs\Button'   => EE_Dependency_Map::load_from_cache,
798
+				'EventEspresso\core\services\form\meta\inputs\DateTime' => EE_Dependency_Map::load_from_cache,
799
+				'EventEspresso\core\services\form\meta\inputs\Input'    => EE_Dependency_Map::load_from_cache,
800
+				'EventEspresso\core\services\form\meta\inputs\Number'   => EE_Dependency_Map::load_from_cache,
801
+				'EventEspresso\core\services\form\meta\inputs\Phone'    => EE_Dependency_Map::load_from_cache,
802
+				'EventEspresso\core\services\form\meta\inputs\Select'   => EE_Dependency_Map::load_from_cache,
803
+				'EventEspresso\core\services\form\meta\inputs\Text'     => EE_Dependency_Map::load_from_cache,
804
+			],
805
+			'EventEspresso\core\domain\services\registration\form\v1\RegFormDependencyHandler' => [
806
+				'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
807
+			],
808
+		];
809
+	}
810
+
811
+
812
+	/**
813
+	 * Registers how core classes are loaded.
814
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
815
+	 *        'EE_Request_Handler' => 'load_core'
816
+	 *        'EE_Messages_Queue'  => 'load_lib'
817
+	 *        'EEH_Debug_Tools'    => 'load_helper'
818
+	 * or, if greater control is required, by providing a custom closure. For example:
819
+	 *        'Some_Class' => function () {
820
+	 *            return new Some_Class();
821
+	 *        },
822
+	 * This is required for instantiating dependencies
823
+	 * where an interface has been type hinted in a class constructor. For example:
824
+	 *        'Required_Interface' => function () {
825
+	 *            return new A_Class_That_Implements_Required_Interface();
826
+	 *        },
827
+	 */
828
+	protected function _register_core_class_loaders()
829
+	{
830
+		$this->_class_loaders = [
831
+			// load_core
832
+			'EE_Dependency_Map'                            => function () {
833
+				return $this;
834
+			},
835
+			'EE_Capabilities'                              => 'load_core',
836
+			'EE_Encryption'                                => 'load_core',
837
+			'EE_Front_Controller'                          => 'load_core',
838
+			'EE_Module_Request_Router'                     => 'load_core',
839
+			'EE_Registry'                                  => 'load_core',
840
+			'EE_Request'                                   => function () {
841
+				return $this->legacy_request;
842
+			},
843
+			'EventEspresso\core\services\request\Request'  => function () {
844
+				return $this->request;
845
+			},
846
+			'EventEspresso\core\services\request\Response' => function () {
847
+				return $this->response;
848
+			},
849
+			'EE_Base'                                      => 'load_core',
850
+			'EE_Request_Handler'                           => 'load_core',
851
+			'EE_Session'                                   => 'load_core',
852
+			'EE_Cron_Tasks'                                => 'load_core',
853
+			'EE_System'                                    => 'load_core',
854
+			'EE_Maintenance_Mode'                          => 'load_core',
855
+			'EE_Register_CPTs'                             => 'load_core',
856
+			'EE_Admin'                                     => 'load_core',
857
+			'EE_CPT_Strategy'                              => 'load_core',
858
+			// load_class
859
+			'EE_Registration_Processor'                    => 'load_class',
860
+			// load_lib
861
+			'EE_Message_Resource_Manager'                  => 'load_lib',
862
+			'EE_Message_Type_Collection'                   => 'load_lib',
863
+			'EE_Message_Type_Collection_Loader'            => 'load_lib',
864
+			'EE_Messenger_Collection'                      => 'load_lib',
865
+			'EE_Messenger_Collection_Loader'               => 'load_lib',
866
+			'EE_Messages_Processor'                        => 'load_lib',
867
+			'EE_Message_Repository'                        => 'load_lib',
868
+			'EE_Messages_Queue'                            => 'load_lib',
869
+			'EE_Messages_Data_Handler_Collection'          => 'load_lib',
870
+			'EE_Message_Template_Group_Collection'         => 'load_lib',
871
+			'EE_Payment_Method_Manager'                    => 'load_lib',
872
+			'EE_DMS_Core_4_1_0'                            => 'load_dms',
873
+			'EE_DMS_Core_4_2_0'                            => 'load_dms',
874
+			'EE_DMS_Core_4_3_0'                            => 'load_dms',
875
+			'EE_DMS_Core_4_5_0'                            => 'load_dms',
876
+			'EE_DMS_Core_4_6_0'                            => 'load_dms',
877
+			'EE_DMS_Core_4_7_0'                            => 'load_dms',
878
+			'EE_DMS_Core_4_8_0'                            => 'load_dms',
879
+			'EE_DMS_Core_4_9_0'                            => 'load_dms',
880
+			'EE_DMS_Core_4_10_0'                           => 'load_dms',
881
+			'EE_DMS_Core_4_11_0'                           => 'load_dms',
882
+			'EE_DMS_Core_4_12_0'                           => 'load_dms',
883
+			'EE_Messages_Generator'                        => static function () {
884
+				return EE_Registry::instance()->load_lib(
885
+					'Messages_Generator',
886
+					[],
887
+					false,
888
+					false
889
+				);
890
+			},
891
+			'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
892
+				return EE_Registry::instance()->load_lib(
893
+					'Messages_Template_Defaults',
894
+					$arguments,
895
+					false,
896
+					false
897
+				);
898
+			},
899
+			// load_helper
900
+			'EEH_Parse_Shortcodes'                         => static function () {
901
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
902
+					return new EEH_Parse_Shortcodes();
903
+				}
904
+				return null;
905
+			},
906
+			'EE_Template_Config'                           => static function () {
907
+				return EE_Config::instance()->template_settings;
908
+			},
909
+			'EE_Currency_Config'                           => static function () {
910
+				return EE_Config::instance()->currency;
911
+			},
912
+			'EE_Registration_Config'                       => static function () {
913
+				return EE_Config::instance()->registration;
914
+			},
915
+			'EE_Core_Config'                               => static function () {
916
+				return EE_Config::instance()->core;
917
+			},
918
+			'EventEspresso\core\services\loaders\Loader'   => static function () {
919
+				return LoaderFactory::getLoader();
920
+			},
921
+			'EE_Network_Config'                            => static function () {
922
+				return EE_Network_Config::instance();
923
+			},
924
+			'EE_Config'                                    => static function () {
925
+				return EE_Config::instance();
926
+			},
927
+			'EventEspresso\core\domain\Domain'             => static function () {
928
+				return DomainFactory::getEventEspressoCoreDomain();
929
+			},
930
+			'EE_Admin_Config'                              => static function () {
931
+				return EE_Config::instance()->admin;
932
+			},
933
+			'EE_Organization_Config'                       => static function () {
934
+				return EE_Config::instance()->organization;
935
+			},
936
+			'EE_Network_Core_Config'                       => static function () {
937
+				return EE_Network_Config::instance()->core;
938
+			},
939
+			'EE_Environment_Config'                        => static function () {
940
+				return EE_Config::instance()->environment;
941
+			},
942
+			'EED_Core_Rest_Api'                            => static function () {
943
+				return EED_Core_Rest_Api::instance();
944
+			},
945
+			'WP_REST_Server'                               => static function () {
946
+				return rest_get_server();
947
+			},
948
+			'EventEspresso\core\Psr4Autoloader'            => static function () {
949
+				return EE_Psr4AutoloaderInit::psr4_loader();
950
+			},
951
+		];
952
+	}
953
+
954
+
955
+	/**
956
+	 * can be used for supplying alternate names for classes,
957
+	 * or for connecting interface names to instantiable classes
958
+	 *
959
+	 * @throws InvalidAliasException
960
+	 */
961
+	protected function _register_core_aliases()
962
+	{
963
+		$aliases = [
964
+			'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
965
+			'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
966
+			'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
967
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
968
+			'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
969
+			'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
970
+			'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
971
+			'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
972
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
973
+			'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
974
+			'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
975
+			'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
976
+			'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
977
+			'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
978
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
979
+			'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
980
+			'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
981
+			'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
982
+			'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
983
+			'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
984
+			'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
985
+			'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
986
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
987
+			'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
988
+			'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
989
+			'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
990
+			'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
991
+			'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
992
+			'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
993
+			'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
994
+			'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
995
+			'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
996
+			'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
997
+			'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
998
+			'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
999
+			'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
1000
+			'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
1001
+			'Registration_Processor'                                                       => 'EE_Registration_Processor',
1002
+			'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
1003
+		];
1004
+		foreach ($aliases as $alias => $fqn) {
1005
+			if (is_array($fqn)) {
1006
+				foreach ($fqn as $class => $for_class) {
1007
+					$this->class_cache->addAlias($class, $alias, $for_class);
1008
+				}
1009
+				continue;
1010
+			}
1011
+			$this->class_cache->addAlias($fqn, $alias);
1012
+		}
1013
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1014
+			$this->class_cache->addAlias(
1015
+				'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1016
+				'EventEspresso\core\services\notices\NoticeConverterInterface'
1017
+			);
1018
+		}
1019
+	}
1020
+
1021
+
1022
+	/**
1023
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
1024
+	 * request Primarily used by unit tests.
1025
+	 */
1026
+	public function reset()
1027
+	{
1028
+		$this->_register_core_class_loaders();
1029
+		$this->_register_core_dependencies();
1030
+	}
1031
+
1032
+
1033
+	/**
1034
+	 * PLZ NOTE: a better name for this method would be is_alias()
1035
+	 * because it returns TRUE if the provided fully qualified name IS an alias
1036
+	 * WHY?
1037
+	 * Because if a class is type hinting for a concretion,
1038
+	 * then why would we need to find another class to supply it?
1039
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1040
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1041
+	 * Don't go looking for some substitute.
1042
+	 * Whereas if a class is type hinting for an interface...
1043
+	 * then we need to find an actual class to use.
1044
+	 * So the interface IS the alias for some other FQN,
1045
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1046
+	 * represents some other class.
1047
+	 *
1048
+	 * @param string $fqn
1049
+	 * @param string $for_class
1050
+	 * @return bool
1051
+	 * @deprecated 4.9.62.p
1052
+	 */
1053
+	public function has_alias($fqn = '', $for_class = '')
1054
+	{
1055
+		return $this->isAlias($fqn, $for_class);
1056
+	}
1057
+
1058
+
1059
+	/**
1060
+	 * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1061
+	 * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1062
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
1063
+	 *  for example:
1064
+	 *      if the following two entries were added to the _aliases array:
1065
+	 *          array(
1066
+	 *              'interface_alias'           => 'some\namespace\interface'
1067
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
1068
+	 *          )
1069
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1070
+	 *      to load an instance of 'some\namespace\classname'
1071
+	 *
1072
+	 * @param string $alias
1073
+	 * @param string $for_class
1074
+	 * @return string
1075
+	 * @deprecated 4.9.62.p
1076
+	 */
1077
+	public function get_alias($alias = '', $for_class = '')
1078
+	{
1079
+		return $this->getFqnForAlias($alias, $for_class);
1080
+	}
1081 1081
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -37,122 +37,122 @@
 block discarded – undo
37 37
  * @since           4.0
38 38
  */
39 39
 if (function_exists('espresso_version')) {
40
-    if (! function_exists('espresso_duplicate_plugin_error')) {
41
-        /**
42
-         *    espresso_duplicate_plugin_error
43
-         *    displays if more than one version of EE is activated at the same time
44
-         */
45
-        function espresso_duplicate_plugin_error()
46
-        {
47
-            ?>
40
+	if (! function_exists('espresso_duplicate_plugin_error')) {
41
+		/**
42
+		 *    espresso_duplicate_plugin_error
43
+		 *    displays if more than one version of EE is activated at the same time
44
+		 */
45
+		function espresso_duplicate_plugin_error()
46
+		{
47
+			?>
48 48
             <div class="error">
49 49
                 <p>
50 50
                     <?php
51
-                    echo esc_html__(
52
-                        '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.',
53
-                        'event_espresso'
54
-                    ); ?>
51
+					echo esc_html__(
52
+						'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.',
53
+						'event_espresso'
54
+					); ?>
55 55
                 </p>
56 56
             </div>
57 57
             <?php
58
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
59
-        }
60
-    }
61
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
58
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
59
+		}
60
+	}
61
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62 62
 } else {
63
-    define('EE_MIN_PHP_VER_REQUIRED', '7.1.0');
64
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
-        /**
66
-         * espresso_minimum_php_version_error
67
-         *
68
-         * @return void
69
-         */
70
-        function espresso_minimum_php_version_error()
71
-        {
72
-            ?>
63
+	define('EE_MIN_PHP_VER_REQUIRED', '7.1.0');
64
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
+		/**
66
+		 * espresso_minimum_php_version_error
67
+		 *
68
+		 * @return void
69
+		 */
70
+		function espresso_minimum_php_version_error()
71
+		{
72
+			?>
73 73
             <div class="error">
74 74
                 <p>
75 75
                     <?php
76
-                    printf(
77
-                        esc_html__(
78
-                            '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.',
79
-                            'event_espresso'
80
-                        ),
81
-                        EE_MIN_PHP_VER_REQUIRED,
82
-                        PHP_VERSION,
83
-                        '<br/>',
84
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
-                    );
86
-                    ?>
76
+					printf(
77
+						esc_html__(
78
+							'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.',
79
+							'event_espresso'
80
+						),
81
+						EE_MIN_PHP_VER_REQUIRED,
82
+						PHP_VERSION,
83
+						'<br/>',
84
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
+					);
86
+					?>
87 87
                 </p>
88 88
             </div>
89 89
             <?php
90
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
91
-        }
90
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
91
+		}
92 92
 
93
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
-    } else {
95
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
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.12.0.rc.001');
105
-        }
93
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
+	} else {
95
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
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.12.0.rc.001');
105
+		}
106 106
 
107
-        /**
108
-         * espresso_plugin_activation
109
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
110
-         */
111
-        function espresso_plugin_activation()
112
-        {
113
-            update_option('ee_espresso_activation', true);
107
+		/**
108
+		 * espresso_plugin_activation
109
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
110
+		 */
111
+		function espresso_plugin_activation()
112
+		{
113
+			update_option('ee_espresso_activation', true);
114 114
 
115
-            // Run WP GraphQL activation callback
116
-            if (! class_exists('WPGraphQL')) {
117
-                require_once EE_THIRD_PARTY . 'wp-graphql/wp-graphql.php';
118
-            }
119
-            graphql_activation_callback();
120
-        }
115
+			// Run WP GraphQL activation callback
116
+			if (! class_exists('WPGraphQL')) {
117
+				require_once EE_THIRD_PARTY . 'wp-graphql/wp-graphql.php';
118
+			}
119
+			graphql_activation_callback();
120
+		}
121 121
 
122
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
122
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
123 123
 
124
-        /**
125
-         * espresso_plugin_deactivation
126
-         */
127
-        function espresso_plugin_deactivation()
128
-        {
129
-            // Run WP GraphQL deactivation callback
130
-            if (! class_exists('WPGraphQL')) {
131
-                require_once EE_THIRD_PARTY . 'wp-graphql/wp-graphql.php';
132
-            }
133
-            graphql_deactivation_callback();
134
-        }
135
-        register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
124
+		/**
125
+		 * espresso_plugin_deactivation
126
+		 */
127
+		function espresso_plugin_deactivation()
128
+		{
129
+			// Run WP GraphQL deactivation callback
130
+			if (! class_exists('WPGraphQL')) {
131
+				require_once EE_THIRD_PARTY . 'wp-graphql/wp-graphql.php';
132
+			}
133
+			graphql_deactivation_callback();
134
+		}
135
+		register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
136 136
 
137
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
138
-        bootstrap_espresso();
139
-    }
137
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
138
+		bootstrap_espresso();
139
+	}
140 140
 }
141 141
 if (! function_exists('espresso_deactivate_plugin')) {
142
-    /**
143
-     *    deactivate_plugin
144
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
145
-     *
146
-     * @access public
147
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
148
-     * @return    void
149
-     */
150
-    function espresso_deactivate_plugin($plugin_basename = '')
151
-    {
152
-        if (! function_exists('deactivate_plugins')) {
153
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
154
-        }
155
-        unset($_GET['activate'], $_REQUEST['activate']);
156
-        deactivate_plugins($plugin_basename);
157
-    }
142
+	/**
143
+	 *    deactivate_plugin
144
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
145
+	 *
146
+	 * @access public
147
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
148
+	 * @return    void
149
+	 */
150
+	function espresso_deactivate_plugin($plugin_basename = '')
151
+	{
152
+		if (! function_exists('deactivate_plugins')) {
153
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
154
+		}
155
+		unset($_GET['activate'], $_REQUEST['activate']);
156
+		deactivate_plugins($plugin_basename);
157
+	}
158 158
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Change_Log.model.php 2 patches
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -11,93 +11,93 @@  discard block
 block discarded – undo
11 11
 class EEM_Change_Log extends EEM_Base
12 12
 {
13 13
 
14
-    /**
15
-     * the related object was created log type
16
-     */
17
-    const type_create = 'create';
18
-    /**
19
-     * the related object was updated (changed, or soft-deleted)
20
-     */
21
-    const type_update = 'update';
22
-    /**
23
-     * the related object was deleted permanently
24
-     */
25
-    const type_delete = 'delete';
26
-    /**
27
-     * the related item had something worth noting happen on it, but
28
-     * only for the purposes of debugging problems
29
-     */
30
-    const type_debug = 'debug';
31
-    /**
32
-     * the related item had an error occur on it
33
-     */
34
-    const type_error = 'error';
35
-    /**
36
-     * the related item is regarding some gateway interaction, like an IPN
37
-     * or request to process a payment
38
-     */
39
-    const type_gateway = 'gateway';
14
+	/**
15
+	 * the related object was created log type
16
+	 */
17
+	const type_create = 'create';
18
+	/**
19
+	 * the related object was updated (changed, or soft-deleted)
20
+	 */
21
+	const type_update = 'update';
22
+	/**
23
+	 * the related object was deleted permanently
24
+	 */
25
+	const type_delete = 'delete';
26
+	/**
27
+	 * the related item had something worth noting happen on it, but
28
+	 * only for the purposes of debugging problems
29
+	 */
30
+	const type_debug = 'debug';
31
+	/**
32
+	 * the related item had an error occur on it
33
+	 */
34
+	const type_error = 'error';
35
+	/**
36
+	 * the related item is regarding some gateway interaction, like an IPN
37
+	 * or request to process a payment
38
+	 */
39
+	const type_gateway = 'gateway';
40 40
 
41
-    /**
42
-     * private instance of the EEM_Change_Log object
43
-     *
44
-     * @access private
45
-     * @var EEM_Change_Log $_instance
46
-     */
47
-    protected static $_instance = null;
41
+	/**
42
+	 * private instance of the EEM_Change_Log object
43
+	 *
44
+	 * @access private
45
+	 * @var EEM_Change_Log $_instance
46
+	 */
47
+	protected static $_instance = null;
48 48
 
49 49
 
50
-    /**
51
-     * constructor
52
-     *
53
-     * @access protected
54
-     * @param null $timezone
55
-     * @throws EE_Error
56
-     */
57
-    protected function __construct($timezone = null)
58
-    {
59
-        global $current_user;
60
-        $this->singular_item       = esc_html__('Log', 'event_espresso');
61
-        $this->plural_item         = esc_html__('Logs', 'event_espresso');
62
-        $this->_tables             = array(
63
-            'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
64
-        );
65
-        $models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
66
-        $this->_fields             = array(
67
-            'Log' => array(
68
-                'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
69
-                'LOG_time'    => new EE_Datetime_Field(
70
-                    'LOG_time',
71
-                    esc_html__("Log Time", 'event_espresso'),
72
-                    false,
73
-                    EE_Datetime_Field::now
74
-                ),
75
-                'OBJ_ID'      => new EE_Foreign_Key_String_Field(
76
-                    'OBJ_ID',
77
-                    esc_html__("Object ID (int or string)", 'event_espresso'),
78
-                    true,
79
-                    null,
80
-                    $models_this_can_attach_to
81
-                ),
82
-                'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
83
-                    'OBJ_type',
84
-                    esc_html__("Object Type", 'event_espresso'),
85
-                    true,
86
-                    null,
87
-                    $models_this_can_attach_to
88
-                ),
89
-                'LOG_type'    => new EE_Plain_Text_Field(
90
-                    'LOG_type',
91
-                    esc_html__("Type of log entry", "event_espresso"),
92
-                    false,
93
-                    self::type_debug
94
-                ),
95
-                'LOG_message' => new EE_Maybe_Serialized_Text_Field(
96
-                    'LOG_message',
97
-                    esc_html__("Log Message (body)", 'event_espresso'),
98
-                    true
99
-                ),
100
-                /*
50
+	/**
51
+	 * constructor
52
+	 *
53
+	 * @access protected
54
+	 * @param null $timezone
55
+	 * @throws EE_Error
56
+	 */
57
+	protected function __construct($timezone = null)
58
+	{
59
+		global $current_user;
60
+		$this->singular_item       = esc_html__('Log', 'event_espresso');
61
+		$this->plural_item         = esc_html__('Logs', 'event_espresso');
62
+		$this->_tables             = array(
63
+			'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
64
+		);
65
+		$models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
66
+		$this->_fields             = array(
67
+			'Log' => array(
68
+				'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
69
+				'LOG_time'    => new EE_Datetime_Field(
70
+					'LOG_time',
71
+					esc_html__("Log Time", 'event_espresso'),
72
+					false,
73
+					EE_Datetime_Field::now
74
+				),
75
+				'OBJ_ID'      => new EE_Foreign_Key_String_Field(
76
+					'OBJ_ID',
77
+					esc_html__("Object ID (int or string)", 'event_espresso'),
78
+					true,
79
+					null,
80
+					$models_this_can_attach_to
81
+				),
82
+				'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
83
+					'OBJ_type',
84
+					esc_html__("Object Type", 'event_espresso'),
85
+					true,
86
+					null,
87
+					$models_this_can_attach_to
88
+				),
89
+				'LOG_type'    => new EE_Plain_Text_Field(
90
+					'LOG_type',
91
+					esc_html__("Type of log entry", "event_espresso"),
92
+					false,
93
+					self::type_debug
94
+				),
95
+				'LOG_message' => new EE_Maybe_Serialized_Text_Field(
96
+					'LOG_message',
97
+					esc_html__("Log Message (body)", 'event_espresso'),
98
+					true
99
+				),
100
+				/*
101 101
                  * Note: when querying for a change log's user, the OBJ_ID and OBJ_type fields are used,
102 102
                  * not the LOG_wp_user field. E.g.,
103 103
                  * `EEM_Change_Log::instance()->get_all(array(array('WP_User.ID'=>1)))` will actually return
@@ -106,158 +106,158 @@  discard block
 block discarded – undo
106 106
                  *  If you want the latter, you can't use the model's magic joining. E.g, you would need to do
107 107
                  * `EEM_Change_Log::instance()->get_all(array(array('LOG_wp_user' => 1)))`.
108 108
                  */
109
-                'LOG_wp_user' => new EE_WP_User_Field(
110
-                    'LOG_wp_user',
111
-                    esc_html__("User who was logged in while this occurred", 'event_espresso'),
112
-                    true
113
-                ),
114
-            ),
115
-        );
116
-        $this->_model_relations    = array();
117
-        foreach ($models_this_can_attach_to as $model) {
118
-            if ($model != 'Change_Log') {
119
-                $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
120
-            }
121
-        }
122
-        // use completely custom caps for this
123
-        unset($this->_cap_restriction_generators);
124
-        // caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
125
-        foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
126
-            $this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
127
-                = new EE_Return_None_Where_Conditions();
128
-        }
129
-        parent::__construct($timezone);
130
-    }
109
+				'LOG_wp_user' => new EE_WP_User_Field(
110
+					'LOG_wp_user',
111
+					esc_html__("User who was logged in while this occurred", 'event_espresso'),
112
+					true
113
+				),
114
+			),
115
+		);
116
+		$this->_model_relations    = array();
117
+		foreach ($models_this_can_attach_to as $model) {
118
+			if ($model != 'Change_Log') {
119
+				$this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
120
+			}
121
+		}
122
+		// use completely custom caps for this
123
+		unset($this->_cap_restriction_generators);
124
+		// caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
125
+		foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
126
+			$this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
127
+				= new EE_Return_None_Where_Conditions();
128
+		}
129
+		parent::__construct($timezone);
130
+	}
131 131
 
132
-    /**
133
-     * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
134
-     * @param mixed         $message  array|string of the message you want to record
135
-     * @param EE_Base_Class $related_model_obj
136
-     * @return EE_Change_Log
137
-     * @throws EE_Error
138
-     */
139
-    public function log($log_type, $message, $related_model_obj)
140
-    {
141
-        if ($related_model_obj instanceof EE_Base_Class) {
142
-            $obj_id   = $related_model_obj->ID();
143
-            $obj_type = $related_model_obj->get_model()->get_this_model_name();
144
-        } else {
145
-            $obj_id   = null;
146
-            $obj_type = null;
147
-        }
148
-        /** @var EE_Change_Log $log */
149
-        $log = EE_Change_Log::new_instance(array(
150
-            'LOG_type'    => $log_type,
151
-            'LOG_message' => $message,
152
-            'OBJ_ID'      => $obj_id,
153
-            'OBJ_type'    => $obj_type,
154
-        ));
155
-        $log->save();
156
-        return $log;
157
-    }
132
+	/**
133
+	 * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
134
+	 * @param mixed         $message  array|string of the message you want to record
135
+	 * @param EE_Base_Class $related_model_obj
136
+	 * @return EE_Change_Log
137
+	 * @throws EE_Error
138
+	 */
139
+	public function log($log_type, $message, $related_model_obj)
140
+	{
141
+		if ($related_model_obj instanceof EE_Base_Class) {
142
+			$obj_id   = $related_model_obj->ID();
143
+			$obj_type = $related_model_obj->get_model()->get_this_model_name();
144
+		} else {
145
+			$obj_id   = null;
146
+			$obj_type = null;
147
+		}
148
+		/** @var EE_Change_Log $log */
149
+		$log = EE_Change_Log::new_instance(array(
150
+			'LOG_type'    => $log_type,
151
+			'LOG_message' => $message,
152
+			'OBJ_ID'      => $obj_id,
153
+			'OBJ_type'    => $obj_type,
154
+		));
155
+		$log->save();
156
+		return $log;
157
+	}
158 158
 
159 159
 
160
-    /**
161
-     * Adds a gateway log for the specified object, given its ID and type
162
-     *
163
-     * @param string $message
164
-     * @param mixed  $related_obj_id
165
-     * @param string $related_obj_type
166
-     * @throws EE_Error
167
-     * @return EE_Change_Log
168
-     */
169
-    public function gateway_log($message, $related_obj_id, $related_obj_type)
170
-    {
171
-        if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
172
-            throw new EE_Error(
173
-                sprintf(
174
-                    esc_html__(
175
-                        "'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
176
-                        "event_espresso"
177
-                    ),
178
-                    $related_obj_type
179
-                )
180
-            );
181
-        }
182
-        /** @var EE_Change_Log $log */
183
-        $log = EE_Change_Log::new_instance(array(
184
-            'LOG_type'    => EEM_Change_Log::type_gateway,
185
-            'LOG_message' => $message,
186
-            'OBJ_ID'      => $related_obj_id,
187
-            'OBJ_type'    => $related_obj_type,
188
-        ));
189
-        $log->save();
190
-        return $log;
191
-    }
160
+	/**
161
+	 * Adds a gateway log for the specified object, given its ID and type
162
+	 *
163
+	 * @param string $message
164
+	 * @param mixed  $related_obj_id
165
+	 * @param string $related_obj_type
166
+	 * @throws EE_Error
167
+	 * @return EE_Change_Log
168
+	 */
169
+	public function gateway_log($message, $related_obj_id, $related_obj_type)
170
+	{
171
+		if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
172
+			throw new EE_Error(
173
+				sprintf(
174
+					esc_html__(
175
+						"'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
176
+						"event_espresso"
177
+					),
178
+					$related_obj_type
179
+				)
180
+			);
181
+		}
182
+		/** @var EE_Change_Log $log */
183
+		$log = EE_Change_Log::new_instance(array(
184
+			'LOG_type'    => EEM_Change_Log::type_gateway,
185
+			'LOG_message' => $message,
186
+			'OBJ_ID'      => $related_obj_id,
187
+			'OBJ_type'    => $related_obj_type,
188
+		));
189
+		$log->save();
190
+		return $log;
191
+	}
192 192
 
193 193
 
194
-    /**
195
-     * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
196
-     *
197
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
198
-     * @return array of arrays
199
-     * @throws EE_Error
200
-     */
201
-    public function get_all_efficiently($query_params)
202
-    {
203
-        return $this->_get_all_wpdb_results($query_params);
204
-    }
194
+	/**
195
+	 * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
196
+	 *
197
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
198
+	 * @return array of arrays
199
+	 * @throws EE_Error
200
+	 */
201
+	public function get_all_efficiently($query_params)
202
+	{
203
+		return $this->_get_all_wpdb_results($query_params);
204
+	}
205 205
 
206 206
 
207
-    /**
208
-     * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
209
-     * models after this, they may be out-of-sync with the database
210
-     *
211
-     * @param DateTime $datetime
212
-     * @return false|int
213
-     * @throws EE_Error
214
-     */
215
-    public function delete_gateway_logs_older_than(DateTime $datetime)
216
-    {
217
-        global $wpdb;
218
-        return $wpdb->query(
219
-            $wpdb->prepare(
220
-                'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
221
-                EEM_Change_Log::type_gateway,
222
-                $datetime->format(EE_Datetime_Field::mysql_timestamp_format)
223
-            )
224
-        );
225
-    }
207
+	/**
208
+	 * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
209
+	 * models after this, they may be out-of-sync with the database
210
+	 *
211
+	 * @param DateTime $datetime
212
+	 * @return false|int
213
+	 * @throws EE_Error
214
+	 */
215
+	public function delete_gateway_logs_older_than(DateTime $datetime)
216
+	{
217
+		global $wpdb;
218
+		return $wpdb->query(
219
+			$wpdb->prepare(
220
+				'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
221
+				EEM_Change_Log::type_gateway,
222
+				$datetime->format(EE_Datetime_Field::mysql_timestamp_format)
223
+			)
224
+		);
225
+	}
226 226
 
227 227
 
228
-    /**
229
-     * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
230
-     * map vai the given filter.
231
-     *
232
-     * @return array
233
-     */
234
-    public static function get_pretty_label_map_for_registered_types()
235
-    {
236
-        return apply_filters(
237
-            'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
238
-            array(
239
-                self::type_create =>  esc_html__("Create", "event_espresso"),
240
-                self::type_update =>  esc_html__("Update", "event_espresso"),
241
-                self::type_delete => esc_html__("Delete", "event_espresso"),
242
-                self::type_debug =>  esc_html__("Debug", "event_espresso"),
243
-                self::type_error =>  esc_html__("Error", "event_espresso"),
244
-                self::type_gateway => esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso')
245
-            )
246
-        );
247
-    }
228
+	/**
229
+	 * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
230
+	 * map vai the given filter.
231
+	 *
232
+	 * @return array
233
+	 */
234
+	public static function get_pretty_label_map_for_registered_types()
235
+	{
236
+		return apply_filters(
237
+			'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
238
+			array(
239
+				self::type_create =>  esc_html__("Create", "event_espresso"),
240
+				self::type_update =>  esc_html__("Update", "event_espresso"),
241
+				self::type_delete => esc_html__("Delete", "event_espresso"),
242
+				self::type_debug =>  esc_html__("Debug", "event_espresso"),
243
+				self::type_error =>  esc_html__("Error", "event_espresso"),
244
+				self::type_gateway => esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso')
245
+			)
246
+		);
247
+	}
248 248
 
249 249
 
250
-    /**
251
-     * Return the pretty (localized) label for the given log type identifier.
252
-     * @param string $type_identifier
253
-     * @return string
254
-     */
255
-    public static function get_pretty_label_for_type($type_identifier)
256
-    {
257
-        $type_identifier_map = self::get_pretty_label_map_for_registered_types();
258
-        // we fallback to the incoming type identifier if there is no localized label for it.
259
-        return isset($type_identifier_map[ $type_identifier ])
260
-            ? $type_identifier_map[ $type_identifier ]
261
-            : $type_identifier;
262
-    }
250
+	/**
251
+	 * Return the pretty (localized) label for the given log type identifier.
252
+	 * @param string $type_identifier
253
+	 * @return string
254
+	 */
255
+	public static function get_pretty_label_for_type($type_identifier)
256
+	{
257
+		$type_identifier_map = self::get_pretty_label_map_for_registered_types();
258
+		// we fallback to the incoming type identifier if there is no localized label for it.
259
+		return isset($type_identifier_map[ $type_identifier ])
260
+			? $type_identifier_map[ $type_identifier ]
261
+			: $type_identifier;
262
+	}
263 263
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -113,17 +113,17 @@  discard block
 block discarded – undo
113 113
                 ),
114 114
             ),
115 115
         );
116
-        $this->_model_relations    = array();
116
+        $this->_model_relations = array();
117 117
         foreach ($models_this_can_attach_to as $model) {
118 118
             if ($model != 'Change_Log') {
119
-                $this->_model_relations[ $model ] = new EE_Belongs_To_Any_Relation();
119
+                $this->_model_relations[$model] = new EE_Belongs_To_Any_Relation();
120 120
             }
121 121
         }
122 122
         // use completely custom caps for this
123 123
         unset($this->_cap_restriction_generators);
124 124
         // caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
125 125
         foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
126
-            $this->_cap_restrictions[ $cap_context ][ EE_Restriction_Generator_Base::get_default_restrictions_cap() ]
126
+            $this->_cap_restrictions[$cap_context][EE_Restriction_Generator_Base::get_default_restrictions_cap()]
127 127
                 = new EE_Return_None_Where_Conditions();
128 128
         }
129 129
         parent::__construct($timezone);
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
      */
169 169
     public function gateway_log($message, $related_obj_id, $related_obj_type)
170 170
     {
171
-        if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
171
+        if ( ! EE_Registry::instance()->is_model_name($related_obj_type)) {
172 172
             throw new EE_Error(
173 173
                 sprintf(
174 174
                     esc_html__(
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
         global $wpdb;
218 218
         return $wpdb->query(
219 219
             $wpdb->prepare(
220
-                'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
220
+                'DELETE FROM '.$this->table().' WHERE LOG_type = %s AND LOG_time < %s',
221 221
                 EEM_Change_Log::type_gateway,
222 222
                 $datetime->format(EE_Datetime_Field::mysql_timestamp_format)
223 223
             )
@@ -256,8 +256,8 @@  discard block
 block discarded – undo
256 256
     {
257 257
         $type_identifier_map = self::get_pretty_label_map_for_registered_types();
258 258
         // we fallback to the incoming type identifier if there is no localized label for it.
259
-        return isset($type_identifier_map[ $type_identifier ])
260
-            ? $type_identifier_map[ $type_identifier ]
259
+        return isset($type_identifier_map[$type_identifier])
260
+            ? $type_identifier_map[$type_identifier]
261 261
             : $type_identifier;
262 262
     }
263 263
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -7,11 +7,9 @@
 block discarded – undo
7 7
 use EventEspresso\core\exceptions\UnexpectedEntityException;
8 8
 use EventEspresso\core\interfaces\ResettableInterface;
9 9
 use EventEspresso\core\services\container\Mirror;
10
-use EventEspresso\core\services\dependencies\DependencyResolver;
11 10
 use EventEspresso\core\services\loaders\LoaderFactory;
12 11
 use EventEspresso\core\services\loaders\LoaderInterface;
13 12
 use EventEspresso\core\services\orm\ModelFieldFactory;
14
-use EventEspresso\core\services\request\RequestInterface;
15 13
 
16 14
 /**
17 15
  * Class EEM_Base
Please login to merge, or discard this patch.
Indentation   +6528 added lines, -6528 removed lines patch added patch discarded remove patch
@@ -40,6534 +40,6534 @@
 block discarded – undo
40 40
 abstract class EEM_Base extends EE_Base implements ResettableInterface
41 41
 {
42 42
 
43
-    /**
44
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
45
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
46
-     * They almost always WILL NOT, but it's not necessarily a requirement.
47
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
48
-     *
49
-     * @var boolean
50
-     */
51
-    private $_values_already_prepared_by_model_object = 0;
52
-
53
-    /**
54
-     * when $_values_already_prepared_by_model_object equals this, we assume
55
-     * the data is just like form input that needs to have the model fields'
56
-     * prepare_for_set and prepare_for_use_in_db called on it
57
-     */
58
-    const not_prepared_by_model_object = 0;
59
-
60
-    /**
61
-     * when $_values_already_prepared_by_model_object equals this, we
62
-     * assume this value is coming from a model object and doesn't need to have
63
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
64
-     */
65
-    const prepared_by_model_object = 1;
66
-
67
-    /**
68
-     * when $_values_already_prepared_by_model_object equals this, we assume
69
-     * the values are already to be used in the database (ie no processing is done
70
-     * on them by the model's fields)
71
-     */
72
-    const prepared_for_use_in_db = 2;
73
-
74
-
75
-    protected $singular_item = 'Item';
76
-
77
-    protected $plural_item   = 'Items';
78
-
79
-    /**
80
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
81
-     */
82
-    protected $_tables;
83
-
84
-    /**
85
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
86
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
87
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
88
-     *
89
-     * @var EE_Model_Field_Base[][] $_fields
90
-     */
91
-    protected $_fields;
92
-
93
-    /**
94
-     * array of different kinds of relations
95
-     *
96
-     * @var EE_Model_Relation_Base[] $_model_relations
97
-     */
98
-    protected $_model_relations = [];
99
-
100
-    /**
101
-     * @var EE_Index[] $_indexes
102
-     */
103
-    protected $_indexes = array();
104
-
105
-    /**
106
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
107
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
108
-     * by setting the same columns as used in these queries in the query yourself.
109
-     *
110
-     * @var EE_Default_Where_Conditions
111
-     */
112
-    protected $_default_where_conditions_strategy;
113
-
114
-    /**
115
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
116
-     * This is particularly useful when you want something between 'none' and 'default'
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_minimum_where_conditions_strategy;
121
-
122
-    /**
123
-     * String describing how to find the "owner" of this model's objects.
124
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
125
-     * But when there isn't, this indicates which related model, or transiently-related model,
126
-     * has the foreign key to the wp_users table.
127
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
128
-     * related to events, and events have a foreign key to wp_users.
129
-     * On EEM_Transaction, this would be 'Transaction.Event'
130
-     *
131
-     * @var string
132
-     */
133
-    protected $_model_chain_to_wp_user = '';
134
-
135
-    /**
136
-     * String describing how to find the model with a password controlling access to this model. This property has the
137
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
138
-     * This value is the path of models to follow to arrive at the model with the password field.
139
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
140
-     * model with a password that should affect reading this on the front-end.
141
-     * Eg this is an empty string for the Event model because it has a password.
142
-     * This is null for the Registration model, because its event's password has no bearing on whether
143
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
144
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
145
-     * should hide tickets for datetimes for events that have a password set.
146
-     * @var string |null
147
-     */
148
-    protected $model_chain_to_password = null;
149
-
150
-    /**
151
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
-     * don't need it (particularly CPT models)
153
-     *
154
-     * @var bool
155
-     */
156
-    protected $_ignore_where_strategy = false;
157
-
158
-    /**
159
-     * String used in caps relating to this model. Eg, if the caps relating to this
160
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
-     *
162
-     * @var string. If null it hasn't been initialized yet. If false then we
163
-     * have indicated capabilities don't apply to this
164
-     */
165
-    protected $_caps_slug = null;
166
-
167
-    /**
168
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
-     * and next-level keys are capability names, and each's value is a
170
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
-     * they specify which context to use (ie, frontend, backend, edit or delete)
172
-     * and then each capability in the corresponding sub-array that they're missing
173
-     * adds the where conditions onto the query.
174
-     *
175
-     * @var array
176
-     */
177
-    protected $_cap_restrictions = array(
178
-        self::caps_read       => array(),
179
-        self::caps_read_admin => array(),
180
-        self::caps_edit       => array(),
181
-        self::caps_delete     => array(),
182
-    );
183
-
184
-    /**
185
-     * Array defining which cap restriction generators to use to create default
186
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
187
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
-     * automatically set this to false (not just null).
190
-     *
191
-     * @var EE_Restriction_Generator_Base[]
192
-     */
193
-    protected $_cap_restriction_generators = array();
194
-
195
-    /**
196
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
-     */
198
-    const caps_read       = 'read';
199
-
200
-    const caps_read_admin = 'read_admin';
201
-
202
-    const caps_edit       = 'edit';
203
-
204
-    const caps_delete     = 'delete';
205
-
206
-    /**
207
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
-     * maps to 'read' because when looking for relevant permissions we're going to use
210
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
211
-     *
212
-     * @var array
213
-     */
214
-    protected $_cap_contexts_to_cap_action_map = array(
215
-        self::caps_read       => 'read',
216
-        self::caps_read_admin => 'read',
217
-        self::caps_edit       => 'edit',
218
-        self::caps_delete     => 'delete',
219
-    );
220
-
221
-    /**
222
-     * Timezone
223
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
-     * EE_Datetime_Field data type will have access to it.
227
-     *
228
-     * @var string
229
-     */
230
-    protected $_timezone;
231
-
232
-
233
-    /**
234
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
-     * multisite.
236
-     *
237
-     * @var int
238
-     */
239
-    protected static $_model_query_blog_id;
240
-
241
-    /**
242
-     * A copy of _fields, except the array keys are the model names pointed to by
243
-     * the field
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cache_foreign_key_to_fields = array();
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, indexed by their name
251
-     *
252
-     * @var EE_Model_Field_Base[]
253
-     */
254
-    private $_cached_fields = null;
255
-
256
-    /**
257
-     * Cached list of all the fields on the model, except those that are
258
-     * marked as only pertinent to the database
259
-     *
260
-     * @var EE_Model_Field_Base[]
261
-     */
262
-    private $_cached_fields_non_db_only = null;
263
-
264
-    /**
265
-     * A cached reference to the primary key for quick lookup
266
-     *
267
-     * @var EE_Model_Field_Base
268
-     */
269
-    private $_primary_key_field = null;
270
-
271
-    /**
272
-     * Flag indicating whether this model has a primary key or not
273
-     *
274
-     * @var boolean
275
-     */
276
-    protected $_has_primary_key_field = null;
277
-
278
-    /**
279
-     * array in the format:  [ FK alias => full PK ]
280
-     * where keys are local column name aliases for foreign keys
281
-     * and values are the fully qualified column name for the primary key they represent
282
-     *  ex:
283
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
-     *
285
-     * @var array $foreign_key_aliases
286
-     */
287
-    protected $foreign_key_aliases = [];
288
-
289
-    /**
290
-     * Whether or not this model is based off a table in WP core only (CPTs should set
291
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
-     * This should be true for models that deal with data that should exist independent of EE.
293
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
295
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
297
-     * @var boolean
298
-     */
299
-    protected $_wp_core_model = false;
300
-
301
-    /**
302
-     * @var bool stores whether this model has a password field or not.
303
-     * null until initialized by hasPasswordField()
304
-     */
305
-    protected $has_password_field;
306
-
307
-    /**
308
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
309
-     */
310
-    protected $password_field;
311
-
312
-    /**
313
-     *    List of valid operators that can be used for querying.
314
-     * The keys are all operators we'll accept, the values are the real SQL
315
-     * operators used
316
-     *
317
-     * @var array
318
-     */
319
-    protected $_valid_operators = array(
320
-        '='           => '=',
321
-        '<='          => '<=',
322
-        '<'           => '<',
323
-        '>='          => '>=',
324
-        '>'           => '>',
325
-        '!='          => '!=',
326
-        'LIKE'        => 'LIKE',
327
-        'like'        => 'LIKE',
328
-        'NOT_LIKE'    => 'NOT LIKE',
329
-        'not_like'    => 'NOT LIKE',
330
-        'NOT LIKE'    => 'NOT LIKE',
331
-        'not like'    => 'NOT LIKE',
332
-        'IN'          => 'IN',
333
-        'in'          => 'IN',
334
-        'NOT_IN'      => 'NOT IN',
335
-        'not_in'      => 'NOT IN',
336
-        'NOT IN'      => 'NOT IN',
337
-        'not in'      => 'NOT IN',
338
-        'between'     => 'BETWEEN',
339
-        'BETWEEN'     => 'BETWEEN',
340
-        'IS_NOT_NULL' => 'IS NOT NULL',
341
-        'is_not_null' => 'IS NOT NULL',
342
-        'IS NOT NULL' => 'IS NOT NULL',
343
-        'is not null' => 'IS NOT NULL',
344
-        'IS_NULL'     => 'IS NULL',
345
-        'is_null'     => 'IS NULL',
346
-        'IS NULL'     => 'IS NULL',
347
-        'is null'     => 'IS NULL',
348
-        'REGEXP'      => 'REGEXP',
349
-        'regexp'      => 'REGEXP',
350
-        'NOT_REGEXP'  => 'NOT REGEXP',
351
-        'not_regexp'  => 'NOT REGEXP',
352
-        'NOT REGEXP'  => 'NOT REGEXP',
353
-        'not regexp'  => 'NOT REGEXP',
354
-    );
355
-
356
-    /**
357
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
358
-     *
359
-     * @var array
360
-     */
361
-    protected $_in_style_operators = array('IN', 'NOT IN');
362
-
363
-    /**
364
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
365
-     * '12-31-2012'"
366
-     *
367
-     * @var array
368
-     */
369
-    protected $_between_style_operators = array('BETWEEN');
370
-
371
-    /**
372
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
373
-     * @var array
374
-     */
375
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
376
-    /**
377
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
378
-     * on a join table.
379
-     *
380
-     * @var array
381
-     */
382
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
383
-
384
-    /**
385
-     * Allowed values for $query_params['order'] for ordering in queries
386
-     *
387
-     * @var array
388
-     */
389
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
390
-
391
-    /**
392
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
393
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
394
-     *
395
-     * @var array
396
-     */
397
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
398
-
399
-    /**
400
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
401
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
402
-     *
403
-     * @var array
404
-     */
405
-    private $_allowed_query_params = array(
406
-        0,
407
-        'limit',
408
-        'order_by',
409
-        'group_by',
410
-        'having',
411
-        'force_join',
412
-        'order',
413
-        'on_join_limit',
414
-        'default_where_conditions',
415
-        'caps',
416
-        'extra_selects',
417
-        'exclude_protected',
418
-    );
419
-
420
-    /**
421
-     * All the data types that can be used in $wpdb->prepare statements.
422
-     *
423
-     * @var array
424
-     */
425
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
426
-
427
-    /**
428
-     * @var EE_Registry $EE
429
-     */
430
-    protected $EE = null;
431
-
432
-
433
-    /**
434
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
435
-     *
436
-     * @var int
437
-     */
438
-    protected $_show_next_x_db_queries = 0;
439
-
440
-    /**
441
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
442
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
443
-     * WHERE, GROUP_BY, etc.
444
-     *
445
-     * @var CustomSelects
446
-     */
447
-    protected $_custom_selections = array();
448
-
449
-    /**
450
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
451
-     * caches every model object we've fetched from the DB on this request
452
-     *
453
-     * @var array
454
-     */
455
-    protected $_entity_map;
456
-
457
-    /**
458
-     * @var LoaderInterface
459
-     */
460
-    private static $loader;
461
-
462
-    /**
463
-     * @var Mirror
464
-     */
465
-    private static $mirror;
466
-
467
-
468
-
469
-    /**
470
-     * constant used to show EEM_Base has not yet verified the db on this http request
471
-     */
472
-    const db_verified_none = 0;
473
-
474
-    /**
475
-     * constant used to show EEM_Base has verified the EE core db on this http request,
476
-     * but not the addons' dbs
477
-     */
478
-    const db_verified_core = 1;
479
-
480
-    /**
481
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
-     * the EE core db too)
483
-     */
484
-    const db_verified_addons = 2;
485
-
486
-    /**
487
-     * indicates whether an EEM_Base child has already re-verified the DB
488
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
489
-     * looking like EEM_Base::db_verified_*
490
-     *
491
-     * @var int - 0 = none, 1 = core, 2 = addons
492
-     */
493
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
494
-
495
-    /**
496
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
-     *        registrations for non-trashed tickets for non-trashed datetimes)
499
-     */
500
-    const default_where_conditions_all = 'all';
501
-
502
-    /**
503
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
-     *        models which share tables with other models, this can return data for the wrong model.
508
-     */
509
-    const default_where_conditions_this_only = 'this_model_only';
510
-
511
-    /**
512
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
-     */
516
-    const default_where_conditions_others_only = 'other_models_only';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
522
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
-     *        (regardless of whether those events and venues are trashed)
524
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
-     *        events.
526
-     */
527
-    const default_where_conditions_minimum_all = 'minimum';
528
-
529
-    /**
530
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
-     *        not)
534
-     */
535
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
-
537
-    /**
538
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
-     *        it's possible it will return table entries for other models. You should use
541
-     *        EEM_Base::default_where_conditions_minimum_all instead.
542
-     */
543
-    const default_where_conditions_none = 'none';
544
-
545
-
546
-
547
-    /**
548
-     * About all child constructors:
549
-     * they should define the _tables, _fields and _model_relations arrays.
550
-     * Should ALWAYS be called after child constructor.
551
-     * In order to make the child constructors to be as simple as possible, this parent constructor
552
-     * finalizes constructing all the object's attributes.
553
-     * Generally, rather than requiring a child to code
554
-     * $this->_tables = array(
555
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
556
-     *        ...);
557
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
558
-     * each EE_Table has a function to set the table's alias after the constructor, using
559
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
560
-     * do something similar.
561
-     *
562
-     * @param null $timezone
563
-     * @throws EE_Error
564
-     */
565
-    protected function __construct($timezone = null)
566
-    {
567
-        // check that the model has not been loaded too soon
568
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
569
-            throw new EE_Error(
570
-                sprintf(
571
-                    __(
572
-                        '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.',
573
-                        'event_espresso'
574
-                    ),
575
-                    get_class($this)
576
-                )
577
-            );
578
-        }
579
-        /**
580
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
581
-         */
582
-        if (empty(EEM_Base::$_model_query_blog_id)) {
583
-            EEM_Base::set_model_query_blog_id();
584
-        }
585
-        /**
586
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
587
-         * just use EE_Register_Model_Extension
588
-         *
589
-         * @var EE_Table_Base[] $_tables
590
-         */
591
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
592
-        foreach ($this->_tables as $table_alias => $table_obj) {
593
-            /** @var $table_obj EE_Table_Base */
594
-            $table_obj->_construct_finalize_with_alias($table_alias);
595
-            if ($table_obj instanceof EE_Secondary_Table) {
596
-                /** @var $table_obj EE_Secondary_Table */
597
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
598
-            }
599
-        }
600
-        /**
601
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
602
-         * EE_Register_Model_Extension
603
-         *
604
-         * @param EE_Model_Field_Base[] $_fields
605
-         */
606
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
607
-        $this->_invalidate_field_caches();
608
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
609
-            if (! array_key_exists($table_alias, $this->_tables)) {
610
-                throw new EE_Error(sprintf(__(
611
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
-                    'event_espresso'
613
-                ), $table_alias, implode(",", $this->_fields)));
614
-            }
615
-            foreach ($fields_for_table as $field_name => $field_obj) {
616
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
617
-                // primary key field base has a slightly different _construct_finalize
618
-                /** @var $field_obj EE_Model_Field_Base */
619
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
620
-            }
621
-        }
622
-        // everything is related to Extra_Meta
623
-        if (get_class($this) !== 'EEM_Extra_Meta') {
624
-            // make extra meta related to everything, but don't block deleting things just
625
-            // because they have related extra meta info. For now just orphan those extra meta
626
-            // in the future we should automatically delete them
627
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
628
-        }
629
-        // and change logs
630
-        if (get_class($this) !== 'EEM_Change_Log') {
631
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
632
-        }
633
-        /**
634
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
635
-         * EE_Register_Model_Extension
636
-         *
637
-         * @param EE_Model_Relation_Base[] $_model_relations
638
-         */
639
-        $this->_model_relations = (array) apply_filters(
640
-            'FHEE__' . get_class($this) . '__construct__model_relations',
641
-            $this->_model_relations
642
-        );
643
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
644
-            /** @var $relation_obj EE_Model_Relation_Base */
645
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
646
-        }
647
-        foreach ($this->_indexes as $index_name => $index_obj) {
648
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
649
-        }
650
-        $this->set_timezone($timezone);
651
-        // finalize default where condition strategy, or set default
652
-        if (! $this->_default_where_conditions_strategy) {
653
-            // nothing was set during child constructor, so set default
654
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
655
-        }
656
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
657
-        if (! $this->_minimum_where_conditions_strategy) {
658
-            // nothing was set during child constructor, so set default
659
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
660
-        }
661
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
662
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
663
-        // to indicate to NOT set it, set it to the logical default
664
-        if ($this->_caps_slug === null) {
665
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
666
-        }
667
-        // initialize the standard cap restriction generators if none were specified by the child constructor
668
-        if (is_array($this->_cap_restriction_generators)) {
669
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
670
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
671
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
672
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
673
-                        new EE_Restriction_Generator_Protected(),
674
-                        $cap_context,
675
-                        $this
676
-                    );
677
-                }
678
-            }
679
-        }
680
-        // if there are cap restriction generators, use them to make the default cap restrictions
681
-        if (is_array($this->_cap_restriction_generators)) {
682
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
683
-                if (! $generator_object) {
684
-                    continue;
685
-                }
686
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
687
-                    throw new EE_Error(
688
-                        sprintf(
689
-                            __(
690
-                                '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.',
691
-                                'event_espresso'
692
-                            ),
693
-                            $context,
694
-                            $this->get_this_model_name()
695
-                        )
696
-                    );
697
-                }
698
-                $action = $this->cap_action_for_context($context);
699
-                if (! $generator_object->construction_finalized()) {
700
-                    $generator_object->_construct_finalize($this, $action);
701
-                }
702
-            }
703
-        }
704
-        do_action('AHEE__' . get_class($this) . '__construct__end');
705
-    }
706
-
707
-
708
-    /**
709
-     * @return LoaderInterface
710
-     * @throws InvalidArgumentException
711
-     * @throws InvalidDataTypeException
712
-     * @throws InvalidInterfaceException
713
-     */
714
-    protected static function getLoader(): LoaderInterface
715
-    {
716
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
717
-            EEM_Base::$loader = LoaderFactory::getLoader();
718
-        }
719
-        return EEM_Base::$loader;
720
-    }
721
-
722
-
723
-    /**
724
-     * @return Mirror
725
-     * @since   $VID:$
726
-     */
727
-    private static function getMirror(): Mirror
728
-    {
729
-        if (! EEM_Base::$mirror instanceof Mirror) {
730
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
731
-        }
732
-        return EEM_Base::$mirror;
733
-    }
734
-
735
-
736
-    /**
737
-     * @param string $model_class_Name
738
-     * @param string $timezone
739
-     * @return array
740
-     * @throws ReflectionException
741
-     * @since   $VID:$
742
-     */
743
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
744
-    {
745
-        $arguments = [$timezone];
746
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
747
-        if (count($params) > 1) {
748
-            if ($params[1]->getName() === 'model_field_factory') {
749
-                $arguments = [
750
-                    $timezone,
751
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class)
752
-                ];
753
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
754
-                $arguments = [
755
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\Element'),
756
-                    $timezone
757
-                ];
758
-            } elseif ($model_class_Name === 'EEM_Form_Input') {
759
-                $arguments = [
760
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\Element'),
761
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
762
-                    $timezone
763
-                ];
764
-            }
765
-        }
766
-        return $arguments;
767
-    }
768
-
769
-
770
-    /**
771
-     * This function is a singleton method used to instantiate the Espresso_model object
772
-     *
773
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
774
-     *                                (and any incoming timezone data that gets saved).
775
-     *                                Note this just sends the timezone info to the date time model field objects.
776
-     *                                Default is NULL
777
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
778
-     * @return static (as in the concrete child class)
779
-     * @throws EE_Error
780
-     * @throws ReflectionException
781
-     */
782
-    public static function instance($timezone = null)
783
-    {
784
-        // check if instance of Espresso_model already exists
785
-        if (! static::$_instance instanceof static) {
786
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
787
-            $model = new static(...$arguments);
788
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
789
-            static::$_instance = $model;
790
-        }
791
-        // we might have a timezone set, let set_timezone decide what to do with it
792
-        if ($timezone){
793
-            static::$_instance->set_timezone($timezone);
794
-        }
795
-        // Espresso_model object
796
-        return static::$_instance;
797
-    }
798
-
799
-
800
-
801
-    /**
802
-     * resets the model and returns it
803
-     *
804
-     * @param string|null $timezone
805
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
806
-     * all its properties reset; if it wasn't instantiated, returns null)
807
-     * @throws EE_Error
808
-     * @throws ReflectionException
809
-     * @throws InvalidArgumentException
810
-     * @throws InvalidDataTypeException
811
-     * @throws InvalidInterfaceException
812
-     */
813
-    public static function reset($timezone = null)
814
-    {
815
-        if (! static::$_instance instanceof EEM_Base) {
816
-            return null;
817
-        }
818
-        // Let's NOT swap out the current instance for a new one
819
-        // because if someone has a reference to it, we can't remove their reference.
820
-        // It's best to keep using the same reference but change the original object instead,
821
-        // so reset all its properties to their original values as defined in the class.
822
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
823
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
824
-            // don't set instance to null like it was originally,
825
-            // but it's static anyways, and we're ignoring static properties (for now at least)
826
-            if (! isset($static_properties[ $property ])) {
827
-                static::$_instance->{$property} = $value;
828
-            }
829
-        }
830
-        // and then directly call its constructor again, like we would if we were creating a new one
831
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
832
-        static::$_instance->__construct(...$arguments);
833
-        return self::instance();
834
-    }
835
-
836
-
837
-    /**
838
-     * Used to set the $_model_query_blog_id static property.
839
-     *
840
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
841
-     *                      value for get_current_blog_id() will be used.
842
-     */
843
-    public static function set_model_query_blog_id($blog_id = 0)
844
-    {
845
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
846
-            ? (int) $blog_id
847
-            : get_current_blog_id();
848
-    }
849
-
850
-
851
-    /**
852
-     * Returns whatever is set as the internal $model_query_blog_id.
853
-     *
854
-     * @return int
855
-     */
856
-    public static function get_model_query_blog_id()
857
-    {
858
-        return EEM_Base::$_model_query_blog_id;
859
-    }
860
-
861
-
862
-
863
-    /**
864
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
865
-     *
866
-     * @param  boolean $translated return localized strings or JUST the array.
867
-     * @return array
868
-     * @throws EE_Error
869
-     * @throws InvalidArgumentException
870
-     * @throws InvalidDataTypeException
871
-     * @throws InvalidInterfaceException
872
-     */
873
-    public function status_array($translated = false)
874
-    {
875
-        if (! array_key_exists('Status', $this->_model_relations)) {
876
-            return array();
877
-        }
878
-        $model_name = $this->get_this_model_name();
879
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
880
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
881
-        $status_array = array();
882
-        foreach ($stati as $status) {
883
-            $status_array[ $status->ID() ] = $status->get('STS_code');
884
-        }
885
-        return $translated
886
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
887
-            : $status_array;
888
-    }
889
-
890
-
891
-
892
-    /**
893
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
894
-     *
895
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
896
-     *                             or if you have the development copy of EE you can view this at the path:
897
-     *                             /docs/G--Model-System/model-query-params.md
898
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
899
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
900
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
901
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
902
-     *                                        array( array(
903
-     *                                        'OR'=>array(
904
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
905
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
906
-     *                                        )
907
-     *                                        ),
908
-     *                                        'limit'=>10,
909
-     *                                        'group_by'=>'TXN_ID'
910
-     *                                        ));
911
-     *                                        get all the answers to the question titled "shirt size" for event with id
912
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
913
-     *                                        'Question.QST_display_text'=>'shirt size',
914
-     *                                        'Registration.Event.EVT_ID'=>12
915
-     *                                        ),
916
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
917
-     *                                        ));
918
-     * @throws EE_Error
919
-     */
920
-    public function get_all($query_params = array())
921
-    {
922
-        if (
923
-            isset($query_params['limit'])
924
-            && ! isset($query_params['group_by'])
925
-        ) {
926
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
927
-        }
928
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
929
-    }
930
-
931
-
932
-
933
-    /**
934
-     * Modifies the query parameters so we only get back model objects
935
-     * that "belong" to the current user
936
-     *
937
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
938
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
939
-     */
940
-    public function alter_query_params_to_only_include_mine($query_params = array())
941
-    {
942
-        $wp_user_field_name = $this->wp_user_field_name();
943
-        if ($wp_user_field_name) {
944
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
945
-        }
946
-        return $query_params;
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * Returns the name of the field's name that points to the WP_User table
953
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
954
-     * foreign key to the WP_User table)
955
-     *
956
-     * @return string|boolean string on success, boolean false when there is no
957
-     * foreign key to the WP_User table
958
-     */
959
-    public function wp_user_field_name()
960
-    {
961
-        try {
962
-            if (! empty($this->_model_chain_to_wp_user)) {
963
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
964
-                $last_model_name = end($models_to_follow_to_wp_users);
965
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
966
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
967
-            } else {
968
-                $model_with_fk_to_wp_users = $this;
969
-                $model_chain_to_wp_user = '';
970
-            }
971
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
972
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
973
-        } catch (EE_Error $e) {
974
-            return false;
975
-        }
976
-    }
977
-
978
-
979
-
980
-    /**
981
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
982
-     * (or transiently-related model) has a foreign key to the wp_users table;
983
-     * useful for finding if model objects of this type are 'owned' by the current user.
984
-     * This is an empty string when the foreign key is on this model and when it isn't,
985
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
986
-     * (or transiently-related model)
987
-     *
988
-     * @return string
989
-     */
990
-    public function model_chain_to_wp_user()
991
-    {
992
-        return $this->_model_chain_to_wp_user;
993
-    }
994
-
995
-
996
-
997
-    /**
998
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
999
-     * like how registrations don't have a foreign key to wp_users, but the
1000
-     * events they are for are), or is unrelated to wp users.
1001
-     * generally available
1002
-     *
1003
-     * @return boolean
1004
-     */
1005
-    public function is_owned()
1006
-    {
1007
-        if ($this->model_chain_to_wp_user()) {
1008
-            return true;
1009
-        }
1010
-        try {
1011
-            $this->get_foreign_key_to('WP_User');
1012
-            return true;
1013
-        } catch (EE_Error $e) {
1014
-            return false;
1015
-        }
1016
-    }
1017
-
1018
-
1019
-    /**
1020
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1021
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1022
-     * the model)
1023
-     *
1024
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1025
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1026
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1027
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1028
-     *                                  override this and set the select to "*", or a specific column name, like
1029
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1030
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1031
-     *                                  the aliases used to refer to this selection, and values are to be
1032
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1033
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1034
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1035
-     * @throws EE_Error
1036
-     * @throws InvalidArgumentException
1037
-     */
1038
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1039
-    {
1040
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1041
-        ;
1042
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1043
-        $select_expressions = $columns_to_select === null
1044
-            ? $this->_construct_default_select_sql($model_query_info)
1045
-            : '';
1046
-        if ($this->_custom_selections instanceof CustomSelects) {
1047
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1048
-            $select_expressions .= $select_expressions
1049
-                ? ', ' . $custom_expressions
1050
-                : $custom_expressions;
1051
-        }
1052
-
1053
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1054
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1055
-    }
1056
-
1057
-
1058
-    /**
1059
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1060
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1061
-     * method of including extra select information.
1062
-     *
1063
-     * @param array             $query_params
1064
-     * @param null|array|string $columns_to_select
1065
-     * @return null|CustomSelects
1066
-     * @throws InvalidArgumentException
1067
-     */
1068
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1069
-    {
1070
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1071
-            return null;
1072
-        }
1073
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1074
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1075
-        return new CustomSelects($selects);
1076
-    }
1077
-
1078
-
1079
-
1080
-    /**
1081
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1082
-     * but you can use the model query params to more easily
1083
-     * take care of joins, field preparation etc.
1084
-     *
1085
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1086
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1087
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1088
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1089
-     *                                  override this and set the select to "*", or a specific column name, like
1090
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1091
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1092
-     *                                  the aliases used to refer to this selection, and values are to be
1093
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1094
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1095
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1096
-     * @throws EE_Error
1097
-     */
1098
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1099
-    {
1100
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1101
-    }
1102
-
1103
-
1104
-
1105
-    /**
1106
-     * For creating a custom select statement
1107
-     *
1108
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1109
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1110
-     *                                 SQL, and 1=>is the datatype
1111
-     * @throws EE_Error
1112
-     * @return string
1113
-     */
1114
-    private function _construct_select_from_input($columns_to_select)
1115
-    {
1116
-        if (is_array($columns_to_select)) {
1117
-            $select_sql_array = array();
1118
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1119
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1120
-                    throw new EE_Error(
1121
-                        sprintf(
1122
-                            __(
1123
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1124
-                                'event_espresso'
1125
-                            ),
1126
-                            $selection_and_datatype,
1127
-                            $alias
1128
-                        )
1129
-                    );
1130
-                }
1131
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1132
-                    throw new EE_Error(
1133
-                        sprintf(
1134
-                            esc_html__(
1135
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1136
-                                'event_espresso'
1137
-                            ),
1138
-                            $selection_and_datatype[1],
1139
-                            $selection_and_datatype[0],
1140
-                            $alias,
1141
-                            implode(', ', $this->_valid_wpdb_data_types)
1142
-                        )
1143
-                    );
1144
-                }
1145
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1146
-            }
1147
-            $columns_to_select_string = implode(', ', $select_sql_array);
1148
-        } else {
1149
-            $columns_to_select_string = $columns_to_select;
1150
-        }
1151
-        return $columns_to_select_string;
1152
-    }
1153
-
1154
-
1155
-
1156
-    /**
1157
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1158
-     *
1159
-     * @return string
1160
-     * @throws EE_Error
1161
-     */
1162
-    public function primary_key_name()
1163
-    {
1164
-        return $this->get_primary_key_field()->get_name();
1165
-    }
1166
-
1167
-
1168
-    /**
1169
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1170
-     * If there is no primary key on this model, $id is treated as primary key string
1171
-     *
1172
-     * @param mixed $id int or string, depending on the type of the model's primary key
1173
-     * @return EE_Base_Class
1174
-     * @throws EE_Error
1175
-     */
1176
-    public function get_one_by_ID($id)
1177
-    {
1178
-        if ($this->get_from_entity_map($id)) {
1179
-            return $this->get_from_entity_map($id);
1180
-        }
1181
-        $model_object = $this->get_one(
1182
-            $this->alter_query_params_to_restrict_by_ID(
1183
-                $id,
1184
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1185
-            )
1186
-        );
1187
-        $className = $this->_get_class_name();
1188
-        if ($model_object instanceof $className) {
1189
-            // make sure valid objects get added to the entity map
1190
-            // so that the next call to this method doesn't trigger another trip to the db
1191
-            $this->add_to_entity_map($model_object);
1192
-        }
1193
-        return $model_object;
1194
-    }
1195
-
1196
-
1197
-
1198
-    /**
1199
-     * Alters query parameters to only get items with this ID are returned.
1200
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1201
-     * or could just be a simple primary key ID
1202
-     *
1203
-     * @param int   $id
1204
-     * @param array $query_params
1205
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1206
-     * @throws EE_Error
1207
-     */
1208
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1209
-    {
1210
-        if (! isset($query_params[0])) {
1211
-            $query_params[0] = array();
1212
-        }
1213
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1214
-        if ($conditions_from_id === null) {
1215
-            $query_params[0][ $this->primary_key_name() ] = $id;
1216
-        } else {
1217
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1218
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1219
-        }
1220
-        return $query_params;
1221
-    }
1222
-
1223
-
1224
-
1225
-    /**
1226
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1227
-     * array. If no item is found, null is returned.
1228
-     *
1229
-     * @param array $query_params like EEM_Base's $query_params variable.
1230
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1231
-     * @throws EE_Error
1232
-     */
1233
-    public function get_one($query_params = array())
1234
-    {
1235
-        if (! is_array($query_params)) {
1236
-            EE_Error::doing_it_wrong(
1237
-                'EEM_Base::get_one',
1238
-                sprintf(
1239
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1240
-                    gettype($query_params)
1241
-                ),
1242
-                '4.6.0'
1243
-            );
1244
-            $query_params = array();
1245
-        }
1246
-        $query_params['limit'] = 1;
1247
-        $items = $this->get_all($query_params);
1248
-        if (empty($items)) {
1249
-            return null;
1250
-        }
1251
-        return array_shift($items);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the next x number of items in sequence from the given value as
1258
-     * 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 next_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(
1280
-            $current_field_value,
1281
-            '>',
1282
-            $field_to_order_by,
1283
-            $limit,
1284
-            $query_params,
1285
-            $columns_to_select
1286
-        );
1287
-    }
1288
-
1289
-
1290
-
1291
-    /**
1292
-     * Returns the previous x number of items in sequence from the given value
1293
-     * as found in the database matching the given query conditions.
1294
-     *
1295
-     * @param mixed $current_field_value    Value used for the reference point.
1296
-     * @param null  $field_to_order_by      What field is used for the
1297
-     *                                      reference point.
1298
-     * @param int   $limit                  How many to return.
1299
-     * @param array $query_params           Extra conditions on the query.
1300
-     * @param null  $columns_to_select      If left null, then an array of
1301
-     *                                      EE_Base_Class objects is returned,
1302
-     *                                      otherwise you can indicate just the
1303
-     *                                      columns you want returned.
1304
-     * @return EE_Base_Class[]|array
1305
-     * @throws EE_Error
1306
-     */
1307
-    public function previous_x(
1308
-        $current_field_value,
1309
-        $field_to_order_by = null,
1310
-        $limit = 1,
1311
-        $query_params = array(),
1312
-        $columns_to_select = null
1313
-    ) {
1314
-        return $this->_get_consecutive(
1315
-            $current_field_value,
1316
-            '<',
1317
-            $field_to_order_by,
1318
-            $limit,
1319
-            $query_params,
1320
-            $columns_to_select
1321
-        );
1322
-    }
1323
-
1324
-
1325
-
1326
-    /**
1327
-     * Returns the next item in sequence from the given value as found in the
1328
-     * database matching the given query conditions.
1329
-     *
1330
-     * @param mixed $current_field_value    Value used for the reference point.
1331
-     * @param null  $field_to_order_by      What field is used for the
1332
-     *                                      reference point.
1333
-     * @param array $query_params           Extra conditions on the query.
1334
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1335
-     *                                      object is returned, otherwise you
1336
-     *                                      can indicate just the columns you
1337
-     *                                      want and a single array indexed by
1338
-     *                                      the columns will be returned.
1339
-     * @return EE_Base_Class|null|array()
1340
-     * @throws EE_Error
1341
-     */
1342
-    public function next(
1343
-        $current_field_value,
1344
-        $field_to_order_by = null,
1345
-        $query_params = array(),
1346
-        $columns_to_select = null
1347
-    ) {
1348
-        $results = $this->_get_consecutive(
1349
-            $current_field_value,
1350
-            '>',
1351
-            $field_to_order_by,
1352
-            1,
1353
-            $query_params,
1354
-            $columns_to_select
1355
-        );
1356
-        return empty($results) ? null : reset($results);
1357
-    }
1358
-
1359
-
1360
-
1361
-    /**
1362
-     * Returns the previous item in sequence from the given value as found in
1363
-     * the database matching the given query conditions.
1364
-     *
1365
-     * @param mixed $current_field_value    Value used for the reference point.
1366
-     * @param null  $field_to_order_by      What field is used for the
1367
-     *                                      reference point.
1368
-     * @param array $query_params           Extra conditions on the query.
1369
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1370
-     *                                      object is returned, otherwise you
1371
-     *                                      can indicate just the columns you
1372
-     *                                      want and a single array indexed by
1373
-     *                                      the columns will be returned.
1374
-     * @return EE_Base_Class|null|array()
1375
-     * @throws EE_Error
1376
-     */
1377
-    public function previous(
1378
-        $current_field_value,
1379
-        $field_to_order_by = null,
1380
-        $query_params = array(),
1381
-        $columns_to_select = null
1382
-    ) {
1383
-        $results = $this->_get_consecutive(
1384
-            $current_field_value,
1385
-            '<',
1386
-            $field_to_order_by,
1387
-            1,
1388
-            $query_params,
1389
-            $columns_to_select
1390
-        );
1391
-        return empty($results) ? null : reset($results);
1392
-    }
1393
-
1394
-
1395
-
1396
-    /**
1397
-     * Returns the a consecutive number of items in sequence from the given
1398
-     * value as found in the database matching the given query conditions.
1399
-     *
1400
-     * @param mixed  $current_field_value   Value used for the reference point.
1401
-     * @param string $operand               What operand is used for the sequence.
1402
-     * @param string $field_to_order_by     What field is used for the reference point.
1403
-     * @param int    $limit                 How many to return.
1404
-     * @param array  $query_params          Extra conditions on the query.
1405
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1406
-     *                                      otherwise you can indicate just the columns you want returned.
1407
-     * @return EE_Base_Class[]|array
1408
-     * @throws EE_Error
1409
-     */
1410
-    protected function _get_consecutive(
1411
-        $current_field_value,
1412
-        $operand = '>',
1413
-        $field_to_order_by = null,
1414
-        $limit = 1,
1415
-        $query_params = array(),
1416
-        $columns_to_select = null
1417
-    ) {
1418
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1419
-        if (empty($field_to_order_by)) {
1420
-            if ($this->has_primary_key_field()) {
1421
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1422
-            } else {
1423
-                if (WP_DEBUG) {
1424
-                    throw new EE_Error(__(
1425
-                        '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).',
1426
-                        'event_espresso'
1427
-                    ));
1428
-                }
1429
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1430
-                return array();
1431
-            }
1432
-        }
1433
-        if (! is_array($query_params)) {
1434
-            EE_Error::doing_it_wrong(
1435
-                'EEM_Base::_get_consecutive',
1436
-                sprintf(
1437
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1438
-                    gettype($query_params)
1439
-                ),
1440
-                '4.6.0'
1441
-            );
1442
-            $query_params = array();
1443
-        }
1444
-        // let's add the where query param for consecutive look up.
1445
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1446
-        $query_params['limit'] = $limit;
1447
-        // set direction
1448
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1449
-        $query_params['order_by'] = $operand === '>'
1450
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1451
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1452
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1453
-        if (empty($columns_to_select)) {
1454
-            return $this->get_all($query_params);
1455
-        }
1456
-        // getting just the fields
1457
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1458
-    }
1459
-
1460
-
1461
-
1462
-    /**
1463
-     * This sets the _timezone property after model object has been instantiated.
1464
-     *
1465
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1466
-     */
1467
-    public function set_timezone($timezone)
1468
-    {
1469
-        if ($timezone !== null) {
1470
-            $this->_timezone = $timezone;
1471
-        }
1472
-        // note we need to loop through relations and set the timezone on those objects as well.
1473
-        foreach ($this->_model_relations as $relation) {
1474
-            $relation->set_timezone($timezone);
1475
-        }
1476
-        // and finally we do the same for any datetime fields
1477
-        foreach ($this->_fields as $field) {
1478
-            if ($field instanceof EE_Datetime_Field) {
1479
-                $field->set_timezone($timezone);
1480
-            }
1481
-        }
1482
-    }
1483
-
1484
-
1485
-
1486
-    /**
1487
-     * This just returns whatever is set for the current timezone.
1488
-     *
1489
-     * @access public
1490
-     * @return string
1491
-     */
1492
-    public function get_timezone()
1493
-    {
1494
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1495
-        if (empty($this->_timezone)) {
1496
-            foreach ($this->_fields as $field) {
1497
-                if ($field instanceof EE_Datetime_Field) {
1498
-                    $this->set_timezone($field->get_timezone());
1499
-                    break;
1500
-                }
1501
-            }
1502
-        }
1503
-        // if timezone STILL empty then return the default timezone for the site.
1504
-        if (empty($this->_timezone)) {
1505
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1506
-        }
1507
-        return $this->_timezone;
1508
-    }
1509
-
1510
-
1511
-
1512
-    /**
1513
-     * This returns the date formats set for the given field name and also ensures that
1514
-     * $this->_timezone property is set correctly.
1515
-     *
1516
-     * @since 4.6.x
1517
-     * @param string $field_name The name of the field the formats are being retrieved for.
1518
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1519
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1520
-     * @return array formats in an array with the date format first, and the time format last.
1521
-     */
1522
-    public function get_formats_for($field_name, $pretty = false)
1523
-    {
1524
-        $field_settings = $this->field_settings_for($field_name);
1525
-        // if not a valid EE_Datetime_Field then throw error
1526
-        if (! $field_settings instanceof EE_Datetime_Field) {
1527
-            throw new EE_Error(sprintf(__(
1528
-                '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.',
1529
-                'event_espresso'
1530
-            ), $field_name));
1531
-        }
1532
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1533
-        // the field.
1534
-        $this->_timezone = $field_settings->get_timezone();
1535
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1536
-    }
1537
-
1538
-
1539
-
1540
-    /**
1541
-     * This returns the current time in a format setup for a query on this model.
1542
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1543
-     * it will return:
1544
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1545
-     *  NOW
1546
-     *  - or a unix timestamp (equivalent to time())
1547
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1548
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1549
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1550
-     * @since 4.6.x
1551
-     * @param string $field_name       The field the current time is needed for.
1552
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1553
-     *                                 formatted string matching the set format for the field in the set timezone will
1554
-     *                                 be returned.
1555
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1556
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1557
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1558
-     *                                 exception is triggered.
1559
-     */
1560
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1561
-    {
1562
-        $formats = $this->get_formats_for($field_name);
1563
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1564
-        if ($timestamp) {
1565
-            return $DateTime->format('U');
1566
-        }
1567
-        // not returning timestamp, so return formatted string in timezone.
1568
-        switch ($what) {
1569
-            case 'time':
1570
-                return $DateTime->format($formats[1]);
1571
-                break;
1572
-            case 'date':
1573
-                return $DateTime->format($formats[0]);
1574
-                break;
1575
-            default:
1576
-                return $DateTime->format(implode(' ', $formats));
1577
-                break;
1578
-        }
1579
-    }
1580
-
1581
-
1582
-
1583
-    /**
1584
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1585
-     * for the model are.  Returns a DateTime object.
1586
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1587
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1588
-     * ignored.
1589
-     *
1590
-     * @param string $field_name      The field being setup.
1591
-     * @param string $timestring      The date time string being used.
1592
-     * @param string $incoming_format The format for the time string.
1593
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1594
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1595
-     *                                format is
1596
-     *                                'U', this is ignored.
1597
-     * @return DateTime
1598
-     * @throws EE_Error
1599
-     */
1600
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1601
-    {
1602
-        // just using this to ensure the timezone is set correctly internally
1603
-        $this->get_formats_for($field_name);
1604
-        // load EEH_DTT_Helper
1605
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1606
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1607
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1608
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1609
-    }
1610
-
1611
-
1612
-
1613
-    /**
1614
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1615
-     *
1616
-     * @return EE_Table_Base[]
1617
-     */
1618
-    public function get_tables()
1619
-    {
1620
-        return $this->_tables;
1621
-    }
1622
-
1623
-
1624
-
1625
-    /**
1626
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1627
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1628
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1629
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1630
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1631
-     * model object with EVT_ID = 1
1632
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1633
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1634
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1635
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1636
-     * are not specified)
1637
-     *
1638
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1639
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1640
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1641
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1642
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1643
-     *                                         ID=34, we'd use this method as follows:
1644
-     *                                         EEM_Transaction::instance()->update(
1645
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1646
-     *                                         array(array('TXN_ID'=>34)));
1647
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1648
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1649
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1650
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1651
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1652
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1653
-     *                                         TRUE, it is assumed that you've already called
1654
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1655
-     *                                         malicious javascript. However, if
1656
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1657
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1658
-     *                                         and every other field, before insertion. We provide this parameter
1659
-     *                                         because model objects perform their prepare_for_set function on all
1660
-     *                                         their values, and so don't need to be called again (and in many cases,
1661
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1662
-     *                                         prepare_for_set method...)
1663
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1664
-     *                                         in this model's entity map according to $fields_n_values that match
1665
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1666
-     *                                         by setting this to FALSE, but be aware that model objects being used
1667
-     *                                         could get out-of-sync with the database
1668
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1669
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1670
-     *                                         bad)
1671
-     * @throws EE_Error
1672
-     */
1673
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674
-    {
1675
-        if (! is_array($query_params)) {
1676
-            EE_Error::doing_it_wrong(
1677
-                'EEM_Base::update',
1678
-                sprintf(
1679
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1680
-                    gettype($query_params)
1681
-                ),
1682
-                '4.6.0'
1683
-            );
1684
-            $query_params = array();
1685
-        }
1686
-        /**
1687
-         * Action called before a model update call has been made.
1688
-         *
1689
-         * @param EEM_Base $model
1690
-         * @param array    $fields_n_values the updated fields and their new values
1691
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1692
-         */
1693
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1694
-        /**
1695
-         * Filters the fields about to be updated given the query parameters. You can provide the
1696
-         * $query_params to $this->get_all() to find exactly which records will be updated
1697
-         *
1698
-         * @param array    $fields_n_values fields and their new values
1699
-         * @param EEM_Base $model           the model being queried
1700
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1701
-         */
1702
-        $fields_n_values = (array) apply_filters(
1703
-            'FHEE__EEM_Base__update__fields_n_values',
1704
-            $fields_n_values,
1705
-            $this,
1706
-            $query_params
1707
-        );
1708
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1709
-        // to do that, for each table, verify that it's PK isn't null.
1710
-        $tables = $this->get_tables();
1711
-        // 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
1712
-        // NOTE: we should make this code more efficient by NOT querying twice
1713
-        // before the real update, but that needs to first go through ALPHA testing
1714
-        // as it's dangerous. says Mike August 8 2014
1715
-        // we want to make sure the default_where strategy is ignored
1716
-        $this->_ignore_where_strategy = true;
1717
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1718
-        foreach ($wpdb_select_results as $wpdb_result) {
1719
-            // type cast stdClass as array
1720
-            $wpdb_result = (array) $wpdb_result;
1721
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1722
-            if ($this->has_primary_key_field()) {
1723
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1724
-            } else {
1725
-                // 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)
1726
-                $main_table_pk_value = null;
1727
-            }
1728
-            // 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
1729
-            // 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
1730
-            if (count($tables) > 1) {
1731
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1732
-                // in that table, and so we'll want to insert one
1733
-                foreach ($tables as $table_obj) {
1734
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1735
-                    // if there is no private key for this table on the results, it means there's no entry
1736
-                    // in this table, right? so insert a row in the current table, using any fields available
1737
-                    if (
1738
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1739
-                           && $wpdb_result[ $this_table_pk_column ])
1740
-                    ) {
1741
-                        $success = $this->_insert_into_specific_table(
1742
-                            $table_obj,
1743
-                            $fields_n_values,
1744
-                            $main_table_pk_value
1745
-                        );
1746
-                        // if we died here, report the error
1747
-                        if (! $success) {
1748
-                            return false;
1749
-                        }
1750
-                    }
1751
-                }
1752
-            }
1753
-            //              //and now check that if we have cached any models by that ID on the model, that
1754
-            //              //they also get updated properly
1755
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1756
-            //              if( $model_object ){
1757
-            //                  foreach( $fields_n_values as $field => $value ){
1758
-            //                      $model_object->set($field, $value);
1759
-            // let's make sure default_where strategy is followed now
1760
-            $this->_ignore_where_strategy = false;
1761
-        }
1762
-        // if we want to keep model objects in sync, AND
1763
-        // if this wasn't called from a model object (to update itself)
1764
-        // then we want to make sure we keep all the existing
1765
-        // model objects in sync with the db
1766
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1767
-            if ($this->has_primary_key_field()) {
1768
-                $model_objs_affected_ids = $this->get_col($query_params);
1769
-            } else {
1770
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1771
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1772
-                $model_objs_affected_ids = array();
1773
-                foreach ($models_affected_key_columns as $row) {
1774
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1775
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1776
-                }
1777
-            }
1778
-            if (! $model_objs_affected_ids) {
1779
-                // wait wait wait- if nothing was affected let's stop here
1780
-                return 0;
1781
-            }
1782
-            foreach ($model_objs_affected_ids as $id) {
1783
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1784
-                if ($model_obj_in_entity_map) {
1785
-                    foreach ($fields_n_values as $field => $new_value) {
1786
-                        $model_obj_in_entity_map->set($field, $new_value);
1787
-                    }
1788
-                }
1789
-            }
1790
-            // if there is a primary key on this model, we can now do a slight optimization
1791
-            if ($this->has_primary_key_field()) {
1792
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1793
-                $query_params = array(
1794
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1795
-                    'limit'                    => count($model_objs_affected_ids),
1796
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1797
-                );
1798
-            }
1799
-        }
1800
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1801
-        $SQL = "UPDATE "
1802
-               . $model_query_info->get_full_join_sql()
1803
-               . " SET "
1804
-               . $this->_construct_update_sql($fields_n_values)
1805
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1806
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1807
-        /**
1808
-         * Action called after a model update call has been made.
1809
-         *
1810
-         * @param EEM_Base $model
1811
-         * @param array    $fields_n_values the updated fields and their new values
1812
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1813
-         * @param int      $rows_affected
1814
-         */
1815
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1816
-        return $rows_affected;// how many supposedly got updated
1817
-    }
1818
-
1819
-
1820
-
1821
-    /**
1822
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1823
-     * are teh values of the field specified (or by default the primary key field)
1824
-     * that matched the query params. Note that you should pass the name of the
1825
-     * model FIELD, not the database table's column name.
1826
-     *
1827
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1828
-     * @param string $field_to_select
1829
-     * @return array just like $wpdb->get_col()
1830
-     * @throws EE_Error
1831
-     */
1832
-    public function get_col($query_params = array(), $field_to_select = null)
1833
-    {
1834
-        if ($field_to_select) {
1835
-            $field = $this->field_settings_for($field_to_select);
1836
-        } elseif ($this->has_primary_key_field()) {
1837
-            $field = $this->get_primary_key_field();
1838
-        } else {
1839
-            // no primary key, just grab the first column
1840
-            $field = reset($this->field_settings());
1841
-        }
1842
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1843
-        $select_expressions = $field->get_qualified_column();
1844
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1845
-        return $this->_do_wpdb_query('get_col', array($SQL));
1846
-    }
1847
-
1848
-
1849
-
1850
-    /**
1851
-     * Returns a single column value for a single row from the database
1852
-     *
1853
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1854
-     * @param string $field_to_select @see EEM_Base::get_col()
1855
-     * @return string
1856
-     * @throws EE_Error
1857
-     */
1858
-    public function get_var($query_params = array(), $field_to_select = null)
1859
-    {
1860
-        $query_params['limit'] = 1;
1861
-        $col = $this->get_col($query_params, $field_to_select);
1862
-        if (! empty($col)) {
1863
-            return reset($col);
1864
-        }
1865
-        return null;
1866
-    }
1867
-
1868
-
1869
-
1870
-    /**
1871
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1872
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1873
-     * injection, but currently no further filtering is done
1874
-     *
1875
-     * @global      $wpdb
1876
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1877
-     *                               be updated to in the DB
1878
-     * @return string of SQL
1879
-     * @throws EE_Error
1880
-     */
1881
-    public function _construct_update_sql($fields_n_values)
1882
-    {
1883
-        /** @type WPDB $wpdb */
1884
-        global $wpdb;
1885
-        $cols_n_values = array();
1886
-        foreach ($fields_n_values as $field_name => $value) {
1887
-            $field_obj = $this->field_settings_for($field_name);
1888
-            // if the value is NULL, we want to assign the value to that.
1889
-            // wpdb->prepare doesn't really handle that properly
1890
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1891
-            $value_sql = $prepared_value === null ? 'NULL'
1892
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1893
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1894
-        }
1895
-        return implode(",", $cols_n_values);
1896
-    }
1897
-
1898
-
1899
-
1900
-    /**
1901
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1902
-     * Performs a HARD delete, meaning the database row should always be removed,
1903
-     * not just have a flag field on it switched
1904
-     * Wrapper for EEM_Base::delete_permanently()
1905
-     *
1906
-     * @param mixed $id
1907
-     * @param boolean $allow_blocking
1908
-     * @return int the number of rows deleted
1909
-     * @throws EE_Error
1910
-     */
1911
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1912
-    {
1913
-        return $this->delete_permanently(
1914
-            array(
1915
-                array($this->get_primary_key_field()->get_name() => $id),
1916
-                'limit' => 1,
1917
-            ),
1918
-            $allow_blocking
1919
-        );
1920
-    }
1921
-
1922
-
1923
-
1924
-    /**
1925
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1926
-     * Wrapper for EEM_Base::delete()
1927
-     *
1928
-     * @param mixed $id
1929
-     * @param boolean $allow_blocking
1930
-     * @return int the number of rows deleted
1931
-     * @throws EE_Error
1932
-     */
1933
-    public function delete_by_ID($id, $allow_blocking = true)
1934
-    {
1935
-        return $this->delete(
1936
-            array(
1937
-                array($this->get_primary_key_field()->get_name() => $id),
1938
-                'limit' => 1,
1939
-            ),
1940
-            $allow_blocking
1941
-        );
1942
-    }
1943
-
1944
-
1945
-
1946
-    /**
1947
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1948
-     * meaning if the model has a field that indicates its been "trashed" or
1949
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1950
-     *
1951
-     * @see EEM_Base::delete_permanently
1952
-     * @param array   $query_params
1953
-     * @param boolean $allow_blocking
1954
-     * @return int how many rows got deleted
1955
-     * @throws EE_Error
1956
-     */
1957
-    public function delete($query_params, $allow_blocking = true)
1958
-    {
1959
-        return $this->delete_permanently($query_params, $allow_blocking);
1960
-    }
1961
-
1962
-
1963
-
1964
-    /**
1965
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1966
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1967
-     * as archived, not actually deleted
1968
-     *
1969
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1970
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1971
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1972
-     *                                deletes regardless of other objects which may depend on it. Its generally
1973
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1974
-     *                                DB
1975
-     * @return int how many rows got deleted
1976
-     * @throws EE_Error
1977
-     */
1978
-    public function delete_permanently($query_params, $allow_blocking = true)
1979
-    {
1980
-        /**
1981
-         * Action called just before performing a real deletion query. You can use the
1982
-         * model and its $query_params to find exactly which items will be deleted
1983
-         *
1984
-         * @param EEM_Base $model
1985
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1986
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1987
-         *                                 to block (prevent) this deletion
1988
-         */
1989
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1990
-        // some MySQL databases may be running safe mode, which may restrict
1991
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1992
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1993
-        // to delete them
1994
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1995
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1996
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1997
-            $columns_and_ids_for_deleting
1998
-        );
1999
-        /**
2000
-         * Allows client code to act on the items being deleted before the query is actually executed.
2001
-         *
2002
-         * @param EEM_Base $this  The model instance being acted on.
2003
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2004
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
2005
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2006
-         *                                                  derived from the incoming query parameters.
2007
-         *                                                  @see details on the structure of this array in the phpdocs
2008
-         *                                                  for the `_get_ids_for_delete_method`
2009
-         *
2010
-         */
2011
-        do_action(
2012
-            'AHEE__EEM_Base__delete__before_query',
2013
-            $this,
2014
-            $query_params,
2015
-            $allow_blocking,
2016
-            $columns_and_ids_for_deleting
2017
-        );
2018
-        if ($deletion_where_query_part) {
2019
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2020
-            $table_aliases = array_keys($this->_tables);
2021
-            $SQL = "DELETE "
2022
-                   . implode(", ", $table_aliases)
2023
-                   . " FROM "
2024
-                   . $model_query_info->get_full_join_sql()
2025
-                   . " WHERE "
2026
-                   . $deletion_where_query_part;
2027
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2028
-        } else {
2029
-            $rows_deleted = 0;
2030
-        }
2031
-
2032
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2033
-        // there was no error with the delete query.
2034
-        if (
2035
-            $this->has_primary_key_field()
2036
-            && $rows_deleted !== false
2037
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2038
-        ) {
2039
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2040
-            foreach ($ids_for_removal as $id) {
2041
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2042
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2043
-                }
2044
-            }
2045
-
2046
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2047
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2048
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2049
-            // (although it is possible).
2050
-            // Note this can be skipped by using the provided filter and returning false.
2051
-            if (
2052
-                apply_filters(
2053
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2054
-                    ! $this instanceof EEM_Extra_Meta,
2055
-                    $this
2056
-                )
2057
-            ) {
2058
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2059
-                    0 => array(
2060
-                        'EXM_type' => $this->get_this_model_name(),
2061
-                        'OBJ_ID'   => array(
2062
-                            'IN',
2063
-                            $ids_for_removal
2064
-                        )
2065
-                    )
2066
-                ));
2067
-            }
2068
-        }
2069
-
2070
-        /**
2071
-         * Action called just after performing a real deletion query. Although at this point the
2072
-         * items should have been deleted
2073
-         *
2074
-         * @param EEM_Base $model
2075
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2076
-         * @param int      $rows_deleted
2077
-         */
2078
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2079
-        return $rows_deleted;// how many supposedly got deleted
2080
-    }
2081
-
2082
-
2083
-
2084
-    /**
2085
-     * Checks all the relations that throw error messages when there are blocking related objects
2086
-     * for related model objects. If there are any related model objects on those relations,
2087
-     * adds an EE_Error, and return true
2088
-     *
2089
-     * @param EE_Base_Class|int $this_model_obj_or_id
2090
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2091
-     *                                                 should be ignored when determining whether there are related
2092
-     *                                                 model objects which block this model object's deletion. Useful
2093
-     *                                                 if you know A is related to B and are considering deleting A,
2094
-     *                                                 but want to see if A has any other objects blocking its deletion
2095
-     *                                                 before removing the relation between A and B
2096
-     * @return boolean
2097
-     * @throws EE_Error
2098
-     */
2099
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2100
-    {
2101
-        // first, if $ignore_this_model_obj was supplied, get its model
2102
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2103
-            $ignored_model = $ignore_this_model_obj->get_model();
2104
-        } else {
2105
-            $ignored_model = null;
2106
-        }
2107
-        // now check all the relations of $this_model_obj_or_id and see if there
2108
-        // are any related model objects blocking it?
2109
-        $is_blocked = false;
2110
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2111
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2112
-                // if $ignore_this_model_obj was supplied, then for the query
2113
-                // on that model needs to be told to ignore $ignore_this_model_obj
2114
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2115
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2116
-                        array(
2117
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2118
-                                '!=',
2119
-                                $ignore_this_model_obj->ID(),
2120
-                            ),
2121
-                        ),
2122
-                    ));
2123
-                } else {
2124
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2125
-                }
2126
-                if ($related_model_objects) {
2127
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2128
-                    $is_blocked = true;
2129
-                }
2130
-            }
2131
-        }
2132
-        return $is_blocked;
2133
-    }
2134
-
2135
-
2136
-    /**
2137
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2138
-     * @param array $row_results_for_deleting
2139
-     * @param bool  $allow_blocking
2140
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2141
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2142
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2143
-     *                 deleted. Example:
2144
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2145
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2146
-     *                 where each element is a group of columns and values that get deleted. Example:
2147
-     *                      array(
2148
-     *                          0 => array(
2149
-     *                              'Term_Relationship.object_id' => 1
2150
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2151
-     *                          ),
2152
-     *                          1 => array(
2153
-     *                              'Term_Relationship.object_id' => 1
2154
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2155
-     *                          )
2156
-     *                      )
2157
-     * @throws EE_Error
2158
-     */
2159
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2160
-    {
2161
-        $ids_to_delete_indexed_by_column = array();
2162
-        if ($this->has_primary_key_field()) {
2163
-            $primary_table = $this->_get_main_table();
2164
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2165
-            $other_tables = $this->_get_other_tables();
2166
-            $ids_to_delete_indexed_by_column = $query = array();
2167
-            foreach ($row_results_for_deleting as $item_to_delete) {
2168
-                // before we mark this item for deletion,
2169
-                // make sure there's no related entities blocking its deletion (if we're checking)
2170
-                if (
2171
-                    $allow_blocking
2172
-                    && $this->delete_is_blocked_by_related_models(
2173
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2174
-                    )
2175
-                ) {
2176
-                    continue;
2177
-                }
2178
-                // primary table deletes
2179
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2180
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2181
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2182
-                }
2183
-            }
2184
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
-            $fields = $this->get_combined_primary_key_fields();
2186
-            foreach ($row_results_for_deleting as $item_to_delete) {
2187
-                $ids_to_delete_indexed_by_column_for_row = array();
2188
-                foreach ($fields as $cpk_field) {
2189
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2190
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2191
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2192
-                    }
2193
-                }
2194
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2195
-            }
2196
-        } else {
2197
-            // so there's no primary key and no combined key...
2198
-            // sorry, can't help you
2199
-            throw new EE_Error(
2200
-                sprintf(
2201
-                    __(
2202
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2203
-                        "event_espresso"
2204
-                    ),
2205
-                    get_class($this)
2206
-                )
2207
-            );
2208
-        }
2209
-        return $ids_to_delete_indexed_by_column;
2210
-    }
2211
-
2212
-
2213
-    /**
2214
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2215
-     * the corresponding query_part for the query performing the delete.
2216
-     *
2217
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2218
-     * @return string
2219
-     * @throws EE_Error
2220
-     */
2221
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2222
-    {
2223
-        $query_part = '';
2224
-        if (empty($ids_to_delete_indexed_by_column)) {
2225
-            return $query_part;
2226
-        } elseif ($this->has_primary_key_field()) {
2227
-            $query = array();
2228
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2229
-                // make sure we have unique $ids
2230
-                $ids = array_unique($ids);
2231
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2232
-            }
2233
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2234
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2235
-            $ways_to_identify_a_row = array();
2236
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2237
-                $values_for_each_combined_primary_key_for_a_row = array();
2238
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2239
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2240
-                }
2241
-                $ways_to_identify_a_row[] = '('
2242
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2243
-                                            . ')';
2244
-            }
2245
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2246
-        }
2247
-        return $query_part;
2248
-    }
2249
-
2250
-
2251
-
2252
-    /**
2253
-     * Gets the model field by the fully qualified name
2254
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2255
-     * @return EE_Model_Field_Base
2256
-     */
2257
-    public function get_field_by_column($qualified_column_name)
2258
-    {
2259
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2260
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2261
-                return $field_obj;
2262
-            }
2263
-        }
2264
-        throw new EE_Error(
2265
-            sprintf(
2266
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2267
-                $this->get_this_model_name(),
2268
-                $qualified_column_name
2269
-            )
2270
-        );
2271
-    }
2272
-
2273
-
2274
-
2275
-    /**
2276
-     * Count all the rows that match criteria the model query params.
2277
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2278
-     * column
2279
-     *
2280
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2281
-     * @param string $field_to_count field on model to count by (not column name)
2282
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2283
-     *                               that by the setting $distinct to TRUE;
2284
-     * @return int
2285
-     * @throws EE_Error
2286
-     */
2287
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2288
-    {
2289
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2290
-        if ($field_to_count) {
2291
-            $field_obj = $this->field_settings_for($field_to_count);
2292
-            $column_to_count = $field_obj->get_qualified_column();
2293
-        } elseif ($this->has_primary_key_field()) {
2294
-            $pk_field_obj = $this->get_primary_key_field();
2295
-            $column_to_count = $pk_field_obj->get_qualified_column();
2296
-        } else {
2297
-            // there's no primary key
2298
-            // if we're counting distinct items, and there's no primary key,
2299
-            // we need to list out the columns for distinction;
2300
-            // otherwise we can just use star
2301
-            if ($distinct) {
2302
-                $columns_to_use = array();
2303
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2304
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2305
-                }
2306
-                $column_to_count = implode(',', $columns_to_use);
2307
-            } else {
2308
-                $column_to_count = '*';
2309
-            }
2310
-        }
2311
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2312
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2314
-    }
2315
-
2316
-
2317
-
2318
-    /**
2319
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2320
-     *
2321
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2322
-     * @param string $field_to_sum name of field (array key in $_fields array)
2323
-     * @return float
2324
-     * @throws EE_Error
2325
-     */
2326
-    public function sum($query_params, $field_to_sum = null)
2327
-    {
2328
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2329
-        if ($field_to_sum) {
2330
-            $field_obj = $this->field_settings_for($field_to_sum);
2331
-        } else {
2332
-            $field_obj = $this->get_primary_key_field();
2333
-        }
2334
-        $column_to_count = $field_obj->get_qualified_column();
2335
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2336
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2337
-        $data_type = $field_obj->get_wpdb_data_type();
2338
-        if ($data_type === '%d' || $data_type === '%s') {
2339
-            return (float) $return_value;
2340
-        }
2341
-        // must be %f
2342
-        return (float) $return_value;
2343
-    }
2344
-
2345
-
2346
-
2347
-    /**
2348
-     * Just calls the specified method on $wpdb with the given arguments
2349
-     * Consolidates a little extra error handling code
2350
-     *
2351
-     * @param string $wpdb_method
2352
-     * @param array  $arguments_to_provide
2353
-     * @throws EE_Error
2354
-     * @global wpdb  $wpdb
2355
-     * @return mixed
2356
-     */
2357
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2358
-    {
2359
-        // if we're in maintenance mode level 2, DON'T run any queries
2360
-        // because level 2 indicates the database needs updating and
2361
-        // is probably out of sync with the code
2362
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2363
-            throw new EE_Error(sprintf(__(
2364
-                "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.",
2365
-                "event_espresso"
2366
-            )));
2367
-        }
2368
-        /** @type WPDB $wpdb */
2369
-        global $wpdb;
2370
-        if (! method_exists($wpdb, $wpdb_method)) {
2371
-            throw new EE_Error(sprintf(__(
2372
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2373
-                'event_espresso'
2374
-            ), $wpdb_method));
2375
-        }
2376
-        if (WP_DEBUG) {
2377
-            $old_show_errors_value = $wpdb->show_errors;
2378
-            $wpdb->show_errors(false);
2379
-        }
2380
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2381
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2382
-        if (WP_DEBUG) {
2383
-            $wpdb->show_errors($old_show_errors_value);
2384
-            if (! empty($wpdb->last_error)) {
2385
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2386
-            }
2387
-            if ($result === false) {
2388
-                throw new EE_Error(sprintf(__(
2389
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2390
-                    'event_espresso'
2391
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2392
-            }
2393
-        } elseif ($result === false) {
2394
-            EE_Error::add_error(
2395
-                sprintf(
2396
-                    __(
2397
-                        '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"',
2398
-                        'event_espresso'
2399
-                    ),
2400
-                    $wpdb_method,
2401
-                    var_export($arguments_to_provide, true),
2402
-                    $wpdb->last_error
2403
-                ),
2404
-                __FILE__,
2405
-                __FUNCTION__,
2406
-                __LINE__
2407
-            );
2408
-        }
2409
-        return $result;
2410
-    }
2411
-
2412
-
2413
-
2414
-    /**
2415
-     * Attempts to run the indicated WPDB method with the provided arguments,
2416
-     * and if there's an error tries to verify the DB is correct. Uses
2417
-     * the static property EEM_Base::$_db_verification_level to determine whether
2418
-     * we should try to fix the EE core db, the addons, or just give up
2419
-     *
2420
-     * @param string $wpdb_method
2421
-     * @param array  $arguments_to_provide
2422
-     * @return mixed
2423
-     */
2424
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2425
-    {
2426
-        /** @type WPDB $wpdb */
2427
-        global $wpdb;
2428
-        $wpdb->last_error = null;
2429
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2430
-        // was there an error running the query? but we don't care on new activations
2431
-        // (we're going to setup the DB anyway on new activations)
2432
-        if (
2433
-            ($result === false || ! empty($wpdb->last_error))
2434
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2435
-        ) {
2436
-            switch (EEM_Base::$_db_verification_level) {
2437
-                case EEM_Base::db_verified_none:
2438
-                    // let's double-check core's DB
2439
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2440
-                    break;
2441
-                case EEM_Base::db_verified_core:
2442
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2443
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2444
-                    break;
2445
-                case EEM_Base::db_verified_addons:
2446
-                    // ummmm... you in trouble
2447
-                    return $result;
2448
-                    break;
2449
-            }
2450
-            if (! empty($error_message)) {
2451
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2452
-                trigger_error($error_message);
2453
-            }
2454
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2455
-        }
2456
-        return $result;
2457
-    }
2458
-
2459
-
2460
-
2461
-    /**
2462
-     * Verifies the EE core database is up-to-date and records that we've done it on
2463
-     * EEM_Base::$_db_verification_level
2464
-     *
2465
-     * @param string $wpdb_method
2466
-     * @param array  $arguments_to_provide
2467
-     * @return string
2468
-     */
2469
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2470
-    {
2471
-        /** @type WPDB $wpdb */
2472
-        global $wpdb;
2473
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2474
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2475
-        $error_message = sprintf(
2476
-            __(
2477
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2478
-                'event_espresso'
2479
-            ),
2480
-            $wpdb->last_error,
2481
-            $wpdb_method,
2482
-            wp_json_encode($arguments_to_provide)
2483
-        );
2484
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2485
-        return $error_message;
2486
-    }
2487
-
2488
-
2489
-
2490
-    /**
2491
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2492
-     * EEM_Base::$_db_verification_level
2493
-     *
2494
-     * @param $wpdb_method
2495
-     * @param $arguments_to_provide
2496
-     * @return string
2497
-     */
2498
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2499
-    {
2500
-        /** @type WPDB $wpdb */
2501
-        global $wpdb;
2502
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2503
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2504
-        $error_message = sprintf(
2505
-            __(
2506
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2507
-                'event_espresso'
2508
-            ),
2509
-            $wpdb->last_error,
2510
-            $wpdb_method,
2511
-            wp_json_encode($arguments_to_provide)
2512
-        );
2513
-        EE_System::instance()->initialize_addons();
2514
-        return $error_message;
2515
-    }
2516
-
2517
-
2518
-
2519
-    /**
2520
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2521
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2522
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2523
-     * ..."
2524
-     *
2525
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2526
-     * @return string
2527
-     */
2528
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2529
-    {
2530
-        return " FROM " . $model_query_info->get_full_join_sql() .
2531
-               $model_query_info->get_where_sql() .
2532
-               $model_query_info->get_group_by_sql() .
2533
-               $model_query_info->get_having_sql() .
2534
-               $model_query_info->get_order_by_sql() .
2535
-               $model_query_info->get_limit_sql();
2536
-    }
2537
-
2538
-
2539
-
2540
-    /**
2541
-     * Set to easily debug the next X queries ran from this model.
2542
-     *
2543
-     * @param int $count
2544
-     */
2545
-    public function show_next_x_db_queries($count = 1)
2546
-    {
2547
-        $this->_show_next_x_db_queries = $count;
2548
-    }
2549
-
2550
-
2551
-
2552
-    /**
2553
-     * @param $sql_query
2554
-     */
2555
-    public function show_db_query_if_previously_requested($sql_query)
2556
-    {
2557
-        if ($this->_show_next_x_db_queries > 0) {
2558
-            echo $sql_query;
2559
-            $this->_show_next_x_db_queries--;
2560
-        }
2561
-    }
2562
-
2563
-
2564
-
2565
-    /**
2566
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2567
-     * There are the 3 cases:
2568
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2569
-     * $otherModelObject has no ID, it is first saved.
2570
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2571
-     * has no ID, it is first saved.
2572
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2573
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2574
-     * join table
2575
-     *
2576
-     * @param        EE_Base_Class                     /int $thisModelObject
2577
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2578
-     * @param string $relationName                     , key in EEM_Base::_relations
2579
-     *                                                 an attendee to a group, you also want to specify which role they
2580
-     *                                                 will have in that group. So you would use this parameter to
2581
-     *                                                 specify array('role-column-name'=>'role-id')
2582
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2583
-     *                                                 to for relation to methods that allow you to further specify
2584
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2585
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2586
-     *                                                 because these will be inserted in any new rows created as well.
2587
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2588
-     * @throws EE_Error
2589
-     */
2590
-    public function add_relationship_to(
2591
-        $id_or_obj,
2592
-        $other_model_id_or_obj,
2593
-        $relationName,
2594
-        $extra_join_model_fields_n_values = array()
2595
-    ) {
2596
-        $relation_obj = $this->related_settings_for($relationName);
2597
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2598
-    }
2599
-
2600
-
2601
-
2602
-    /**
2603
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2604
-     * There are the 3 cases:
2605
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2606
-     * error
2607
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2608
-     * an error
2609
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2610
-     *
2611
-     * @param        EE_Base_Class /int $id_or_obj
2612
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2613
-     * @param string $relationName key in EEM_Base::_relations
2614
-     * @return boolean of success
2615
-     * @throws EE_Error
2616
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2617
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2618
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2619
-     *                             because these will be inserted in any new rows created as well.
2620
-     */
2621
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2622
-    {
2623
-        $relation_obj = $this->related_settings_for($relationName);
2624
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2625
-    }
2626
-
2627
-
2628
-
2629
-    /**
2630
-     * @param mixed           $id_or_obj
2631
-     * @param string          $relationName
2632
-     * @param array           $where_query_params
2633
-     * @param EE_Base_Class[] objects to which relations were removed
2634
-     * @return \EE_Base_Class[]
2635
-     * @throws EE_Error
2636
-     */
2637
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2638
-    {
2639
-        $relation_obj = $this->related_settings_for($relationName);
2640
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2641
-    }
2642
-
2643
-
2644
-
2645
-    /**
2646
-     * Gets all the related items of the specified $model_name, using $query_params.
2647
-     * Note: by default, we remove the "default query params"
2648
-     * because we want to get even deleted items etc.
2649
-     *
2650
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2651
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2652
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2653
-     * @return EE_Base_Class[]
2654
-     * @throws EE_Error
2655
-     */
2656
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2657
-    {
2658
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2659
-        $relation_settings = $this->related_settings_for($model_name);
2660
-        return $relation_settings->get_all_related($model_obj, $query_params);
2661
-    }
2662
-
2663
-
2664
-
2665
-    /**
2666
-     * Deletes all the model objects across the relation indicated by $model_name
2667
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2668
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2669
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2670
-     *
2671
-     * @param EE_Base_Class|int|string $id_or_obj
2672
-     * @param string                   $model_name
2673
-     * @param array                    $query_params
2674
-     * @return int how many deleted
2675
-     * @throws EE_Error
2676
-     */
2677
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2678
-    {
2679
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2680
-        $relation_settings = $this->related_settings_for($model_name);
2681
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2682
-    }
2683
-
2684
-
2685
-
2686
-    /**
2687
-     * Hard deletes all the model objects across the relation indicated by $model_name
2688
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2689
-     * the model objects can't be hard deleted because of blocking related model objects,
2690
-     * just does a soft-delete on them instead.
2691
-     *
2692
-     * @param EE_Base_Class|int|string $id_or_obj
2693
-     * @param string                   $model_name
2694
-     * @param array                    $query_params
2695
-     * @return int how many deleted
2696
-     * @throws EE_Error
2697
-     */
2698
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2699
-    {
2700
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2701
-        $relation_settings = $this->related_settings_for($model_name);
2702
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2703
-    }
2704
-
2705
-
2706
-
2707
-    /**
2708
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2709
-     * unless otherwise specified in the $query_params
2710
-     *
2711
-     * @param        int             /EE_Base_Class $id_or_obj
2712
-     * @param string $model_name     like 'Event', or 'Registration'
2713
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2714
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2715
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2716
-     *                               that by the setting $distinct to TRUE;
2717
-     * @return int
2718
-     * @throws EE_Error
2719
-     */
2720
-    public function count_related(
2721
-        $id_or_obj,
2722
-        $model_name,
2723
-        $query_params = array(),
2724
-        $field_to_count = null,
2725
-        $distinct = false
2726
-    ) {
2727
-        $related_model = $this->get_related_model_obj($model_name);
2728
-        // we're just going to use the query params on the related model's normal get_all query,
2729
-        // except add a condition to say to match the current mod
2730
-        if (! isset($query_params['default_where_conditions'])) {
2731
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2732
-        }
2733
-        $this_model_name = $this->get_this_model_name();
2734
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2735
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2736
-        return $related_model->count($query_params, $field_to_count, $distinct);
2737
-    }
2738
-
2739
-
2740
-
2741
-    /**
2742
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2743
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2744
-     *
2745
-     * @param        int           /EE_Base_Class $id_or_obj
2746
-     * @param string $model_name   like 'Event', or 'Registration'
2747
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2748
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2749
-     * @return float
2750
-     * @throws EE_Error
2751
-     */
2752
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2753
-    {
2754
-        $related_model = $this->get_related_model_obj($model_name);
2755
-        if (! is_array($query_params)) {
2756
-            EE_Error::doing_it_wrong(
2757
-                'EEM_Base::sum_related',
2758
-                sprintf(
2759
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2760
-                    gettype($query_params)
2761
-                ),
2762
-                '4.6.0'
2763
-            );
2764
-            $query_params = array();
2765
-        }
2766
-        // we're just going to use the query params on the related model's normal get_all query,
2767
-        // except add a condition to say to match the current mod
2768
-        if (! isset($query_params['default_where_conditions'])) {
2769
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2770
-        }
2771
-        $this_model_name = $this->get_this_model_name();
2772
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2773
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2774
-        return $related_model->sum($query_params, $field_to_sum);
2775
-    }
2776
-
2777
-
2778
-
2779
-    /**
2780
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2781
-     * $modelObject
2782
-     *
2783
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2784
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2785
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2786
-     * @return EE_Base_Class
2787
-     * @throws EE_Error
2788
-     */
2789
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2790
-    {
2791
-        $query_params['limit'] = 1;
2792
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2793
-        if ($results) {
2794
-            return array_shift($results);
2795
-        }
2796
-        return null;
2797
-    }
2798
-
2799
-
2800
-
2801
-    /**
2802
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2803
-     *
2804
-     * @return string
2805
-     */
2806
-    public function get_this_model_name()
2807
-    {
2808
-        return str_replace("EEM_", "", get_class($this));
2809
-    }
2810
-
2811
-
2812
-
2813
-    /**
2814
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2815
-     *
2816
-     * @return EE_Any_Foreign_Model_Name_Field
2817
-     * @throws EE_Error
2818
-     */
2819
-    public function get_field_containing_related_model_name()
2820
-    {
2821
-        foreach ($this->field_settings(true) as $field) {
2822
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2823
-                $field_with_model_name = $field;
2824
-            }
2825
-        }
2826
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2827
-            throw new EE_Error(sprintf(
2828
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2829
-                $this->get_this_model_name()
2830
-            ));
2831
-        }
2832
-        return $field_with_model_name;
2833
-    }
2834
-
2835
-
2836
-
2837
-    /**
2838
-     * Inserts a new entry into the database, for each table.
2839
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2840
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2841
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2842
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2843
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2844
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2845
-     *
2846
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2847
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2848
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2849
-     *                              of EEM_Base)
2850
-     * @return int|string new primary key on main table that got inserted
2851
-     * @throws EE_Error
2852
-     */
2853
-    public function insert($field_n_values)
2854
-    {
2855
-        /**
2856
-         * Filters the fields and their values before inserting an item using the models
2857
-         *
2858
-         * @param array    $fields_n_values keys are the fields and values are their new values
2859
-         * @param EEM_Base $model           the model used
2860
-         */
2861
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2862
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2863
-            $main_table = $this->_get_main_table();
2864
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2865
-            if ($new_id !== false) {
2866
-                foreach ($this->_get_other_tables() as $other_table) {
2867
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2868
-                }
2869
-            }
2870
-            /**
2871
-             * Done just after attempting to insert a new model object
2872
-             *
2873
-             * @param EEM_Base   $model           used
2874
-             * @param array      $fields_n_values fields and their values
2875
-             * @param int|string the              ID of the newly-inserted model object
2876
-             */
2877
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2878
-            return $new_id;
2879
-        }
2880
-        return false;
2881
-    }
2882
-
2883
-
2884
-
2885
-    /**
2886
-     * Checks that the result would satisfy the unique indexes on this model
2887
-     *
2888
-     * @param array  $field_n_values
2889
-     * @param string $action
2890
-     * @return boolean
2891
-     * @throws EE_Error
2892
-     */
2893
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2894
-    {
2895
-        foreach ($this->unique_indexes() as $index_name => $index) {
2896
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2897
-            if ($this->exists(array($uniqueness_where_params))) {
2898
-                EE_Error::add_error(
2899
-                    sprintf(
2900
-                        __(
2901
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2902
-                            "event_espresso"
2903
-                        ),
2904
-                        $action,
2905
-                        $this->_get_class_name(),
2906
-                        $index_name,
2907
-                        implode(",", $index->field_names()),
2908
-                        http_build_query($uniqueness_where_params)
2909
-                    ),
2910
-                    __FILE__,
2911
-                    __FUNCTION__,
2912
-                    __LINE__
2913
-                );
2914
-                return false;
2915
-            }
2916
-        }
2917
-        return true;
2918
-    }
2919
-
2920
-
2921
-
2922
-    /**
2923
-     * Checks the database for an item that conflicts (ie, if this item were
2924
-     * saved to the DB would break some uniqueness requirement, like a primary key
2925
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2926
-     * can be either an EE_Base_Class or an array of fields n values
2927
-     *
2928
-     * @param EE_Base_Class|array $obj_or_fields_array
2929
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2930
-     *                                                 when looking for conflicts
2931
-     *                                                 (ie, if false, we ignore the model object's primary key
2932
-     *                                                 when finding "conflicts". If true, it's also considered).
2933
-     *                                                 Only works for INT primary key,
2934
-     *                                                 STRING primary keys cannot be ignored
2935
-     * @throws EE_Error
2936
-     * @return EE_Base_Class|array
2937
-     */
2938
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2939
-    {
2940
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2941
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2942
-        } elseif (is_array($obj_or_fields_array)) {
2943
-            $fields_n_values = $obj_or_fields_array;
2944
-        } else {
2945
-            throw new EE_Error(
2946
-                sprintf(
2947
-                    __(
2948
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2949
-                        "event_espresso"
2950
-                    ),
2951
-                    get_class($this),
2952
-                    $obj_or_fields_array
2953
-                )
2954
-            );
2955
-        }
2956
-        $query_params = array();
2957
-        if (
2958
-            $this->has_primary_key_field()
2959
-            && ($include_primary_key
2960
-                || $this->get_primary_key_field()
2961
-                   instanceof
2962
-                   EE_Primary_Key_String_Field)
2963
-            && isset($fields_n_values[ $this->primary_key_name() ])
2964
-        ) {
2965
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2966
-        }
2967
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2968
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2969
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2970
-        }
2971
-        // if there is nothing to base this search on, then we shouldn't find anything
2972
-        if (empty($query_params)) {
2973
-            return array();
2974
-        }
2975
-        return $this->get_one($query_params);
2976
-    }
2977
-
2978
-
2979
-
2980
-    /**
2981
-     * Like count, but is optimized and returns a boolean instead of an int
2982
-     *
2983
-     * @param array $query_params
2984
-     * @return boolean
2985
-     * @throws EE_Error
2986
-     */
2987
-    public function exists($query_params)
2988
-    {
2989
-        $query_params['limit'] = 1;
2990
-        return $this->count($query_params) > 0;
2991
-    }
2992
-
2993
-
2994
-
2995
-    /**
2996
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2997
-     *
2998
-     * @param int|string $id
2999
-     * @return boolean
3000
-     * @throws EE_Error
3001
-     */
3002
-    public function exists_by_ID($id)
3003
-    {
3004
-        return $this->exists(
3005
-            array(
3006
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
3007
-                array(
3008
-                    $this->primary_key_name() => $id,
3009
-                ),
3010
-            )
3011
-        );
3012
-    }
3013
-
3014
-
3015
-
3016
-    /**
3017
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3018
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3019
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3020
-     * on the main table)
3021
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3022
-     * cases where we want to call it directly rather than via insert().
3023
-     *
3024
-     * @access   protected
3025
-     * @param EE_Table_Base $table
3026
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3027
-     *                                       float
3028
-     * @param int           $new_id          for now we assume only int keys
3029
-     * @throws EE_Error
3030
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3031
-     * @return int ID of new row inserted, or FALSE on failure
3032
-     */
3033
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3034
-    {
3035
-        global $wpdb;
3036
-        $insertion_col_n_values = array();
3037
-        $format_for_insertion = array();
3038
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3039
-        foreach ($fields_on_table as $field_name => $field_obj) {
3040
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3041
-            if ($field_obj->is_auto_increment()) {
3042
-                continue;
3043
-            }
3044
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3045
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3046
-            if ($prepared_value !== null) {
3047
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3048
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3049
-            }
3050
-        }
3051
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3052
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3053
-            // so add the fk to the main table as a column
3054
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3055
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3056
-        }
3057
-        // insert the new entry
3058
-        $result = $this->_do_wpdb_query(
3059
-            'insert',
3060
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3061
-        );
3062
-        if ($result === false) {
3063
-            return false;
3064
-        }
3065
-        // ok, now what do we return for the ID of the newly-inserted thing?
3066
-        if ($this->has_primary_key_field()) {
3067
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3068
-                return $wpdb->insert_id;
3069
-            }
3070
-            // it's not an auto-increment primary key, so
3071
-            // it must have been supplied
3072
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3073
-        }
3074
-        // we can't return a  primary key because there is none. instead return
3075
-        // a unique string indicating this model
3076
-        return $this->get_index_primary_key_string($fields_n_values);
3077
-    }
3078
-
3079
-
3080
-
3081
-    /**
3082
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3083
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3084
-     * and there is no default, we pass it along. WPDB will take care of it)
3085
-     *
3086
-     * @param EE_Model_Field_Base $field_obj
3087
-     * @param array               $fields_n_values
3088
-     * @return mixed string|int|float depending on what the table column will be expecting
3089
-     * @throws EE_Error
3090
-     */
3091
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3092
-    {
3093
-        // if this field doesn't allow nullable, don't allow it
3094
-        if (
3095
-            ! $field_obj->is_nullable()
3096
-            && (
3097
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3098
-                || $fields_n_values[ $field_obj->get_name() ] === null
3099
-            )
3100
-        ) {
3101
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3102
-        }
3103
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3104
-            ? $fields_n_values[ $field_obj->get_name() ]
3105
-            : null;
3106
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3107
-    }
3108
-
3109
-
3110
-
3111
-    /**
3112
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3113
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3114
-     * the field's prepare_for_set() method.
3115
-     *
3116
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3117
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3118
-     *                                   top of file)
3119
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3120
-     *                                   $value is a custom selection
3121
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3122
-     */
3123
-    private function _prepare_value_for_use_in_db($value, $field)
3124
-    {
3125
-        if ($field && $field instanceof EE_Model_Field_Base) {
3126
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3127
-            switch ($this->_values_already_prepared_by_model_object) {
3128
-                /** @noinspection PhpMissingBreakStatementInspection */
3129
-                case self::not_prepared_by_model_object:
3130
-                    $value = $field->prepare_for_set($value);
3131
-                // purposefully left out "return"
3132
-                case self::prepared_by_model_object:
3133
-                    /** @noinspection SuspiciousAssignmentsInspection */
3134
-                    $value = $field->prepare_for_use_in_db($value);
3135
-                case self::prepared_for_use_in_db:
3136
-                    // leave the value alone
3137
-            }
3138
-            return $value;
3139
-            // phpcs:enable
3140
-        }
3141
-        return $value;
3142
-    }
3143
-
3144
-
3145
-
3146
-    /**
3147
-     * Returns the main table on this model
3148
-     *
3149
-     * @return EE_Primary_Table
3150
-     * @throws EE_Error
3151
-     */
3152
-    protected function _get_main_table()
3153
-    {
3154
-        foreach ($this->_tables as $table) {
3155
-            if ($table instanceof EE_Primary_Table) {
3156
-                return $table;
3157
-            }
3158
-        }
3159
-        throw new EE_Error(sprintf(__(
3160
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3161
-            'event_espresso'
3162
-        ), get_class($this)));
3163
-    }
3164
-
3165
-
3166
-
3167
-    /**
3168
-     * table
3169
-     * returns EE_Primary_Table table name
3170
-     *
3171
-     * @return string
3172
-     * @throws EE_Error
3173
-     */
3174
-    public function table()
3175
-    {
3176
-        return $this->_get_main_table()->get_table_name();
3177
-    }
3178
-
3179
-
3180
-
3181
-    /**
3182
-     * table
3183
-     * returns first EE_Secondary_Table table name
3184
-     *
3185
-     * @return string
3186
-     */
3187
-    public function second_table()
3188
-    {
3189
-        // grab second table from tables array
3190
-        $second_table = end($this->_tables);
3191
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3192
-    }
3193
-
3194
-
3195
-
3196
-    /**
3197
-     * get_table_obj_by_alias
3198
-     * returns table name given it's alias
3199
-     *
3200
-     * @param string $table_alias
3201
-     * @return EE_Primary_Table | EE_Secondary_Table
3202
-     */
3203
-    public function get_table_obj_by_alias($table_alias = '')
3204
-    {
3205
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3206
-    }
3207
-
3208
-
3209
-
3210
-    /**
3211
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3212
-     *
3213
-     * @return EE_Secondary_Table[]
3214
-     */
3215
-    protected function _get_other_tables()
3216
-    {
3217
-        $other_tables = array();
3218
-        foreach ($this->_tables as $table_alias => $table) {
3219
-            if ($table instanceof EE_Secondary_Table) {
3220
-                $other_tables[ $table_alias ] = $table;
3221
-            }
3222
-        }
3223
-        return $other_tables;
3224
-    }
3225
-
3226
-
3227
-
3228
-    /**
3229
-     * Finds all the fields that correspond to the given table
3230
-     *
3231
-     * @param string $table_alias , array key in EEM_Base::_tables
3232
-     * @return EE_Model_Field_Base[]
3233
-     */
3234
-    public function _get_fields_for_table($table_alias)
3235
-    {
3236
-        return $this->_fields[ $table_alias ];
3237
-    }
3238
-
3239
-
3240
-
3241
-    /**
3242
-     * Recurses through all the where parameters, and finds all the related models we'll need
3243
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3244
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3245
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3246
-     * related Registration, Transaction, and Payment models.
3247
-     *
3248
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3249
-     * @return EE_Model_Query_Info_Carrier
3250
-     * @throws EE_Error
3251
-     */
3252
-    public function _extract_related_models_from_query($query_params)
3253
-    {
3254
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3255
-        if (array_key_exists(0, $query_params)) {
3256
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3257
-        }
3258
-        if (array_key_exists('group_by', $query_params)) {
3259
-            if (is_array($query_params['group_by'])) {
3260
-                $this->_extract_related_models_from_sub_params_array_values(
3261
-                    $query_params['group_by'],
3262
-                    $query_info_carrier,
3263
-                    'group_by'
3264
-                );
3265
-            } elseif (! empty($query_params['group_by'])) {
3266
-                $this->_extract_related_model_info_from_query_param(
3267
-                    $query_params['group_by'],
3268
-                    $query_info_carrier,
3269
-                    'group_by'
3270
-                );
3271
-            }
3272
-        }
3273
-        if (array_key_exists('having', $query_params)) {
3274
-            $this->_extract_related_models_from_sub_params_array_keys(
3275
-                $query_params[0],
3276
-                $query_info_carrier,
3277
-                'having'
3278
-            );
3279
-        }
3280
-        if (array_key_exists('order_by', $query_params)) {
3281
-            if (is_array($query_params['order_by'])) {
3282
-                $this->_extract_related_models_from_sub_params_array_keys(
3283
-                    $query_params['order_by'],
3284
-                    $query_info_carrier,
3285
-                    'order_by'
3286
-                );
3287
-            } elseif (! empty($query_params['order_by'])) {
3288
-                $this->_extract_related_model_info_from_query_param(
3289
-                    $query_params['order_by'],
3290
-                    $query_info_carrier,
3291
-                    'order_by'
3292
-                );
3293
-            }
3294
-        }
3295
-        if (array_key_exists('force_join', $query_params)) {
3296
-            $this->_extract_related_models_from_sub_params_array_values(
3297
-                $query_params['force_join'],
3298
-                $query_info_carrier,
3299
-                'force_join'
3300
-            );
3301
-        }
3302
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3303
-        return $query_info_carrier;
3304
-    }
3305
-
3306
-
3307
-
3308
-    /**
3309
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3310
-     *
3311
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3312
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3313
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3314
-     * @throws EE_Error
3315
-     * @return \EE_Model_Query_Info_Carrier
3316
-     */
3317
-    private function _extract_related_models_from_sub_params_array_keys(
3318
-        $sub_query_params,
3319
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3320
-        $query_param_type
3321
-    ) {
3322
-        if (! empty($sub_query_params)) {
3323
-            $sub_query_params = (array) $sub_query_params;
3324
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3325
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3326
-                $this->_extract_related_model_info_from_query_param(
3327
-                    $param,
3328
-                    $model_query_info_carrier,
3329
-                    $query_param_type
3330
-                );
3331
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3332
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3333
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3334
-                // of array('Registration.TXN_ID'=>23)
3335
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3336
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3337
-                    if (! is_array($possibly_array_of_params)) {
3338
-                        throw new EE_Error(sprintf(
3339
-                            __(
3340
-                                "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'))",
3341
-                                "event_espresso"
3342
-                            ),
3343
-                            $param,
3344
-                            $possibly_array_of_params
3345
-                        ));
3346
-                    }
3347
-                    $this->_extract_related_models_from_sub_params_array_keys(
3348
-                        $possibly_array_of_params,
3349
-                        $model_query_info_carrier,
3350
-                        $query_param_type
3351
-                    );
3352
-                } elseif (
3353
-                    $query_param_type === 0 // ie WHERE
3354
-                          && is_array($possibly_array_of_params)
3355
-                          && isset($possibly_array_of_params[2])
3356
-                          && $possibly_array_of_params[2] == true
3357
-                ) {
3358
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3359
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3360
-                    // from which we should extract query parameters!
3361
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3362
-                        throw new EE_Error(sprintf(__(
3363
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3364
-                            "event_espresso"
3365
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3366
-                    }
3367
-                    $this->_extract_related_model_info_from_query_param(
3368
-                        $possibly_array_of_params[1],
3369
-                        $model_query_info_carrier,
3370
-                        $query_param_type
3371
-                    );
3372
-                }
3373
-            }
3374
-        }
3375
-        return $model_query_info_carrier;
3376
-    }
3377
-
3378
-
3379
-
3380
-    /**
3381
-     * For extracting related models from forced_joins, where the array values contain the info about what
3382
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3383
-     *
3384
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3385
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3386
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3387
-     * @throws EE_Error
3388
-     * @return \EE_Model_Query_Info_Carrier
3389
-     */
3390
-    private function _extract_related_models_from_sub_params_array_values(
3391
-        $sub_query_params,
3392
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3393
-        $query_param_type
3394
-    ) {
3395
-        if (! empty($sub_query_params)) {
3396
-            if (! is_array($sub_query_params)) {
3397
-                throw new EE_Error(sprintf(
3398
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399
-                    $sub_query_params
3400
-                ));
3401
-            }
3402
-            foreach ($sub_query_params as $param) {
3403
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3404
-                $this->_extract_related_model_info_from_query_param(
3405
-                    $param,
3406
-                    $model_query_info_carrier,
3407
-                    $query_param_type
3408
-                );
3409
-            }
3410
-        }
3411
-        return $model_query_info_carrier;
3412
-    }
3413
-
3414
-
3415
-    /**
3416
-     * Extract all the query parts from  model query params
3417
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3418
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3419
-     * but use them in a different order. Eg, we need to know what models we are querying
3420
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3421
-     * other models before we can finalize the where clause SQL.
3422
-     *
3423
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3424
-     * @throws EE_Error
3425
-     * @return EE_Model_Query_Info_Carrier
3426
-     * @throws ModelConfigurationException
3427
-     */
3428
-    public function _create_model_query_info_carrier($query_params)
3429
-    {
3430
-        if (! is_array($query_params)) {
3431
-            EE_Error::doing_it_wrong(
3432
-                'EEM_Base::_create_model_query_info_carrier',
3433
-                sprintf(
3434
-                    __(
3435
-                        '$query_params should be an array, you passed a variable of type %s',
3436
-                        'event_espresso'
3437
-                    ),
3438
-                    gettype($query_params)
3439
-                ),
3440
-                '4.6.0'
3441
-            );
3442
-            $query_params = array();
3443
-        }
3444
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3445
-        // first check if we should alter the query to account for caps or not
3446
-        // because the caps might require us to do extra joins
3447
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3448
-            $query_params[0] = array_replace_recursive(
3449
-                $query_params[0],
3450
-                $this->caps_where_conditions(
3451
-                    $query_params['caps']
3452
-                )
3453
-            );
3454
-        }
3455
-
3456
-        // check if we should alter the query to remove data related to protected
3457
-        // custom post types
3458
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3459
-            $where_param_key_for_password = $this->modelChainAndPassword();
3460
-            // only include if related to a cpt where no password has been set
3461
-            $query_params[0]['OR*nopassword'] = array(
3462
-                $where_param_key_for_password => '',
3463
-                $where_param_key_for_password . '*' => array('IS_NULL')
3464
-            );
3465
-        }
3466
-        $query_object = $this->_extract_related_models_from_query($query_params);
3467
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3468
-        foreach ($query_params[0] as $key => $value) {
3469
-            if (is_int($key)) {
3470
-                throw new EE_Error(
3471
-                    sprintf(
3472
-                        __(
3473
-                            "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.",
3474
-                            "event_espresso"
3475
-                        ),
3476
-                        $key,
3477
-                        var_export($value, true),
3478
-                        var_export($query_params, true),
3479
-                        get_class($this)
3480
-                    )
3481
-                );
3482
-            }
3483
-        }
3484
-        if (
3485
-            array_key_exists('default_where_conditions', $query_params)
3486
-            && ! empty($query_params['default_where_conditions'])
3487
-        ) {
3488
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3489
-        } else {
3490
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3491
-        }
3492
-        $query_params[0] = array_merge(
3493
-            $this->_get_default_where_conditions_for_models_in_query(
3494
-                $query_object,
3495
-                $use_default_where_conditions,
3496
-                $query_params[0]
3497
-            ),
3498
-            $query_params[0]
3499
-        );
3500
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3501
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3502
-        // So we need to setup a subquery and use that for the main join.
3503
-        // Note for now this only works on the primary table for the model.
3504
-        // So for instance, you could set the limit array like this:
3505
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3506
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3507
-            $query_object->set_main_model_join_sql(
3508
-                $this->_construct_limit_join_select(
3509
-                    $query_params['on_join_limit'][0],
3510
-                    $query_params['on_join_limit'][1]
3511
-                )
3512
-            );
3513
-        }
3514
-        // set limit
3515
-        if (array_key_exists('limit', $query_params)) {
3516
-            if (is_array($query_params['limit'])) {
3517
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3518
-                    $e = sprintf(
3519
-                        __(
3520
-                            "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)",
3521
-                            "event_espresso"
3522
-                        ),
3523
-                        http_build_query($query_params['limit'])
3524
-                    );
3525
-                    throw new EE_Error($e . "|" . $e);
3526
-                }
3527
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3528
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3529
-            } elseif (! empty($query_params['limit'])) {
3530
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3531
-            }
3532
-        }
3533
-        // set order by
3534
-        if (array_key_exists('order_by', $query_params)) {
3535
-            if (is_array($query_params['order_by'])) {
3536
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3537
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3538
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3539
-                if (array_key_exists('order', $query_params)) {
3540
-                    throw new EE_Error(
3541
-                        sprintf(
3542
-                            __(
3543
-                                "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 ",
3544
-                                "event_espresso"
3545
-                            ),
3546
-                            get_class($this),
3547
-                            implode(", ", array_keys($query_params['order_by'])),
3548
-                            implode(", ", $query_params['order_by']),
3549
-                            $query_params['order']
3550
-                        )
3551
-                    );
3552
-                }
3553
-                $this->_extract_related_models_from_sub_params_array_keys(
3554
-                    $query_params['order_by'],
3555
-                    $query_object,
3556
-                    'order_by'
3557
-                );
3558
-                // assume it's an array of fields to order by
3559
-                $order_array = array();
3560
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3561
-                    $order = $this->_extract_order($order);
3562
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3563
-                }
3564
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3565
-            } elseif (! empty($query_params['order_by'])) {
3566
-                $this->_extract_related_model_info_from_query_param(
3567
-                    $query_params['order_by'],
3568
-                    $query_object,
3569
-                    'order',
3570
-                    $query_params['order_by']
3571
-                );
3572
-                $order = isset($query_params['order'])
3573
-                    ? $this->_extract_order($query_params['order'])
3574
-                    : 'DESC';
3575
-                $query_object->set_order_by_sql(
3576
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3577
-                );
3578
-            }
3579
-        }
3580
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3581
-        if (
3582
-            ! array_key_exists('order_by', $query_params)
3583
-            && array_key_exists('order', $query_params)
3584
-            && ! empty($query_params['order'])
3585
-        ) {
3586
-            $pk_field = $this->get_primary_key_field();
3587
-            $order = $this->_extract_order($query_params['order']);
3588
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3589
-        }
3590
-        // set group by
3591
-        if (array_key_exists('group_by', $query_params)) {
3592
-            if (is_array($query_params['group_by'])) {
3593
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3594
-                $group_by_array = array();
3595
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597
-                }
3598
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
-            } elseif (! empty($query_params['group_by'])) {
3600
-                $query_object->set_group_by_sql(
3601
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3602
-                );
3603
-            }
3604
-        }
3605
-        // set having
3606
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3607
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3608
-        }
3609
-        // now, just verify they didn't pass anything wack
3610
-        foreach ($query_params as $query_key => $query_value) {
3611
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3612
-                throw new EE_Error(
3613
-                    sprintf(
3614
-                        __(
3615
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3616
-                            'event_espresso'
3617
-                        ),
3618
-                        $query_key,
3619
-                        get_class($this),
3620
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3621
-                        implode(',', $this->_allowed_query_params)
3622
-                    )
3623
-                );
3624
-            }
3625
-        }
3626
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3627
-        if (empty($main_model_join_sql)) {
3628
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3629
-        }
3630
-        return $query_object;
3631
-    }
3632
-
3633
-
3634
-
3635
-    /**
3636
-     * Gets the where conditions that should be imposed on the query based on the
3637
-     * context (eg reading frontend, backend, edit or delete).
3638
-     *
3639
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3640
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3641
-     * @throws EE_Error
3642
-     */
3643
-    public function caps_where_conditions($context = self::caps_read)
3644
-    {
3645
-        EEM_Base::verify_is_valid_cap_context($context);
3646
-        $cap_where_conditions = array();
3647
-        $cap_restrictions = $this->caps_missing($context);
3648
-        /**
3649
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3650
-         */
3651
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3652
-            $cap_where_conditions = array_replace_recursive(
3653
-                $cap_where_conditions,
3654
-                $restriction_if_no_cap->get_default_where_conditions()
3655
-            );
3656
-        }
3657
-        return apply_filters(
3658
-            'FHEE__EEM_Base__caps_where_conditions__return',
3659
-            $cap_where_conditions,
3660
-            $this,
3661
-            $context,
3662
-            $cap_restrictions
3663
-        );
3664
-    }
3665
-
3666
-
3667
-
3668
-    /**
3669
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3670
-     * otherwise throws an exception
3671
-     *
3672
-     * @param string $should_be_order_string
3673
-     * @return string either ASC, asc, DESC or desc
3674
-     * @throws EE_Error
3675
-     */
3676
-    private function _extract_order($should_be_order_string)
3677
-    {
3678
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3679
-            return $should_be_order_string;
3680
-        }
3681
-        throw new EE_Error(
3682
-            sprintf(
3683
-                __(
3684
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3685
-                    "event_espresso"
3686
-                ),
3687
-                get_class($this),
3688
-                $should_be_order_string
3689
-            )
3690
-        );
3691
-    }
3692
-
3693
-
3694
-
3695
-    /**
3696
-     * Looks at all the models which are included in this query, and asks each
3697
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3698
-     * so they can be merged
3699
-     *
3700
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3701
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3702
-     *                                                                  'none' means NO default where conditions will
3703
-     *                                                                  be used AT ALL during this query.
3704
-     *                                                                  'other_models_only' means default where
3705
-     *                                                                  conditions from other models will be used, but
3706
-     *                                                                  not for this primary model. 'all', the default,
3707
-     *                                                                  means default where conditions will apply as
3708
-     *                                                                  normal
3709
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3710
-     * @throws EE_Error
3711
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3712
-     */
3713
-    private function _get_default_where_conditions_for_models_in_query(
3714
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3715
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3716
-        $where_query_params = array()
3717
-    ) {
3718
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720
-            throw new EE_Error(sprintf(
3721
-                __(
3722
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3723
-                    "event_espresso"
3724
-                ),
3725
-                $use_default_where_conditions,
3726
-                implode(", ", $allowed_used_default_where_conditions_values)
3727
-            ));
3728
-        }
3729
-        $universal_query_params = array();
3730
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3731
-            $universal_query_params = $this->_get_default_where_conditions();
3732
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3733
-            $universal_query_params = $this->_get_minimum_where_conditions();
3734
-        }
3735
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
-            $related_model = $this->get_related_model_obj($model_name);
3737
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3739
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3740
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3741
-            } else {
3742
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3743
-                continue;
3744
-            }
3745
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3746
-                $related_model_universal_where_params,
3747
-                $where_query_params,
3748
-                $related_model,
3749
-                $model_relation_path
3750
-            );
3751
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3752
-                $universal_query_params,
3753
-                $overrides
3754
-            );
3755
-        }
3756
-        return $universal_query_params;
3757
-    }
3758
-
3759
-
3760
-
3761
-    /**
3762
-     * Determines whether or not we should use default where conditions for the model in question
3763
-     * (this model, or other related models).
3764
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3765
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3766
-     * We should use default where conditions on related models when they requested to use default where conditions
3767
-     * on all models, or specifically just on other related models
3768
-     * @param      $default_where_conditions_value
3769
-     * @param bool $for_this_model false means this is for OTHER related models
3770
-     * @return bool
3771
-     */
3772
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3773
-    {
3774
-        return (
3775
-                   $for_this_model
3776
-                   && in_array(
3777
-                       $default_where_conditions_value,
3778
-                       array(
3779
-                           EEM_Base::default_where_conditions_all,
3780
-                           EEM_Base::default_where_conditions_this_only,
3781
-                           EEM_Base::default_where_conditions_minimum_others,
3782
-                       ),
3783
-                       true
3784
-                   )
3785
-               )
3786
-               || (
3787
-                   ! $for_this_model
3788
-                   && in_array(
3789
-                       $default_where_conditions_value,
3790
-                       array(
3791
-                           EEM_Base::default_where_conditions_all,
3792
-                           EEM_Base::default_where_conditions_others_only,
3793
-                       ),
3794
-                       true
3795
-                   )
3796
-               );
3797
-    }
3798
-
3799
-    /**
3800
-     * Determines whether or not we should use default minimum conditions for the model in question
3801
-     * (this model, or other related models).
3802
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3803
-     * where conditions.
3804
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3805
-     * on this model or others
3806
-     * @param      $default_where_conditions_value
3807
-     * @param bool $for_this_model false means this is for OTHER related models
3808
-     * @return bool
3809
-     */
3810
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
-    {
3812
-        return (
3813
-                   $for_this_model
3814
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
-               )
3816
-               || (
3817
-                   ! $for_this_model
3818
-                   && in_array(
3819
-                       $default_where_conditions_value,
3820
-                       array(
3821
-                           EEM_Base::default_where_conditions_minimum_others,
3822
-                           EEM_Base::default_where_conditions_minimum_all,
3823
-                       ),
3824
-                       true
3825
-                   )
3826
-               );
3827
-    }
3828
-
3829
-
3830
-    /**
3831
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
-     * then we also add a special where condition which allows for that model's primary key
3833
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
-     *
3836
-     * @param array    $default_where_conditions
3837
-     * @param array    $provided_where_conditions
3838
-     * @param EEM_Base $model
3839
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3840
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3841
-     * @throws EE_Error
3842
-     */
3843
-    private function _override_defaults_or_make_null_friendly(
3844
-        $default_where_conditions,
3845
-        $provided_where_conditions,
3846
-        $model,
3847
-        $model_relation_path
3848
-    ) {
3849
-        $null_friendly_where_conditions = array();
3850
-        $none_overridden = true;
3851
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3852
-        foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3854
-                $none_overridden = false;
3855
-            } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
-            }
3858
-        }
3859
-        if ($none_overridden && $default_where_conditions) {
3860
-            if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
-                                                                                . "."
3863
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3864
-            }/*else{
43
+	/**
44
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
45
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
46
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
47
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
48
+	 *
49
+	 * @var boolean
50
+	 */
51
+	private $_values_already_prepared_by_model_object = 0;
52
+
53
+	/**
54
+	 * when $_values_already_prepared_by_model_object equals this, we assume
55
+	 * the data is just like form input that needs to have the model fields'
56
+	 * prepare_for_set and prepare_for_use_in_db called on it
57
+	 */
58
+	const not_prepared_by_model_object = 0;
59
+
60
+	/**
61
+	 * when $_values_already_prepared_by_model_object equals this, we
62
+	 * assume this value is coming from a model object and doesn't need to have
63
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
64
+	 */
65
+	const prepared_by_model_object = 1;
66
+
67
+	/**
68
+	 * when $_values_already_prepared_by_model_object equals this, we assume
69
+	 * the values are already to be used in the database (ie no processing is done
70
+	 * on them by the model's fields)
71
+	 */
72
+	const prepared_for_use_in_db = 2;
73
+
74
+
75
+	protected $singular_item = 'Item';
76
+
77
+	protected $plural_item   = 'Items';
78
+
79
+	/**
80
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
81
+	 */
82
+	protected $_tables;
83
+
84
+	/**
85
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
86
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
87
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
88
+	 *
89
+	 * @var EE_Model_Field_Base[][] $_fields
90
+	 */
91
+	protected $_fields;
92
+
93
+	/**
94
+	 * array of different kinds of relations
95
+	 *
96
+	 * @var EE_Model_Relation_Base[] $_model_relations
97
+	 */
98
+	protected $_model_relations = [];
99
+
100
+	/**
101
+	 * @var EE_Index[] $_indexes
102
+	 */
103
+	protected $_indexes = array();
104
+
105
+	/**
106
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
107
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
108
+	 * by setting the same columns as used in these queries in the query yourself.
109
+	 *
110
+	 * @var EE_Default_Where_Conditions
111
+	 */
112
+	protected $_default_where_conditions_strategy;
113
+
114
+	/**
115
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
116
+	 * This is particularly useful when you want something between 'none' and 'default'
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_minimum_where_conditions_strategy;
121
+
122
+	/**
123
+	 * String describing how to find the "owner" of this model's objects.
124
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
125
+	 * But when there isn't, this indicates which related model, or transiently-related model,
126
+	 * has the foreign key to the wp_users table.
127
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
128
+	 * related to events, and events have a foreign key to wp_users.
129
+	 * On EEM_Transaction, this would be 'Transaction.Event'
130
+	 *
131
+	 * @var string
132
+	 */
133
+	protected $_model_chain_to_wp_user = '';
134
+
135
+	/**
136
+	 * String describing how to find the model with a password controlling access to this model. This property has the
137
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
138
+	 * This value is the path of models to follow to arrive at the model with the password field.
139
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
140
+	 * model with a password that should affect reading this on the front-end.
141
+	 * Eg this is an empty string for the Event model because it has a password.
142
+	 * This is null for the Registration model, because its event's password has no bearing on whether
143
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
144
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
145
+	 * should hide tickets for datetimes for events that have a password set.
146
+	 * @var string |null
147
+	 */
148
+	protected $model_chain_to_password = null;
149
+
150
+	/**
151
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
+	 * don't need it (particularly CPT models)
153
+	 *
154
+	 * @var bool
155
+	 */
156
+	protected $_ignore_where_strategy = false;
157
+
158
+	/**
159
+	 * String used in caps relating to this model. Eg, if the caps relating to this
160
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
+	 *
162
+	 * @var string. If null it hasn't been initialized yet. If false then we
163
+	 * have indicated capabilities don't apply to this
164
+	 */
165
+	protected $_caps_slug = null;
166
+
167
+	/**
168
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
+	 * and next-level keys are capability names, and each's value is a
170
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
172
+	 * and then each capability in the corresponding sub-array that they're missing
173
+	 * adds the where conditions onto the query.
174
+	 *
175
+	 * @var array
176
+	 */
177
+	protected $_cap_restrictions = array(
178
+		self::caps_read       => array(),
179
+		self::caps_read_admin => array(),
180
+		self::caps_edit       => array(),
181
+		self::caps_delete     => array(),
182
+	);
183
+
184
+	/**
185
+	 * Array defining which cap restriction generators to use to create default
186
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
187
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
+	 * automatically set this to false (not just null).
190
+	 *
191
+	 * @var EE_Restriction_Generator_Base[]
192
+	 */
193
+	protected $_cap_restriction_generators = array();
194
+
195
+	/**
196
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
+	 */
198
+	const caps_read       = 'read';
199
+
200
+	const caps_read_admin = 'read_admin';
201
+
202
+	const caps_edit       = 'edit';
203
+
204
+	const caps_delete     = 'delete';
205
+
206
+	/**
207
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
+	 * maps to 'read' because when looking for relevant permissions we're going to use
210
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
211
+	 *
212
+	 * @var array
213
+	 */
214
+	protected $_cap_contexts_to_cap_action_map = array(
215
+		self::caps_read       => 'read',
216
+		self::caps_read_admin => 'read',
217
+		self::caps_edit       => 'edit',
218
+		self::caps_delete     => 'delete',
219
+	);
220
+
221
+	/**
222
+	 * Timezone
223
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
+	 * EE_Datetime_Field data type will have access to it.
227
+	 *
228
+	 * @var string
229
+	 */
230
+	protected $_timezone;
231
+
232
+
233
+	/**
234
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
+	 * multisite.
236
+	 *
237
+	 * @var int
238
+	 */
239
+	protected static $_model_query_blog_id;
240
+
241
+	/**
242
+	 * A copy of _fields, except the array keys are the model names pointed to by
243
+	 * the field
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cache_foreign_key_to_fields = array();
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, indexed by their name
251
+	 *
252
+	 * @var EE_Model_Field_Base[]
253
+	 */
254
+	private $_cached_fields = null;
255
+
256
+	/**
257
+	 * Cached list of all the fields on the model, except those that are
258
+	 * marked as only pertinent to the database
259
+	 *
260
+	 * @var EE_Model_Field_Base[]
261
+	 */
262
+	private $_cached_fields_non_db_only = null;
263
+
264
+	/**
265
+	 * A cached reference to the primary key for quick lookup
266
+	 *
267
+	 * @var EE_Model_Field_Base
268
+	 */
269
+	private $_primary_key_field = null;
270
+
271
+	/**
272
+	 * Flag indicating whether this model has a primary key or not
273
+	 *
274
+	 * @var boolean
275
+	 */
276
+	protected $_has_primary_key_field = null;
277
+
278
+	/**
279
+	 * array in the format:  [ FK alias => full PK ]
280
+	 * where keys are local column name aliases for foreign keys
281
+	 * and values are the fully qualified column name for the primary key they represent
282
+	 *  ex:
283
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
+	 *
285
+	 * @var array $foreign_key_aliases
286
+	 */
287
+	protected $foreign_key_aliases = [];
288
+
289
+	/**
290
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
291
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
+	 * This should be true for models that deal with data that should exist independent of EE.
293
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
295
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
297
+	 * @var boolean
298
+	 */
299
+	protected $_wp_core_model = false;
300
+
301
+	/**
302
+	 * @var bool stores whether this model has a password field or not.
303
+	 * null until initialized by hasPasswordField()
304
+	 */
305
+	protected $has_password_field;
306
+
307
+	/**
308
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
309
+	 */
310
+	protected $password_field;
311
+
312
+	/**
313
+	 *    List of valid operators that can be used for querying.
314
+	 * The keys are all operators we'll accept, the values are the real SQL
315
+	 * operators used
316
+	 *
317
+	 * @var array
318
+	 */
319
+	protected $_valid_operators = array(
320
+		'='           => '=',
321
+		'<='          => '<=',
322
+		'<'           => '<',
323
+		'>='          => '>=',
324
+		'>'           => '>',
325
+		'!='          => '!=',
326
+		'LIKE'        => 'LIKE',
327
+		'like'        => 'LIKE',
328
+		'NOT_LIKE'    => 'NOT LIKE',
329
+		'not_like'    => 'NOT LIKE',
330
+		'NOT LIKE'    => 'NOT LIKE',
331
+		'not like'    => 'NOT LIKE',
332
+		'IN'          => 'IN',
333
+		'in'          => 'IN',
334
+		'NOT_IN'      => 'NOT IN',
335
+		'not_in'      => 'NOT IN',
336
+		'NOT IN'      => 'NOT IN',
337
+		'not in'      => 'NOT IN',
338
+		'between'     => 'BETWEEN',
339
+		'BETWEEN'     => 'BETWEEN',
340
+		'IS_NOT_NULL' => 'IS NOT NULL',
341
+		'is_not_null' => 'IS NOT NULL',
342
+		'IS NOT NULL' => 'IS NOT NULL',
343
+		'is not null' => 'IS NOT NULL',
344
+		'IS_NULL'     => 'IS NULL',
345
+		'is_null'     => 'IS NULL',
346
+		'IS NULL'     => 'IS NULL',
347
+		'is null'     => 'IS NULL',
348
+		'REGEXP'      => 'REGEXP',
349
+		'regexp'      => 'REGEXP',
350
+		'NOT_REGEXP'  => 'NOT REGEXP',
351
+		'not_regexp'  => 'NOT REGEXP',
352
+		'NOT REGEXP'  => 'NOT REGEXP',
353
+		'not regexp'  => 'NOT REGEXP',
354
+	);
355
+
356
+	/**
357
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
358
+	 *
359
+	 * @var array
360
+	 */
361
+	protected $_in_style_operators = array('IN', 'NOT IN');
362
+
363
+	/**
364
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
365
+	 * '12-31-2012'"
366
+	 *
367
+	 * @var array
368
+	 */
369
+	protected $_between_style_operators = array('BETWEEN');
370
+
371
+	/**
372
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
373
+	 * @var array
374
+	 */
375
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
376
+	/**
377
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
378
+	 * on a join table.
379
+	 *
380
+	 * @var array
381
+	 */
382
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
383
+
384
+	/**
385
+	 * Allowed values for $query_params['order'] for ordering in queries
386
+	 *
387
+	 * @var array
388
+	 */
389
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
390
+
391
+	/**
392
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
393
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
394
+	 *
395
+	 * @var array
396
+	 */
397
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
398
+
399
+	/**
400
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
401
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
402
+	 *
403
+	 * @var array
404
+	 */
405
+	private $_allowed_query_params = array(
406
+		0,
407
+		'limit',
408
+		'order_by',
409
+		'group_by',
410
+		'having',
411
+		'force_join',
412
+		'order',
413
+		'on_join_limit',
414
+		'default_where_conditions',
415
+		'caps',
416
+		'extra_selects',
417
+		'exclude_protected',
418
+	);
419
+
420
+	/**
421
+	 * All the data types that can be used in $wpdb->prepare statements.
422
+	 *
423
+	 * @var array
424
+	 */
425
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
426
+
427
+	/**
428
+	 * @var EE_Registry $EE
429
+	 */
430
+	protected $EE = null;
431
+
432
+
433
+	/**
434
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
435
+	 *
436
+	 * @var int
437
+	 */
438
+	protected $_show_next_x_db_queries = 0;
439
+
440
+	/**
441
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
442
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
443
+	 * WHERE, GROUP_BY, etc.
444
+	 *
445
+	 * @var CustomSelects
446
+	 */
447
+	protected $_custom_selections = array();
448
+
449
+	/**
450
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
451
+	 * caches every model object we've fetched from the DB on this request
452
+	 *
453
+	 * @var array
454
+	 */
455
+	protected $_entity_map;
456
+
457
+	/**
458
+	 * @var LoaderInterface
459
+	 */
460
+	private static $loader;
461
+
462
+	/**
463
+	 * @var Mirror
464
+	 */
465
+	private static $mirror;
466
+
467
+
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has not yet verified the db on this http request
471
+	 */
472
+	const db_verified_none = 0;
473
+
474
+	/**
475
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
476
+	 * but not the addons' dbs
477
+	 */
478
+	const db_verified_core = 1;
479
+
480
+	/**
481
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
482
+	 * the EE core db too)
483
+	 */
484
+	const db_verified_addons = 2;
485
+
486
+	/**
487
+	 * indicates whether an EEM_Base child has already re-verified the DB
488
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
489
+	 * looking like EEM_Base::db_verified_*
490
+	 *
491
+	 * @var int - 0 = none, 1 = core, 2 = addons
492
+	 */
493
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
494
+
495
+	/**
496
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
497
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
498
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
499
+	 */
500
+	const default_where_conditions_all = 'all';
501
+
502
+	/**
503
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
504
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
505
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
506
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
507
+	 *        models which share tables with other models, this can return data for the wrong model.
508
+	 */
509
+	const default_where_conditions_this_only = 'this_model_only';
510
+
511
+	/**
512
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
513
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
514
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
515
+	 */
516
+	const default_where_conditions_others_only = 'other_models_only';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
520
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
521
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
522
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
523
+	 *        (regardless of whether those events and venues are trashed)
524
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
525
+	 *        events.
526
+	 */
527
+	const default_where_conditions_minimum_all = 'minimum';
528
+
529
+	/**
530
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
531
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
532
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
533
+	 *        not)
534
+	 */
535
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
536
+
537
+	/**
538
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
539
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
540
+	 *        it's possible it will return table entries for other models. You should use
541
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
542
+	 */
543
+	const default_where_conditions_none = 'none';
544
+
545
+
546
+
547
+	/**
548
+	 * About all child constructors:
549
+	 * they should define the _tables, _fields and _model_relations arrays.
550
+	 * Should ALWAYS be called after child constructor.
551
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
552
+	 * finalizes constructing all the object's attributes.
553
+	 * Generally, rather than requiring a child to code
554
+	 * $this->_tables = array(
555
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
556
+	 *        ...);
557
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
558
+	 * each EE_Table has a function to set the table's alias after the constructor, using
559
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
560
+	 * do something similar.
561
+	 *
562
+	 * @param null $timezone
563
+	 * @throws EE_Error
564
+	 */
565
+	protected function __construct($timezone = null)
566
+	{
567
+		// check that the model has not been loaded too soon
568
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
569
+			throw new EE_Error(
570
+				sprintf(
571
+					__(
572
+						'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.',
573
+						'event_espresso'
574
+					),
575
+					get_class($this)
576
+				)
577
+			);
578
+		}
579
+		/**
580
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
581
+		 */
582
+		if (empty(EEM_Base::$_model_query_blog_id)) {
583
+			EEM_Base::set_model_query_blog_id();
584
+		}
585
+		/**
586
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
587
+		 * just use EE_Register_Model_Extension
588
+		 *
589
+		 * @var EE_Table_Base[] $_tables
590
+		 */
591
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
592
+		foreach ($this->_tables as $table_alias => $table_obj) {
593
+			/** @var $table_obj EE_Table_Base */
594
+			$table_obj->_construct_finalize_with_alias($table_alias);
595
+			if ($table_obj instanceof EE_Secondary_Table) {
596
+				/** @var $table_obj EE_Secondary_Table */
597
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
598
+			}
599
+		}
600
+		/**
601
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
602
+		 * EE_Register_Model_Extension
603
+		 *
604
+		 * @param EE_Model_Field_Base[] $_fields
605
+		 */
606
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
607
+		$this->_invalidate_field_caches();
608
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
609
+			if (! array_key_exists($table_alias, $this->_tables)) {
610
+				throw new EE_Error(sprintf(__(
611
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612
+					'event_espresso'
613
+				), $table_alias, implode(",", $this->_fields)));
614
+			}
615
+			foreach ($fields_for_table as $field_name => $field_obj) {
616
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
617
+				// primary key field base has a slightly different _construct_finalize
618
+				/** @var $field_obj EE_Model_Field_Base */
619
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
620
+			}
621
+		}
622
+		// everything is related to Extra_Meta
623
+		if (get_class($this) !== 'EEM_Extra_Meta') {
624
+			// make extra meta related to everything, but don't block deleting things just
625
+			// because they have related extra meta info. For now just orphan those extra meta
626
+			// in the future we should automatically delete them
627
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
628
+		}
629
+		// and change logs
630
+		if (get_class($this) !== 'EEM_Change_Log') {
631
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
632
+		}
633
+		/**
634
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
635
+		 * EE_Register_Model_Extension
636
+		 *
637
+		 * @param EE_Model_Relation_Base[] $_model_relations
638
+		 */
639
+		$this->_model_relations = (array) apply_filters(
640
+			'FHEE__' . get_class($this) . '__construct__model_relations',
641
+			$this->_model_relations
642
+		);
643
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
644
+			/** @var $relation_obj EE_Model_Relation_Base */
645
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
646
+		}
647
+		foreach ($this->_indexes as $index_name => $index_obj) {
648
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
649
+		}
650
+		$this->set_timezone($timezone);
651
+		// finalize default where condition strategy, or set default
652
+		if (! $this->_default_where_conditions_strategy) {
653
+			// nothing was set during child constructor, so set default
654
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
655
+		}
656
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
657
+		if (! $this->_minimum_where_conditions_strategy) {
658
+			// nothing was set during child constructor, so set default
659
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
660
+		}
661
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
662
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
663
+		// to indicate to NOT set it, set it to the logical default
664
+		if ($this->_caps_slug === null) {
665
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
666
+		}
667
+		// initialize the standard cap restriction generators if none were specified by the child constructor
668
+		if (is_array($this->_cap_restriction_generators)) {
669
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
670
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
671
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
672
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
673
+						new EE_Restriction_Generator_Protected(),
674
+						$cap_context,
675
+						$this
676
+					);
677
+				}
678
+			}
679
+		}
680
+		// if there are cap restriction generators, use them to make the default cap restrictions
681
+		if (is_array($this->_cap_restriction_generators)) {
682
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
683
+				if (! $generator_object) {
684
+					continue;
685
+				}
686
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
687
+					throw new EE_Error(
688
+						sprintf(
689
+							__(
690
+								'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.',
691
+								'event_espresso'
692
+							),
693
+							$context,
694
+							$this->get_this_model_name()
695
+						)
696
+					);
697
+				}
698
+				$action = $this->cap_action_for_context($context);
699
+				if (! $generator_object->construction_finalized()) {
700
+					$generator_object->_construct_finalize($this, $action);
701
+				}
702
+			}
703
+		}
704
+		do_action('AHEE__' . get_class($this) . '__construct__end');
705
+	}
706
+
707
+
708
+	/**
709
+	 * @return LoaderInterface
710
+	 * @throws InvalidArgumentException
711
+	 * @throws InvalidDataTypeException
712
+	 * @throws InvalidInterfaceException
713
+	 */
714
+	protected static function getLoader(): LoaderInterface
715
+	{
716
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
717
+			EEM_Base::$loader = LoaderFactory::getLoader();
718
+		}
719
+		return EEM_Base::$loader;
720
+	}
721
+
722
+
723
+	/**
724
+	 * @return Mirror
725
+	 * @since   $VID:$
726
+	 */
727
+	private static function getMirror(): Mirror
728
+	{
729
+		if (! EEM_Base::$mirror instanceof Mirror) {
730
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
731
+		}
732
+		return EEM_Base::$mirror;
733
+	}
734
+
735
+
736
+	/**
737
+	 * @param string $model_class_Name
738
+	 * @param string $timezone
739
+	 * @return array
740
+	 * @throws ReflectionException
741
+	 * @since   $VID:$
742
+	 */
743
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
744
+	{
745
+		$arguments = [$timezone];
746
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
747
+		if (count($params) > 1) {
748
+			if ($params[1]->getName() === 'model_field_factory') {
749
+				$arguments = [
750
+					$timezone,
751
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class)
752
+				];
753
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
754
+				$arguments = [
755
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\Element'),
756
+					$timezone
757
+				];
758
+			} elseif ($model_class_Name === 'EEM_Form_Input') {
759
+				$arguments = [
760
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\Element'),
761
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
762
+					$timezone
763
+				];
764
+			}
765
+		}
766
+		return $arguments;
767
+	}
768
+
769
+
770
+	/**
771
+	 * This function is a singleton method used to instantiate the Espresso_model object
772
+	 *
773
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
774
+	 *                                (and any incoming timezone data that gets saved).
775
+	 *                                Note this just sends the timezone info to the date time model field objects.
776
+	 *                                Default is NULL
777
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
778
+	 * @return static (as in the concrete child class)
779
+	 * @throws EE_Error
780
+	 * @throws ReflectionException
781
+	 */
782
+	public static function instance($timezone = null)
783
+	{
784
+		// check if instance of Espresso_model already exists
785
+		if (! static::$_instance instanceof static) {
786
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
787
+			$model = new static(...$arguments);
788
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
789
+			static::$_instance = $model;
790
+		}
791
+		// we might have a timezone set, let set_timezone decide what to do with it
792
+		if ($timezone){
793
+			static::$_instance->set_timezone($timezone);
794
+		}
795
+		// Espresso_model object
796
+		return static::$_instance;
797
+	}
798
+
799
+
800
+
801
+	/**
802
+	 * resets the model and returns it
803
+	 *
804
+	 * @param string|null $timezone
805
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
806
+	 * all its properties reset; if it wasn't instantiated, returns null)
807
+	 * @throws EE_Error
808
+	 * @throws ReflectionException
809
+	 * @throws InvalidArgumentException
810
+	 * @throws InvalidDataTypeException
811
+	 * @throws InvalidInterfaceException
812
+	 */
813
+	public static function reset($timezone = null)
814
+	{
815
+		if (! static::$_instance instanceof EEM_Base) {
816
+			return null;
817
+		}
818
+		// Let's NOT swap out the current instance for a new one
819
+		// because if someone has a reference to it, we can't remove their reference.
820
+		// It's best to keep using the same reference but change the original object instead,
821
+		// so reset all its properties to their original values as defined in the class.
822
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
823
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
824
+			// don't set instance to null like it was originally,
825
+			// but it's static anyways, and we're ignoring static properties (for now at least)
826
+			if (! isset($static_properties[ $property ])) {
827
+				static::$_instance->{$property} = $value;
828
+			}
829
+		}
830
+		// and then directly call its constructor again, like we would if we were creating a new one
831
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
832
+		static::$_instance->__construct(...$arguments);
833
+		return self::instance();
834
+	}
835
+
836
+
837
+	/**
838
+	 * Used to set the $_model_query_blog_id static property.
839
+	 *
840
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
841
+	 *                      value for get_current_blog_id() will be used.
842
+	 */
843
+	public static function set_model_query_blog_id($blog_id = 0)
844
+	{
845
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
846
+			? (int) $blog_id
847
+			: get_current_blog_id();
848
+	}
849
+
850
+
851
+	/**
852
+	 * Returns whatever is set as the internal $model_query_blog_id.
853
+	 *
854
+	 * @return int
855
+	 */
856
+	public static function get_model_query_blog_id()
857
+	{
858
+		return EEM_Base::$_model_query_blog_id;
859
+	}
860
+
861
+
862
+
863
+	/**
864
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
865
+	 *
866
+	 * @param  boolean $translated return localized strings or JUST the array.
867
+	 * @return array
868
+	 * @throws EE_Error
869
+	 * @throws InvalidArgumentException
870
+	 * @throws InvalidDataTypeException
871
+	 * @throws InvalidInterfaceException
872
+	 */
873
+	public function status_array($translated = false)
874
+	{
875
+		if (! array_key_exists('Status', $this->_model_relations)) {
876
+			return array();
877
+		}
878
+		$model_name = $this->get_this_model_name();
879
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
880
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
881
+		$status_array = array();
882
+		foreach ($stati as $status) {
883
+			$status_array[ $status->ID() ] = $status->get('STS_code');
884
+		}
885
+		return $translated
886
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
887
+			: $status_array;
888
+	}
889
+
890
+
891
+
892
+	/**
893
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
894
+	 *
895
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
896
+	 *                             or if you have the development copy of EE you can view this at the path:
897
+	 *                             /docs/G--Model-System/model-query-params.md
898
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
899
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
900
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
901
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
902
+	 *                                        array( array(
903
+	 *                                        'OR'=>array(
904
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
905
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
906
+	 *                                        )
907
+	 *                                        ),
908
+	 *                                        'limit'=>10,
909
+	 *                                        'group_by'=>'TXN_ID'
910
+	 *                                        ));
911
+	 *                                        get all the answers to the question titled "shirt size" for event with id
912
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
913
+	 *                                        'Question.QST_display_text'=>'shirt size',
914
+	 *                                        'Registration.Event.EVT_ID'=>12
915
+	 *                                        ),
916
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
917
+	 *                                        ));
918
+	 * @throws EE_Error
919
+	 */
920
+	public function get_all($query_params = array())
921
+	{
922
+		if (
923
+			isset($query_params['limit'])
924
+			&& ! isset($query_params['group_by'])
925
+		) {
926
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
927
+		}
928
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
929
+	}
930
+
931
+
932
+
933
+	/**
934
+	 * Modifies the query parameters so we only get back model objects
935
+	 * that "belong" to the current user
936
+	 *
937
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
938
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
939
+	 */
940
+	public function alter_query_params_to_only_include_mine($query_params = array())
941
+	{
942
+		$wp_user_field_name = $this->wp_user_field_name();
943
+		if ($wp_user_field_name) {
944
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
945
+		}
946
+		return $query_params;
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * Returns the name of the field's name that points to the WP_User table
953
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
954
+	 * foreign key to the WP_User table)
955
+	 *
956
+	 * @return string|boolean string on success, boolean false when there is no
957
+	 * foreign key to the WP_User table
958
+	 */
959
+	public function wp_user_field_name()
960
+	{
961
+		try {
962
+			if (! empty($this->_model_chain_to_wp_user)) {
963
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
964
+				$last_model_name = end($models_to_follow_to_wp_users);
965
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
966
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
967
+			} else {
968
+				$model_with_fk_to_wp_users = $this;
969
+				$model_chain_to_wp_user = '';
970
+			}
971
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
972
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
973
+		} catch (EE_Error $e) {
974
+			return false;
975
+		}
976
+	}
977
+
978
+
979
+
980
+	/**
981
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
982
+	 * (or transiently-related model) has a foreign key to the wp_users table;
983
+	 * useful for finding if model objects of this type are 'owned' by the current user.
984
+	 * This is an empty string when the foreign key is on this model and when it isn't,
985
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
986
+	 * (or transiently-related model)
987
+	 *
988
+	 * @return string
989
+	 */
990
+	public function model_chain_to_wp_user()
991
+	{
992
+		return $this->_model_chain_to_wp_user;
993
+	}
994
+
995
+
996
+
997
+	/**
998
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
999
+	 * like how registrations don't have a foreign key to wp_users, but the
1000
+	 * events they are for are), or is unrelated to wp users.
1001
+	 * generally available
1002
+	 *
1003
+	 * @return boolean
1004
+	 */
1005
+	public function is_owned()
1006
+	{
1007
+		if ($this->model_chain_to_wp_user()) {
1008
+			return true;
1009
+		}
1010
+		try {
1011
+			$this->get_foreign_key_to('WP_User');
1012
+			return true;
1013
+		} catch (EE_Error $e) {
1014
+			return false;
1015
+		}
1016
+	}
1017
+
1018
+
1019
+	/**
1020
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1021
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1022
+	 * the model)
1023
+	 *
1024
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1025
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1026
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1027
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1028
+	 *                                  override this and set the select to "*", or a specific column name, like
1029
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1030
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1031
+	 *                                  the aliases used to refer to this selection, and values are to be
1032
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1033
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1034
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1035
+	 * @throws EE_Error
1036
+	 * @throws InvalidArgumentException
1037
+	 */
1038
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1039
+	{
1040
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1041
+		;
1042
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1043
+		$select_expressions = $columns_to_select === null
1044
+			? $this->_construct_default_select_sql($model_query_info)
1045
+			: '';
1046
+		if ($this->_custom_selections instanceof CustomSelects) {
1047
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1048
+			$select_expressions .= $select_expressions
1049
+				? ', ' . $custom_expressions
1050
+				: $custom_expressions;
1051
+		}
1052
+
1053
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1054
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1055
+	}
1056
+
1057
+
1058
+	/**
1059
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1060
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1061
+	 * method of including extra select information.
1062
+	 *
1063
+	 * @param array             $query_params
1064
+	 * @param null|array|string $columns_to_select
1065
+	 * @return null|CustomSelects
1066
+	 * @throws InvalidArgumentException
1067
+	 */
1068
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1069
+	{
1070
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1071
+			return null;
1072
+		}
1073
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1074
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1075
+		return new CustomSelects($selects);
1076
+	}
1077
+
1078
+
1079
+
1080
+	/**
1081
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1082
+	 * but you can use the model query params to more easily
1083
+	 * take care of joins, field preparation etc.
1084
+	 *
1085
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1086
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1087
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1088
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1089
+	 *                                  override this and set the select to "*", or a specific column name, like
1090
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1091
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1092
+	 *                                  the aliases used to refer to this selection, and values are to be
1093
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1094
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1095
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1096
+	 * @throws EE_Error
1097
+	 */
1098
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1099
+	{
1100
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1101
+	}
1102
+
1103
+
1104
+
1105
+	/**
1106
+	 * For creating a custom select statement
1107
+	 *
1108
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1109
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1110
+	 *                                 SQL, and 1=>is the datatype
1111
+	 * @throws EE_Error
1112
+	 * @return string
1113
+	 */
1114
+	private function _construct_select_from_input($columns_to_select)
1115
+	{
1116
+		if (is_array($columns_to_select)) {
1117
+			$select_sql_array = array();
1118
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1119
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1120
+					throw new EE_Error(
1121
+						sprintf(
1122
+							__(
1123
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1124
+								'event_espresso'
1125
+							),
1126
+							$selection_and_datatype,
1127
+							$alias
1128
+						)
1129
+					);
1130
+				}
1131
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1132
+					throw new EE_Error(
1133
+						sprintf(
1134
+							esc_html__(
1135
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1136
+								'event_espresso'
1137
+							),
1138
+							$selection_and_datatype[1],
1139
+							$selection_and_datatype[0],
1140
+							$alias,
1141
+							implode(', ', $this->_valid_wpdb_data_types)
1142
+						)
1143
+					);
1144
+				}
1145
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1146
+			}
1147
+			$columns_to_select_string = implode(', ', $select_sql_array);
1148
+		} else {
1149
+			$columns_to_select_string = $columns_to_select;
1150
+		}
1151
+		return $columns_to_select_string;
1152
+	}
1153
+
1154
+
1155
+
1156
+	/**
1157
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1158
+	 *
1159
+	 * @return string
1160
+	 * @throws EE_Error
1161
+	 */
1162
+	public function primary_key_name()
1163
+	{
1164
+		return $this->get_primary_key_field()->get_name();
1165
+	}
1166
+
1167
+
1168
+	/**
1169
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1170
+	 * If there is no primary key on this model, $id is treated as primary key string
1171
+	 *
1172
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1173
+	 * @return EE_Base_Class
1174
+	 * @throws EE_Error
1175
+	 */
1176
+	public function get_one_by_ID($id)
1177
+	{
1178
+		if ($this->get_from_entity_map($id)) {
1179
+			return $this->get_from_entity_map($id);
1180
+		}
1181
+		$model_object = $this->get_one(
1182
+			$this->alter_query_params_to_restrict_by_ID(
1183
+				$id,
1184
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1185
+			)
1186
+		);
1187
+		$className = $this->_get_class_name();
1188
+		if ($model_object instanceof $className) {
1189
+			// make sure valid objects get added to the entity map
1190
+			// so that the next call to this method doesn't trigger another trip to the db
1191
+			$this->add_to_entity_map($model_object);
1192
+		}
1193
+		return $model_object;
1194
+	}
1195
+
1196
+
1197
+
1198
+	/**
1199
+	 * Alters query parameters to only get items with this ID are returned.
1200
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1201
+	 * or could just be a simple primary key ID
1202
+	 *
1203
+	 * @param int   $id
1204
+	 * @param array $query_params
1205
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1206
+	 * @throws EE_Error
1207
+	 */
1208
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1209
+	{
1210
+		if (! isset($query_params[0])) {
1211
+			$query_params[0] = array();
1212
+		}
1213
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1214
+		if ($conditions_from_id === null) {
1215
+			$query_params[0][ $this->primary_key_name() ] = $id;
1216
+		} else {
1217
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1218
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1219
+		}
1220
+		return $query_params;
1221
+	}
1222
+
1223
+
1224
+
1225
+	/**
1226
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1227
+	 * array. If no item is found, null is returned.
1228
+	 *
1229
+	 * @param array $query_params like EEM_Base's $query_params variable.
1230
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1231
+	 * @throws EE_Error
1232
+	 */
1233
+	public function get_one($query_params = array())
1234
+	{
1235
+		if (! is_array($query_params)) {
1236
+			EE_Error::doing_it_wrong(
1237
+				'EEM_Base::get_one',
1238
+				sprintf(
1239
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1240
+					gettype($query_params)
1241
+				),
1242
+				'4.6.0'
1243
+			);
1244
+			$query_params = array();
1245
+		}
1246
+		$query_params['limit'] = 1;
1247
+		$items = $this->get_all($query_params);
1248
+		if (empty($items)) {
1249
+			return null;
1250
+		}
1251
+		return array_shift($items);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the next x number of items in sequence from the given value as
1258
+	 * 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 next_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(
1280
+			$current_field_value,
1281
+			'>',
1282
+			$field_to_order_by,
1283
+			$limit,
1284
+			$query_params,
1285
+			$columns_to_select
1286
+		);
1287
+	}
1288
+
1289
+
1290
+
1291
+	/**
1292
+	 * Returns the previous x number of items in sequence from the given value
1293
+	 * as found in the database matching the given query conditions.
1294
+	 *
1295
+	 * @param mixed $current_field_value    Value used for the reference point.
1296
+	 * @param null  $field_to_order_by      What field is used for the
1297
+	 *                                      reference point.
1298
+	 * @param int   $limit                  How many to return.
1299
+	 * @param array $query_params           Extra conditions on the query.
1300
+	 * @param null  $columns_to_select      If left null, then an array of
1301
+	 *                                      EE_Base_Class objects is returned,
1302
+	 *                                      otherwise you can indicate just the
1303
+	 *                                      columns you want returned.
1304
+	 * @return EE_Base_Class[]|array
1305
+	 * @throws EE_Error
1306
+	 */
1307
+	public function previous_x(
1308
+		$current_field_value,
1309
+		$field_to_order_by = null,
1310
+		$limit = 1,
1311
+		$query_params = array(),
1312
+		$columns_to_select = null
1313
+	) {
1314
+		return $this->_get_consecutive(
1315
+			$current_field_value,
1316
+			'<',
1317
+			$field_to_order_by,
1318
+			$limit,
1319
+			$query_params,
1320
+			$columns_to_select
1321
+		);
1322
+	}
1323
+
1324
+
1325
+
1326
+	/**
1327
+	 * Returns the next item in sequence from the given value as found in the
1328
+	 * database matching the given query conditions.
1329
+	 *
1330
+	 * @param mixed $current_field_value    Value used for the reference point.
1331
+	 * @param null  $field_to_order_by      What field is used for the
1332
+	 *                                      reference point.
1333
+	 * @param array $query_params           Extra conditions on the query.
1334
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1335
+	 *                                      object is returned, otherwise you
1336
+	 *                                      can indicate just the columns you
1337
+	 *                                      want and a single array indexed by
1338
+	 *                                      the columns will be returned.
1339
+	 * @return EE_Base_Class|null|array()
1340
+	 * @throws EE_Error
1341
+	 */
1342
+	public function next(
1343
+		$current_field_value,
1344
+		$field_to_order_by = null,
1345
+		$query_params = array(),
1346
+		$columns_to_select = null
1347
+	) {
1348
+		$results = $this->_get_consecutive(
1349
+			$current_field_value,
1350
+			'>',
1351
+			$field_to_order_by,
1352
+			1,
1353
+			$query_params,
1354
+			$columns_to_select
1355
+		);
1356
+		return empty($results) ? null : reset($results);
1357
+	}
1358
+
1359
+
1360
+
1361
+	/**
1362
+	 * Returns the previous item in sequence from the given value as found in
1363
+	 * the database matching the given query conditions.
1364
+	 *
1365
+	 * @param mixed $current_field_value    Value used for the reference point.
1366
+	 * @param null  $field_to_order_by      What field is used for the
1367
+	 *                                      reference point.
1368
+	 * @param array $query_params           Extra conditions on the query.
1369
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1370
+	 *                                      object is returned, otherwise you
1371
+	 *                                      can indicate just the columns you
1372
+	 *                                      want and a single array indexed by
1373
+	 *                                      the columns will be returned.
1374
+	 * @return EE_Base_Class|null|array()
1375
+	 * @throws EE_Error
1376
+	 */
1377
+	public function previous(
1378
+		$current_field_value,
1379
+		$field_to_order_by = null,
1380
+		$query_params = array(),
1381
+		$columns_to_select = null
1382
+	) {
1383
+		$results = $this->_get_consecutive(
1384
+			$current_field_value,
1385
+			'<',
1386
+			$field_to_order_by,
1387
+			1,
1388
+			$query_params,
1389
+			$columns_to_select
1390
+		);
1391
+		return empty($results) ? null : reset($results);
1392
+	}
1393
+
1394
+
1395
+
1396
+	/**
1397
+	 * Returns the a consecutive number of items in sequence from the given
1398
+	 * value as found in the database matching the given query conditions.
1399
+	 *
1400
+	 * @param mixed  $current_field_value   Value used for the reference point.
1401
+	 * @param string $operand               What operand is used for the sequence.
1402
+	 * @param string $field_to_order_by     What field is used for the reference point.
1403
+	 * @param int    $limit                 How many to return.
1404
+	 * @param array  $query_params          Extra conditions on the query.
1405
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1406
+	 *                                      otherwise you can indicate just the columns you want returned.
1407
+	 * @return EE_Base_Class[]|array
1408
+	 * @throws EE_Error
1409
+	 */
1410
+	protected function _get_consecutive(
1411
+		$current_field_value,
1412
+		$operand = '>',
1413
+		$field_to_order_by = null,
1414
+		$limit = 1,
1415
+		$query_params = array(),
1416
+		$columns_to_select = null
1417
+	) {
1418
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1419
+		if (empty($field_to_order_by)) {
1420
+			if ($this->has_primary_key_field()) {
1421
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1422
+			} else {
1423
+				if (WP_DEBUG) {
1424
+					throw new EE_Error(__(
1425
+						'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).',
1426
+						'event_espresso'
1427
+					));
1428
+				}
1429
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1430
+				return array();
1431
+			}
1432
+		}
1433
+		if (! is_array($query_params)) {
1434
+			EE_Error::doing_it_wrong(
1435
+				'EEM_Base::_get_consecutive',
1436
+				sprintf(
1437
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1438
+					gettype($query_params)
1439
+				),
1440
+				'4.6.0'
1441
+			);
1442
+			$query_params = array();
1443
+		}
1444
+		// let's add the where query param for consecutive look up.
1445
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1446
+		$query_params['limit'] = $limit;
1447
+		// set direction
1448
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1449
+		$query_params['order_by'] = $operand === '>'
1450
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1451
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1452
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1453
+		if (empty($columns_to_select)) {
1454
+			return $this->get_all($query_params);
1455
+		}
1456
+		// getting just the fields
1457
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1458
+	}
1459
+
1460
+
1461
+
1462
+	/**
1463
+	 * This sets the _timezone property after model object has been instantiated.
1464
+	 *
1465
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1466
+	 */
1467
+	public function set_timezone($timezone)
1468
+	{
1469
+		if ($timezone !== null) {
1470
+			$this->_timezone = $timezone;
1471
+		}
1472
+		// note we need to loop through relations and set the timezone on those objects as well.
1473
+		foreach ($this->_model_relations as $relation) {
1474
+			$relation->set_timezone($timezone);
1475
+		}
1476
+		// and finally we do the same for any datetime fields
1477
+		foreach ($this->_fields as $field) {
1478
+			if ($field instanceof EE_Datetime_Field) {
1479
+				$field->set_timezone($timezone);
1480
+			}
1481
+		}
1482
+	}
1483
+
1484
+
1485
+
1486
+	/**
1487
+	 * This just returns whatever is set for the current timezone.
1488
+	 *
1489
+	 * @access public
1490
+	 * @return string
1491
+	 */
1492
+	public function get_timezone()
1493
+	{
1494
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1495
+		if (empty($this->_timezone)) {
1496
+			foreach ($this->_fields as $field) {
1497
+				if ($field instanceof EE_Datetime_Field) {
1498
+					$this->set_timezone($field->get_timezone());
1499
+					break;
1500
+				}
1501
+			}
1502
+		}
1503
+		// if timezone STILL empty then return the default timezone for the site.
1504
+		if (empty($this->_timezone)) {
1505
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1506
+		}
1507
+		return $this->_timezone;
1508
+	}
1509
+
1510
+
1511
+
1512
+	/**
1513
+	 * This returns the date formats set for the given field name and also ensures that
1514
+	 * $this->_timezone property is set correctly.
1515
+	 *
1516
+	 * @since 4.6.x
1517
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1518
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1519
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1520
+	 * @return array formats in an array with the date format first, and the time format last.
1521
+	 */
1522
+	public function get_formats_for($field_name, $pretty = false)
1523
+	{
1524
+		$field_settings = $this->field_settings_for($field_name);
1525
+		// if not a valid EE_Datetime_Field then throw error
1526
+		if (! $field_settings instanceof EE_Datetime_Field) {
1527
+			throw new EE_Error(sprintf(__(
1528
+				'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.',
1529
+				'event_espresso'
1530
+			), $field_name));
1531
+		}
1532
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1533
+		// the field.
1534
+		$this->_timezone = $field_settings->get_timezone();
1535
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1536
+	}
1537
+
1538
+
1539
+
1540
+	/**
1541
+	 * This returns the current time in a format setup for a query on this model.
1542
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1543
+	 * it will return:
1544
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1545
+	 *  NOW
1546
+	 *  - or a unix timestamp (equivalent to time())
1547
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1548
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1549
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1550
+	 * @since 4.6.x
1551
+	 * @param string $field_name       The field the current time is needed for.
1552
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1553
+	 *                                 formatted string matching the set format for the field in the set timezone will
1554
+	 *                                 be returned.
1555
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1556
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1557
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1558
+	 *                                 exception is triggered.
1559
+	 */
1560
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1561
+	{
1562
+		$formats = $this->get_formats_for($field_name);
1563
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1564
+		if ($timestamp) {
1565
+			return $DateTime->format('U');
1566
+		}
1567
+		// not returning timestamp, so return formatted string in timezone.
1568
+		switch ($what) {
1569
+			case 'time':
1570
+				return $DateTime->format($formats[1]);
1571
+				break;
1572
+			case 'date':
1573
+				return $DateTime->format($formats[0]);
1574
+				break;
1575
+			default:
1576
+				return $DateTime->format(implode(' ', $formats));
1577
+				break;
1578
+		}
1579
+	}
1580
+
1581
+
1582
+
1583
+	/**
1584
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1585
+	 * for the model are.  Returns a DateTime object.
1586
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1587
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1588
+	 * ignored.
1589
+	 *
1590
+	 * @param string $field_name      The field being setup.
1591
+	 * @param string $timestring      The date time string being used.
1592
+	 * @param string $incoming_format The format for the time string.
1593
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1594
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1595
+	 *                                format is
1596
+	 *                                'U', this is ignored.
1597
+	 * @return DateTime
1598
+	 * @throws EE_Error
1599
+	 */
1600
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1601
+	{
1602
+		// just using this to ensure the timezone is set correctly internally
1603
+		$this->get_formats_for($field_name);
1604
+		// load EEH_DTT_Helper
1605
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1606
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1607
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1608
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1609
+	}
1610
+
1611
+
1612
+
1613
+	/**
1614
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1615
+	 *
1616
+	 * @return EE_Table_Base[]
1617
+	 */
1618
+	public function get_tables()
1619
+	{
1620
+		return $this->_tables;
1621
+	}
1622
+
1623
+
1624
+
1625
+	/**
1626
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1627
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1628
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1629
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1630
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1631
+	 * model object with EVT_ID = 1
1632
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1633
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1634
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1635
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1636
+	 * are not specified)
1637
+	 *
1638
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1639
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1640
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1641
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1642
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1643
+	 *                                         ID=34, we'd use this method as follows:
1644
+	 *                                         EEM_Transaction::instance()->update(
1645
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1646
+	 *                                         array(array('TXN_ID'=>34)));
1647
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1648
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1649
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1650
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1651
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1652
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1653
+	 *                                         TRUE, it is assumed that you've already called
1654
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1655
+	 *                                         malicious javascript. However, if
1656
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1657
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1658
+	 *                                         and every other field, before insertion. We provide this parameter
1659
+	 *                                         because model objects perform their prepare_for_set function on all
1660
+	 *                                         their values, and so don't need to be called again (and in many cases,
1661
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1662
+	 *                                         prepare_for_set method...)
1663
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1664
+	 *                                         in this model's entity map according to $fields_n_values that match
1665
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1666
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1667
+	 *                                         could get out-of-sync with the database
1668
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1669
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1670
+	 *                                         bad)
1671
+	 * @throws EE_Error
1672
+	 */
1673
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674
+	{
1675
+		if (! is_array($query_params)) {
1676
+			EE_Error::doing_it_wrong(
1677
+				'EEM_Base::update',
1678
+				sprintf(
1679
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1680
+					gettype($query_params)
1681
+				),
1682
+				'4.6.0'
1683
+			);
1684
+			$query_params = array();
1685
+		}
1686
+		/**
1687
+		 * Action called before a model update call has been made.
1688
+		 *
1689
+		 * @param EEM_Base $model
1690
+		 * @param array    $fields_n_values the updated fields and their new values
1691
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1692
+		 */
1693
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1694
+		/**
1695
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1696
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1697
+		 *
1698
+		 * @param array    $fields_n_values fields and their new values
1699
+		 * @param EEM_Base $model           the model being queried
1700
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1701
+		 */
1702
+		$fields_n_values = (array) apply_filters(
1703
+			'FHEE__EEM_Base__update__fields_n_values',
1704
+			$fields_n_values,
1705
+			$this,
1706
+			$query_params
1707
+		);
1708
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1709
+		// to do that, for each table, verify that it's PK isn't null.
1710
+		$tables = $this->get_tables();
1711
+		// 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
1712
+		// NOTE: we should make this code more efficient by NOT querying twice
1713
+		// before the real update, but that needs to first go through ALPHA testing
1714
+		// as it's dangerous. says Mike August 8 2014
1715
+		// we want to make sure the default_where strategy is ignored
1716
+		$this->_ignore_where_strategy = true;
1717
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1718
+		foreach ($wpdb_select_results as $wpdb_result) {
1719
+			// type cast stdClass as array
1720
+			$wpdb_result = (array) $wpdb_result;
1721
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1722
+			if ($this->has_primary_key_field()) {
1723
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1724
+			} else {
1725
+				// 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)
1726
+				$main_table_pk_value = null;
1727
+			}
1728
+			// 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
1729
+			// 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
1730
+			if (count($tables) > 1) {
1731
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1732
+				// in that table, and so we'll want to insert one
1733
+				foreach ($tables as $table_obj) {
1734
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1735
+					// if there is no private key for this table on the results, it means there's no entry
1736
+					// in this table, right? so insert a row in the current table, using any fields available
1737
+					if (
1738
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1739
+						   && $wpdb_result[ $this_table_pk_column ])
1740
+					) {
1741
+						$success = $this->_insert_into_specific_table(
1742
+							$table_obj,
1743
+							$fields_n_values,
1744
+							$main_table_pk_value
1745
+						);
1746
+						// if we died here, report the error
1747
+						if (! $success) {
1748
+							return false;
1749
+						}
1750
+					}
1751
+				}
1752
+			}
1753
+			//              //and now check that if we have cached any models by that ID on the model, that
1754
+			//              //they also get updated properly
1755
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1756
+			//              if( $model_object ){
1757
+			//                  foreach( $fields_n_values as $field => $value ){
1758
+			//                      $model_object->set($field, $value);
1759
+			// let's make sure default_where strategy is followed now
1760
+			$this->_ignore_where_strategy = false;
1761
+		}
1762
+		// if we want to keep model objects in sync, AND
1763
+		// if this wasn't called from a model object (to update itself)
1764
+		// then we want to make sure we keep all the existing
1765
+		// model objects in sync with the db
1766
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1767
+			if ($this->has_primary_key_field()) {
1768
+				$model_objs_affected_ids = $this->get_col($query_params);
1769
+			} else {
1770
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1771
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1772
+				$model_objs_affected_ids = array();
1773
+				foreach ($models_affected_key_columns as $row) {
1774
+					$combined_index_key = $this->get_index_primary_key_string($row);
1775
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1776
+				}
1777
+			}
1778
+			if (! $model_objs_affected_ids) {
1779
+				// wait wait wait- if nothing was affected let's stop here
1780
+				return 0;
1781
+			}
1782
+			foreach ($model_objs_affected_ids as $id) {
1783
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1784
+				if ($model_obj_in_entity_map) {
1785
+					foreach ($fields_n_values as $field => $new_value) {
1786
+						$model_obj_in_entity_map->set($field, $new_value);
1787
+					}
1788
+				}
1789
+			}
1790
+			// if there is a primary key on this model, we can now do a slight optimization
1791
+			if ($this->has_primary_key_field()) {
1792
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1793
+				$query_params = array(
1794
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1795
+					'limit'                    => count($model_objs_affected_ids),
1796
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1797
+				);
1798
+			}
1799
+		}
1800
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1801
+		$SQL = "UPDATE "
1802
+			   . $model_query_info->get_full_join_sql()
1803
+			   . " SET "
1804
+			   . $this->_construct_update_sql($fields_n_values)
1805
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1806
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1807
+		/**
1808
+		 * Action called after a model update call has been made.
1809
+		 *
1810
+		 * @param EEM_Base $model
1811
+		 * @param array    $fields_n_values the updated fields and their new values
1812
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1813
+		 * @param int      $rows_affected
1814
+		 */
1815
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1816
+		return $rows_affected;// how many supposedly got updated
1817
+	}
1818
+
1819
+
1820
+
1821
+	/**
1822
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1823
+	 * are teh values of the field specified (or by default the primary key field)
1824
+	 * that matched the query params. Note that you should pass the name of the
1825
+	 * model FIELD, not the database table's column name.
1826
+	 *
1827
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1828
+	 * @param string $field_to_select
1829
+	 * @return array just like $wpdb->get_col()
1830
+	 * @throws EE_Error
1831
+	 */
1832
+	public function get_col($query_params = array(), $field_to_select = null)
1833
+	{
1834
+		if ($field_to_select) {
1835
+			$field = $this->field_settings_for($field_to_select);
1836
+		} elseif ($this->has_primary_key_field()) {
1837
+			$field = $this->get_primary_key_field();
1838
+		} else {
1839
+			// no primary key, just grab the first column
1840
+			$field = reset($this->field_settings());
1841
+		}
1842
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1843
+		$select_expressions = $field->get_qualified_column();
1844
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1845
+		return $this->_do_wpdb_query('get_col', array($SQL));
1846
+	}
1847
+
1848
+
1849
+
1850
+	/**
1851
+	 * Returns a single column value for a single row from the database
1852
+	 *
1853
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1854
+	 * @param string $field_to_select @see EEM_Base::get_col()
1855
+	 * @return string
1856
+	 * @throws EE_Error
1857
+	 */
1858
+	public function get_var($query_params = array(), $field_to_select = null)
1859
+	{
1860
+		$query_params['limit'] = 1;
1861
+		$col = $this->get_col($query_params, $field_to_select);
1862
+		if (! empty($col)) {
1863
+			return reset($col);
1864
+		}
1865
+		return null;
1866
+	}
1867
+
1868
+
1869
+
1870
+	/**
1871
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1872
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1873
+	 * injection, but currently no further filtering is done
1874
+	 *
1875
+	 * @global      $wpdb
1876
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1877
+	 *                               be updated to in the DB
1878
+	 * @return string of SQL
1879
+	 * @throws EE_Error
1880
+	 */
1881
+	public function _construct_update_sql($fields_n_values)
1882
+	{
1883
+		/** @type WPDB $wpdb */
1884
+		global $wpdb;
1885
+		$cols_n_values = array();
1886
+		foreach ($fields_n_values as $field_name => $value) {
1887
+			$field_obj = $this->field_settings_for($field_name);
1888
+			// if the value is NULL, we want to assign the value to that.
1889
+			// wpdb->prepare doesn't really handle that properly
1890
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1891
+			$value_sql = $prepared_value === null ? 'NULL'
1892
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1893
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1894
+		}
1895
+		return implode(",", $cols_n_values);
1896
+	}
1897
+
1898
+
1899
+
1900
+	/**
1901
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1902
+	 * Performs a HARD delete, meaning the database row should always be removed,
1903
+	 * not just have a flag field on it switched
1904
+	 * Wrapper for EEM_Base::delete_permanently()
1905
+	 *
1906
+	 * @param mixed $id
1907
+	 * @param boolean $allow_blocking
1908
+	 * @return int the number of rows deleted
1909
+	 * @throws EE_Error
1910
+	 */
1911
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1912
+	{
1913
+		return $this->delete_permanently(
1914
+			array(
1915
+				array($this->get_primary_key_field()->get_name() => $id),
1916
+				'limit' => 1,
1917
+			),
1918
+			$allow_blocking
1919
+		);
1920
+	}
1921
+
1922
+
1923
+
1924
+	/**
1925
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1926
+	 * Wrapper for EEM_Base::delete()
1927
+	 *
1928
+	 * @param mixed $id
1929
+	 * @param boolean $allow_blocking
1930
+	 * @return int the number of rows deleted
1931
+	 * @throws EE_Error
1932
+	 */
1933
+	public function delete_by_ID($id, $allow_blocking = true)
1934
+	{
1935
+		return $this->delete(
1936
+			array(
1937
+				array($this->get_primary_key_field()->get_name() => $id),
1938
+				'limit' => 1,
1939
+			),
1940
+			$allow_blocking
1941
+		);
1942
+	}
1943
+
1944
+
1945
+
1946
+	/**
1947
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1948
+	 * meaning if the model has a field that indicates its been "trashed" or
1949
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1950
+	 *
1951
+	 * @see EEM_Base::delete_permanently
1952
+	 * @param array   $query_params
1953
+	 * @param boolean $allow_blocking
1954
+	 * @return int how many rows got deleted
1955
+	 * @throws EE_Error
1956
+	 */
1957
+	public function delete($query_params, $allow_blocking = true)
1958
+	{
1959
+		return $this->delete_permanently($query_params, $allow_blocking);
1960
+	}
1961
+
1962
+
1963
+
1964
+	/**
1965
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1966
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1967
+	 * as archived, not actually deleted
1968
+	 *
1969
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1970
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1971
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1972
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1973
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1974
+	 *                                DB
1975
+	 * @return int how many rows got deleted
1976
+	 * @throws EE_Error
1977
+	 */
1978
+	public function delete_permanently($query_params, $allow_blocking = true)
1979
+	{
1980
+		/**
1981
+		 * Action called just before performing a real deletion query. You can use the
1982
+		 * model and its $query_params to find exactly which items will be deleted
1983
+		 *
1984
+		 * @param EEM_Base $model
1985
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1986
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1987
+		 *                                 to block (prevent) this deletion
1988
+		 */
1989
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1990
+		// some MySQL databases may be running safe mode, which may restrict
1991
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1992
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1993
+		// to delete them
1994
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1995
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1996
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1997
+			$columns_and_ids_for_deleting
1998
+		);
1999
+		/**
2000
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2001
+		 *
2002
+		 * @param EEM_Base $this  The model instance being acted on.
2003
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2004
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
2005
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
2006
+		 *                                                  derived from the incoming query parameters.
2007
+		 *                                                  @see details on the structure of this array in the phpdocs
2008
+		 *                                                  for the `_get_ids_for_delete_method`
2009
+		 *
2010
+		 */
2011
+		do_action(
2012
+			'AHEE__EEM_Base__delete__before_query',
2013
+			$this,
2014
+			$query_params,
2015
+			$allow_blocking,
2016
+			$columns_and_ids_for_deleting
2017
+		);
2018
+		if ($deletion_where_query_part) {
2019
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2020
+			$table_aliases = array_keys($this->_tables);
2021
+			$SQL = "DELETE "
2022
+				   . implode(", ", $table_aliases)
2023
+				   . " FROM "
2024
+				   . $model_query_info->get_full_join_sql()
2025
+				   . " WHERE "
2026
+				   . $deletion_where_query_part;
2027
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2028
+		} else {
2029
+			$rows_deleted = 0;
2030
+		}
2031
+
2032
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2033
+		// there was no error with the delete query.
2034
+		if (
2035
+			$this->has_primary_key_field()
2036
+			&& $rows_deleted !== false
2037
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2038
+		) {
2039
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2040
+			foreach ($ids_for_removal as $id) {
2041
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2042
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2043
+				}
2044
+			}
2045
+
2046
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2047
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2048
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2049
+			// (although it is possible).
2050
+			// Note this can be skipped by using the provided filter and returning false.
2051
+			if (
2052
+				apply_filters(
2053
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2054
+					! $this instanceof EEM_Extra_Meta,
2055
+					$this
2056
+				)
2057
+			) {
2058
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2059
+					0 => array(
2060
+						'EXM_type' => $this->get_this_model_name(),
2061
+						'OBJ_ID'   => array(
2062
+							'IN',
2063
+							$ids_for_removal
2064
+						)
2065
+					)
2066
+				));
2067
+			}
2068
+		}
2069
+
2070
+		/**
2071
+		 * Action called just after performing a real deletion query. Although at this point the
2072
+		 * items should have been deleted
2073
+		 *
2074
+		 * @param EEM_Base $model
2075
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2076
+		 * @param int      $rows_deleted
2077
+		 */
2078
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2079
+		return $rows_deleted;// how many supposedly got deleted
2080
+	}
2081
+
2082
+
2083
+
2084
+	/**
2085
+	 * Checks all the relations that throw error messages when there are blocking related objects
2086
+	 * for related model objects. If there are any related model objects on those relations,
2087
+	 * adds an EE_Error, and return true
2088
+	 *
2089
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2090
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2091
+	 *                                                 should be ignored when determining whether there are related
2092
+	 *                                                 model objects which block this model object's deletion. Useful
2093
+	 *                                                 if you know A is related to B and are considering deleting A,
2094
+	 *                                                 but want to see if A has any other objects blocking its deletion
2095
+	 *                                                 before removing the relation between A and B
2096
+	 * @return boolean
2097
+	 * @throws EE_Error
2098
+	 */
2099
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2100
+	{
2101
+		// first, if $ignore_this_model_obj was supplied, get its model
2102
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2103
+			$ignored_model = $ignore_this_model_obj->get_model();
2104
+		} else {
2105
+			$ignored_model = null;
2106
+		}
2107
+		// now check all the relations of $this_model_obj_or_id and see if there
2108
+		// are any related model objects blocking it?
2109
+		$is_blocked = false;
2110
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2111
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2112
+				// if $ignore_this_model_obj was supplied, then for the query
2113
+				// on that model needs to be told to ignore $ignore_this_model_obj
2114
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2115
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2116
+						array(
2117
+							$ignored_model->get_primary_key_field()->get_name() => array(
2118
+								'!=',
2119
+								$ignore_this_model_obj->ID(),
2120
+							),
2121
+						),
2122
+					));
2123
+				} else {
2124
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2125
+				}
2126
+				if ($related_model_objects) {
2127
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2128
+					$is_blocked = true;
2129
+				}
2130
+			}
2131
+		}
2132
+		return $is_blocked;
2133
+	}
2134
+
2135
+
2136
+	/**
2137
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2138
+	 * @param array $row_results_for_deleting
2139
+	 * @param bool  $allow_blocking
2140
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2141
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2142
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2143
+	 *                 deleted. Example:
2144
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2145
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2146
+	 *                 where each element is a group of columns and values that get deleted. Example:
2147
+	 *                      array(
2148
+	 *                          0 => array(
2149
+	 *                              'Term_Relationship.object_id' => 1
2150
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2151
+	 *                          ),
2152
+	 *                          1 => array(
2153
+	 *                              'Term_Relationship.object_id' => 1
2154
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2155
+	 *                          )
2156
+	 *                      )
2157
+	 * @throws EE_Error
2158
+	 */
2159
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2160
+	{
2161
+		$ids_to_delete_indexed_by_column = array();
2162
+		if ($this->has_primary_key_field()) {
2163
+			$primary_table = $this->_get_main_table();
2164
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2165
+			$other_tables = $this->_get_other_tables();
2166
+			$ids_to_delete_indexed_by_column = $query = array();
2167
+			foreach ($row_results_for_deleting as $item_to_delete) {
2168
+				// before we mark this item for deletion,
2169
+				// make sure there's no related entities blocking its deletion (if we're checking)
2170
+				if (
2171
+					$allow_blocking
2172
+					&& $this->delete_is_blocked_by_related_models(
2173
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2174
+					)
2175
+				) {
2176
+					continue;
2177
+				}
2178
+				// primary table deletes
2179
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2180
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2181
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2182
+				}
2183
+			}
2184
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2185
+			$fields = $this->get_combined_primary_key_fields();
2186
+			foreach ($row_results_for_deleting as $item_to_delete) {
2187
+				$ids_to_delete_indexed_by_column_for_row = array();
2188
+				foreach ($fields as $cpk_field) {
2189
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2190
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2191
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2192
+					}
2193
+				}
2194
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2195
+			}
2196
+		} else {
2197
+			// so there's no primary key and no combined key...
2198
+			// sorry, can't help you
2199
+			throw new EE_Error(
2200
+				sprintf(
2201
+					__(
2202
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2203
+						"event_espresso"
2204
+					),
2205
+					get_class($this)
2206
+				)
2207
+			);
2208
+		}
2209
+		return $ids_to_delete_indexed_by_column;
2210
+	}
2211
+
2212
+
2213
+	/**
2214
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2215
+	 * the corresponding query_part for the query performing the delete.
2216
+	 *
2217
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2218
+	 * @return string
2219
+	 * @throws EE_Error
2220
+	 */
2221
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2222
+	{
2223
+		$query_part = '';
2224
+		if (empty($ids_to_delete_indexed_by_column)) {
2225
+			return $query_part;
2226
+		} elseif ($this->has_primary_key_field()) {
2227
+			$query = array();
2228
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2229
+				// make sure we have unique $ids
2230
+				$ids = array_unique($ids);
2231
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2232
+			}
2233
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2234
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2235
+			$ways_to_identify_a_row = array();
2236
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2237
+				$values_for_each_combined_primary_key_for_a_row = array();
2238
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2239
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2240
+				}
2241
+				$ways_to_identify_a_row[] = '('
2242
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2243
+											. ')';
2244
+			}
2245
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2246
+		}
2247
+		return $query_part;
2248
+	}
2249
+
2250
+
2251
+
2252
+	/**
2253
+	 * Gets the model field by the fully qualified name
2254
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2255
+	 * @return EE_Model_Field_Base
2256
+	 */
2257
+	public function get_field_by_column($qualified_column_name)
2258
+	{
2259
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2260
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2261
+				return $field_obj;
2262
+			}
2263
+		}
2264
+		throw new EE_Error(
2265
+			sprintf(
2266
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2267
+				$this->get_this_model_name(),
2268
+				$qualified_column_name
2269
+			)
2270
+		);
2271
+	}
2272
+
2273
+
2274
+
2275
+	/**
2276
+	 * Count all the rows that match criteria the model query params.
2277
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2278
+	 * column
2279
+	 *
2280
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2281
+	 * @param string $field_to_count field on model to count by (not column name)
2282
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2283
+	 *                               that by the setting $distinct to TRUE;
2284
+	 * @return int
2285
+	 * @throws EE_Error
2286
+	 */
2287
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2288
+	{
2289
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2290
+		if ($field_to_count) {
2291
+			$field_obj = $this->field_settings_for($field_to_count);
2292
+			$column_to_count = $field_obj->get_qualified_column();
2293
+		} elseif ($this->has_primary_key_field()) {
2294
+			$pk_field_obj = $this->get_primary_key_field();
2295
+			$column_to_count = $pk_field_obj->get_qualified_column();
2296
+		} else {
2297
+			// there's no primary key
2298
+			// if we're counting distinct items, and there's no primary key,
2299
+			// we need to list out the columns for distinction;
2300
+			// otherwise we can just use star
2301
+			if ($distinct) {
2302
+				$columns_to_use = array();
2303
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2304
+					$columns_to_use[] = $field_obj->get_qualified_column();
2305
+				}
2306
+				$column_to_count = implode(',', $columns_to_use);
2307
+			} else {
2308
+				$column_to_count = '*';
2309
+			}
2310
+		}
2311
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2312
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2314
+	}
2315
+
2316
+
2317
+
2318
+	/**
2319
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2320
+	 *
2321
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2322
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2323
+	 * @return float
2324
+	 * @throws EE_Error
2325
+	 */
2326
+	public function sum($query_params, $field_to_sum = null)
2327
+	{
2328
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2329
+		if ($field_to_sum) {
2330
+			$field_obj = $this->field_settings_for($field_to_sum);
2331
+		} else {
2332
+			$field_obj = $this->get_primary_key_field();
2333
+		}
2334
+		$column_to_count = $field_obj->get_qualified_column();
2335
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2336
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2337
+		$data_type = $field_obj->get_wpdb_data_type();
2338
+		if ($data_type === '%d' || $data_type === '%s') {
2339
+			return (float) $return_value;
2340
+		}
2341
+		// must be %f
2342
+		return (float) $return_value;
2343
+	}
2344
+
2345
+
2346
+
2347
+	/**
2348
+	 * Just calls the specified method on $wpdb with the given arguments
2349
+	 * Consolidates a little extra error handling code
2350
+	 *
2351
+	 * @param string $wpdb_method
2352
+	 * @param array  $arguments_to_provide
2353
+	 * @throws EE_Error
2354
+	 * @global wpdb  $wpdb
2355
+	 * @return mixed
2356
+	 */
2357
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2358
+	{
2359
+		// if we're in maintenance mode level 2, DON'T run any queries
2360
+		// because level 2 indicates the database needs updating and
2361
+		// is probably out of sync with the code
2362
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2363
+			throw new EE_Error(sprintf(__(
2364
+				"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.",
2365
+				"event_espresso"
2366
+			)));
2367
+		}
2368
+		/** @type WPDB $wpdb */
2369
+		global $wpdb;
2370
+		if (! method_exists($wpdb, $wpdb_method)) {
2371
+			throw new EE_Error(sprintf(__(
2372
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2373
+				'event_espresso'
2374
+			), $wpdb_method));
2375
+		}
2376
+		if (WP_DEBUG) {
2377
+			$old_show_errors_value = $wpdb->show_errors;
2378
+			$wpdb->show_errors(false);
2379
+		}
2380
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2381
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2382
+		if (WP_DEBUG) {
2383
+			$wpdb->show_errors($old_show_errors_value);
2384
+			if (! empty($wpdb->last_error)) {
2385
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2386
+			}
2387
+			if ($result === false) {
2388
+				throw new EE_Error(sprintf(__(
2389
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2390
+					'event_espresso'
2391
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2392
+			}
2393
+		} elseif ($result === false) {
2394
+			EE_Error::add_error(
2395
+				sprintf(
2396
+					__(
2397
+						'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"',
2398
+						'event_espresso'
2399
+					),
2400
+					$wpdb_method,
2401
+					var_export($arguments_to_provide, true),
2402
+					$wpdb->last_error
2403
+				),
2404
+				__FILE__,
2405
+				__FUNCTION__,
2406
+				__LINE__
2407
+			);
2408
+		}
2409
+		return $result;
2410
+	}
2411
+
2412
+
2413
+
2414
+	/**
2415
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2416
+	 * and if there's an error tries to verify the DB is correct. Uses
2417
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2418
+	 * we should try to fix the EE core db, the addons, or just give up
2419
+	 *
2420
+	 * @param string $wpdb_method
2421
+	 * @param array  $arguments_to_provide
2422
+	 * @return mixed
2423
+	 */
2424
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2425
+	{
2426
+		/** @type WPDB $wpdb */
2427
+		global $wpdb;
2428
+		$wpdb->last_error = null;
2429
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2430
+		// was there an error running the query? but we don't care on new activations
2431
+		// (we're going to setup the DB anyway on new activations)
2432
+		if (
2433
+			($result === false || ! empty($wpdb->last_error))
2434
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2435
+		) {
2436
+			switch (EEM_Base::$_db_verification_level) {
2437
+				case EEM_Base::db_verified_none:
2438
+					// let's double-check core's DB
2439
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2440
+					break;
2441
+				case EEM_Base::db_verified_core:
2442
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2443
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2444
+					break;
2445
+				case EEM_Base::db_verified_addons:
2446
+					// ummmm... you in trouble
2447
+					return $result;
2448
+					break;
2449
+			}
2450
+			if (! empty($error_message)) {
2451
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2452
+				trigger_error($error_message);
2453
+			}
2454
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2455
+		}
2456
+		return $result;
2457
+	}
2458
+
2459
+
2460
+
2461
+	/**
2462
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2463
+	 * EEM_Base::$_db_verification_level
2464
+	 *
2465
+	 * @param string $wpdb_method
2466
+	 * @param array  $arguments_to_provide
2467
+	 * @return string
2468
+	 */
2469
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2470
+	{
2471
+		/** @type WPDB $wpdb */
2472
+		global $wpdb;
2473
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2474
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2475
+		$error_message = sprintf(
2476
+			__(
2477
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2478
+				'event_espresso'
2479
+			),
2480
+			$wpdb->last_error,
2481
+			$wpdb_method,
2482
+			wp_json_encode($arguments_to_provide)
2483
+		);
2484
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2485
+		return $error_message;
2486
+	}
2487
+
2488
+
2489
+
2490
+	/**
2491
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2492
+	 * EEM_Base::$_db_verification_level
2493
+	 *
2494
+	 * @param $wpdb_method
2495
+	 * @param $arguments_to_provide
2496
+	 * @return string
2497
+	 */
2498
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2499
+	{
2500
+		/** @type WPDB $wpdb */
2501
+		global $wpdb;
2502
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2503
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2504
+		$error_message = sprintf(
2505
+			__(
2506
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2507
+				'event_espresso'
2508
+			),
2509
+			$wpdb->last_error,
2510
+			$wpdb_method,
2511
+			wp_json_encode($arguments_to_provide)
2512
+		);
2513
+		EE_System::instance()->initialize_addons();
2514
+		return $error_message;
2515
+	}
2516
+
2517
+
2518
+
2519
+	/**
2520
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2521
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2522
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2523
+	 * ..."
2524
+	 *
2525
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2526
+	 * @return string
2527
+	 */
2528
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2529
+	{
2530
+		return " FROM " . $model_query_info->get_full_join_sql() .
2531
+			   $model_query_info->get_where_sql() .
2532
+			   $model_query_info->get_group_by_sql() .
2533
+			   $model_query_info->get_having_sql() .
2534
+			   $model_query_info->get_order_by_sql() .
2535
+			   $model_query_info->get_limit_sql();
2536
+	}
2537
+
2538
+
2539
+
2540
+	/**
2541
+	 * Set to easily debug the next X queries ran from this model.
2542
+	 *
2543
+	 * @param int $count
2544
+	 */
2545
+	public function show_next_x_db_queries($count = 1)
2546
+	{
2547
+		$this->_show_next_x_db_queries = $count;
2548
+	}
2549
+
2550
+
2551
+
2552
+	/**
2553
+	 * @param $sql_query
2554
+	 */
2555
+	public function show_db_query_if_previously_requested($sql_query)
2556
+	{
2557
+		if ($this->_show_next_x_db_queries > 0) {
2558
+			echo $sql_query;
2559
+			$this->_show_next_x_db_queries--;
2560
+		}
2561
+	}
2562
+
2563
+
2564
+
2565
+	/**
2566
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2567
+	 * There are the 3 cases:
2568
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2569
+	 * $otherModelObject has no ID, it is first saved.
2570
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2571
+	 * has no ID, it is first saved.
2572
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2573
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2574
+	 * join table
2575
+	 *
2576
+	 * @param        EE_Base_Class                     /int $thisModelObject
2577
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2578
+	 * @param string $relationName                     , key in EEM_Base::_relations
2579
+	 *                                                 an attendee to a group, you also want to specify which role they
2580
+	 *                                                 will have in that group. So you would use this parameter to
2581
+	 *                                                 specify array('role-column-name'=>'role-id')
2582
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2583
+	 *                                                 to for relation to methods that allow you to further specify
2584
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2585
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2586
+	 *                                                 because these will be inserted in any new rows created as well.
2587
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2588
+	 * @throws EE_Error
2589
+	 */
2590
+	public function add_relationship_to(
2591
+		$id_or_obj,
2592
+		$other_model_id_or_obj,
2593
+		$relationName,
2594
+		$extra_join_model_fields_n_values = array()
2595
+	) {
2596
+		$relation_obj = $this->related_settings_for($relationName);
2597
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2598
+	}
2599
+
2600
+
2601
+
2602
+	/**
2603
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2604
+	 * There are the 3 cases:
2605
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2606
+	 * error
2607
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2608
+	 * an error
2609
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2610
+	 *
2611
+	 * @param        EE_Base_Class /int $id_or_obj
2612
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2613
+	 * @param string $relationName key in EEM_Base::_relations
2614
+	 * @return boolean of success
2615
+	 * @throws EE_Error
2616
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2617
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2618
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2619
+	 *                             because these will be inserted in any new rows created as well.
2620
+	 */
2621
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2622
+	{
2623
+		$relation_obj = $this->related_settings_for($relationName);
2624
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2625
+	}
2626
+
2627
+
2628
+
2629
+	/**
2630
+	 * @param mixed           $id_or_obj
2631
+	 * @param string          $relationName
2632
+	 * @param array           $where_query_params
2633
+	 * @param EE_Base_Class[] objects to which relations were removed
2634
+	 * @return \EE_Base_Class[]
2635
+	 * @throws EE_Error
2636
+	 */
2637
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2638
+	{
2639
+		$relation_obj = $this->related_settings_for($relationName);
2640
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2641
+	}
2642
+
2643
+
2644
+
2645
+	/**
2646
+	 * Gets all the related items of the specified $model_name, using $query_params.
2647
+	 * Note: by default, we remove the "default query params"
2648
+	 * because we want to get even deleted items etc.
2649
+	 *
2650
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2651
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2652
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2653
+	 * @return EE_Base_Class[]
2654
+	 * @throws EE_Error
2655
+	 */
2656
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2657
+	{
2658
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2659
+		$relation_settings = $this->related_settings_for($model_name);
2660
+		return $relation_settings->get_all_related($model_obj, $query_params);
2661
+	}
2662
+
2663
+
2664
+
2665
+	/**
2666
+	 * Deletes all the model objects across the relation indicated by $model_name
2667
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2668
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2669
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2670
+	 *
2671
+	 * @param EE_Base_Class|int|string $id_or_obj
2672
+	 * @param string                   $model_name
2673
+	 * @param array                    $query_params
2674
+	 * @return int how many deleted
2675
+	 * @throws EE_Error
2676
+	 */
2677
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2678
+	{
2679
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2680
+		$relation_settings = $this->related_settings_for($model_name);
2681
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2682
+	}
2683
+
2684
+
2685
+
2686
+	/**
2687
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2688
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2689
+	 * the model objects can't be hard deleted because of blocking related model objects,
2690
+	 * just does a soft-delete on them instead.
2691
+	 *
2692
+	 * @param EE_Base_Class|int|string $id_or_obj
2693
+	 * @param string                   $model_name
2694
+	 * @param array                    $query_params
2695
+	 * @return int how many deleted
2696
+	 * @throws EE_Error
2697
+	 */
2698
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2699
+	{
2700
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2701
+		$relation_settings = $this->related_settings_for($model_name);
2702
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2703
+	}
2704
+
2705
+
2706
+
2707
+	/**
2708
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2709
+	 * unless otherwise specified in the $query_params
2710
+	 *
2711
+	 * @param        int             /EE_Base_Class $id_or_obj
2712
+	 * @param string $model_name     like 'Event', or 'Registration'
2713
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2714
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2715
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2716
+	 *                               that by the setting $distinct to TRUE;
2717
+	 * @return int
2718
+	 * @throws EE_Error
2719
+	 */
2720
+	public function count_related(
2721
+		$id_or_obj,
2722
+		$model_name,
2723
+		$query_params = array(),
2724
+		$field_to_count = null,
2725
+		$distinct = false
2726
+	) {
2727
+		$related_model = $this->get_related_model_obj($model_name);
2728
+		// we're just going to use the query params on the related model's normal get_all query,
2729
+		// except add a condition to say to match the current mod
2730
+		if (! isset($query_params['default_where_conditions'])) {
2731
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2732
+		}
2733
+		$this_model_name = $this->get_this_model_name();
2734
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2735
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2736
+		return $related_model->count($query_params, $field_to_count, $distinct);
2737
+	}
2738
+
2739
+
2740
+
2741
+	/**
2742
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2743
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2744
+	 *
2745
+	 * @param        int           /EE_Base_Class $id_or_obj
2746
+	 * @param string $model_name   like 'Event', or 'Registration'
2747
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2748
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2749
+	 * @return float
2750
+	 * @throws EE_Error
2751
+	 */
2752
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2753
+	{
2754
+		$related_model = $this->get_related_model_obj($model_name);
2755
+		if (! is_array($query_params)) {
2756
+			EE_Error::doing_it_wrong(
2757
+				'EEM_Base::sum_related',
2758
+				sprintf(
2759
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2760
+					gettype($query_params)
2761
+				),
2762
+				'4.6.0'
2763
+			);
2764
+			$query_params = array();
2765
+		}
2766
+		// we're just going to use the query params on the related model's normal get_all query,
2767
+		// except add a condition to say to match the current mod
2768
+		if (! isset($query_params['default_where_conditions'])) {
2769
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2770
+		}
2771
+		$this_model_name = $this->get_this_model_name();
2772
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2773
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2774
+		return $related_model->sum($query_params, $field_to_sum);
2775
+	}
2776
+
2777
+
2778
+
2779
+	/**
2780
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2781
+	 * $modelObject
2782
+	 *
2783
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2784
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2785
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2786
+	 * @return EE_Base_Class
2787
+	 * @throws EE_Error
2788
+	 */
2789
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2790
+	{
2791
+		$query_params['limit'] = 1;
2792
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2793
+		if ($results) {
2794
+			return array_shift($results);
2795
+		}
2796
+		return null;
2797
+	}
2798
+
2799
+
2800
+
2801
+	/**
2802
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2803
+	 *
2804
+	 * @return string
2805
+	 */
2806
+	public function get_this_model_name()
2807
+	{
2808
+		return str_replace("EEM_", "", get_class($this));
2809
+	}
2810
+
2811
+
2812
+
2813
+	/**
2814
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2815
+	 *
2816
+	 * @return EE_Any_Foreign_Model_Name_Field
2817
+	 * @throws EE_Error
2818
+	 */
2819
+	public function get_field_containing_related_model_name()
2820
+	{
2821
+		foreach ($this->field_settings(true) as $field) {
2822
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2823
+				$field_with_model_name = $field;
2824
+			}
2825
+		}
2826
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2827
+			throw new EE_Error(sprintf(
2828
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2829
+				$this->get_this_model_name()
2830
+			));
2831
+		}
2832
+		return $field_with_model_name;
2833
+	}
2834
+
2835
+
2836
+
2837
+	/**
2838
+	 * Inserts a new entry into the database, for each table.
2839
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2840
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2841
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2842
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2843
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2844
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2845
+	 *
2846
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2847
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2848
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2849
+	 *                              of EEM_Base)
2850
+	 * @return int|string new primary key on main table that got inserted
2851
+	 * @throws EE_Error
2852
+	 */
2853
+	public function insert($field_n_values)
2854
+	{
2855
+		/**
2856
+		 * Filters the fields and their values before inserting an item using the models
2857
+		 *
2858
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2859
+		 * @param EEM_Base $model           the model used
2860
+		 */
2861
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2862
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2863
+			$main_table = $this->_get_main_table();
2864
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2865
+			if ($new_id !== false) {
2866
+				foreach ($this->_get_other_tables() as $other_table) {
2867
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2868
+				}
2869
+			}
2870
+			/**
2871
+			 * Done just after attempting to insert a new model object
2872
+			 *
2873
+			 * @param EEM_Base   $model           used
2874
+			 * @param array      $fields_n_values fields and their values
2875
+			 * @param int|string the              ID of the newly-inserted model object
2876
+			 */
2877
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2878
+			return $new_id;
2879
+		}
2880
+		return false;
2881
+	}
2882
+
2883
+
2884
+
2885
+	/**
2886
+	 * Checks that the result would satisfy the unique indexes on this model
2887
+	 *
2888
+	 * @param array  $field_n_values
2889
+	 * @param string $action
2890
+	 * @return boolean
2891
+	 * @throws EE_Error
2892
+	 */
2893
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2894
+	{
2895
+		foreach ($this->unique_indexes() as $index_name => $index) {
2896
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2897
+			if ($this->exists(array($uniqueness_where_params))) {
2898
+				EE_Error::add_error(
2899
+					sprintf(
2900
+						__(
2901
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2902
+							"event_espresso"
2903
+						),
2904
+						$action,
2905
+						$this->_get_class_name(),
2906
+						$index_name,
2907
+						implode(",", $index->field_names()),
2908
+						http_build_query($uniqueness_where_params)
2909
+					),
2910
+					__FILE__,
2911
+					__FUNCTION__,
2912
+					__LINE__
2913
+				);
2914
+				return false;
2915
+			}
2916
+		}
2917
+		return true;
2918
+	}
2919
+
2920
+
2921
+
2922
+	/**
2923
+	 * Checks the database for an item that conflicts (ie, if this item were
2924
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2925
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2926
+	 * can be either an EE_Base_Class or an array of fields n values
2927
+	 *
2928
+	 * @param EE_Base_Class|array $obj_or_fields_array
2929
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2930
+	 *                                                 when looking for conflicts
2931
+	 *                                                 (ie, if false, we ignore the model object's primary key
2932
+	 *                                                 when finding "conflicts". If true, it's also considered).
2933
+	 *                                                 Only works for INT primary key,
2934
+	 *                                                 STRING primary keys cannot be ignored
2935
+	 * @throws EE_Error
2936
+	 * @return EE_Base_Class|array
2937
+	 */
2938
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2939
+	{
2940
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2941
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2942
+		} elseif (is_array($obj_or_fields_array)) {
2943
+			$fields_n_values = $obj_or_fields_array;
2944
+		} else {
2945
+			throw new EE_Error(
2946
+				sprintf(
2947
+					__(
2948
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2949
+						"event_espresso"
2950
+					),
2951
+					get_class($this),
2952
+					$obj_or_fields_array
2953
+				)
2954
+			);
2955
+		}
2956
+		$query_params = array();
2957
+		if (
2958
+			$this->has_primary_key_field()
2959
+			&& ($include_primary_key
2960
+				|| $this->get_primary_key_field()
2961
+				   instanceof
2962
+				   EE_Primary_Key_String_Field)
2963
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2964
+		) {
2965
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2966
+		}
2967
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2968
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2969
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2970
+		}
2971
+		// if there is nothing to base this search on, then we shouldn't find anything
2972
+		if (empty($query_params)) {
2973
+			return array();
2974
+		}
2975
+		return $this->get_one($query_params);
2976
+	}
2977
+
2978
+
2979
+
2980
+	/**
2981
+	 * Like count, but is optimized and returns a boolean instead of an int
2982
+	 *
2983
+	 * @param array $query_params
2984
+	 * @return boolean
2985
+	 * @throws EE_Error
2986
+	 */
2987
+	public function exists($query_params)
2988
+	{
2989
+		$query_params['limit'] = 1;
2990
+		return $this->count($query_params) > 0;
2991
+	}
2992
+
2993
+
2994
+
2995
+	/**
2996
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2997
+	 *
2998
+	 * @param int|string $id
2999
+	 * @return boolean
3000
+	 * @throws EE_Error
3001
+	 */
3002
+	public function exists_by_ID($id)
3003
+	{
3004
+		return $this->exists(
3005
+			array(
3006
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
3007
+				array(
3008
+					$this->primary_key_name() => $id,
3009
+				),
3010
+			)
3011
+		);
3012
+	}
3013
+
3014
+
3015
+
3016
+	/**
3017
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3018
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3019
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3020
+	 * on the main table)
3021
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3022
+	 * cases where we want to call it directly rather than via insert().
3023
+	 *
3024
+	 * @access   protected
3025
+	 * @param EE_Table_Base $table
3026
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3027
+	 *                                       float
3028
+	 * @param int           $new_id          for now we assume only int keys
3029
+	 * @throws EE_Error
3030
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3031
+	 * @return int ID of new row inserted, or FALSE on failure
3032
+	 */
3033
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3034
+	{
3035
+		global $wpdb;
3036
+		$insertion_col_n_values = array();
3037
+		$format_for_insertion = array();
3038
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
3039
+		foreach ($fields_on_table as $field_name => $field_obj) {
3040
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3041
+			if ($field_obj->is_auto_increment()) {
3042
+				continue;
3043
+			}
3044
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3045
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3046
+			if ($prepared_value !== null) {
3047
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3048
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3049
+			}
3050
+		}
3051
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3052
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3053
+			// so add the fk to the main table as a column
3054
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3055
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3056
+		}
3057
+		// insert the new entry
3058
+		$result = $this->_do_wpdb_query(
3059
+			'insert',
3060
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3061
+		);
3062
+		if ($result === false) {
3063
+			return false;
3064
+		}
3065
+		// ok, now what do we return for the ID of the newly-inserted thing?
3066
+		if ($this->has_primary_key_field()) {
3067
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3068
+				return $wpdb->insert_id;
3069
+			}
3070
+			// it's not an auto-increment primary key, so
3071
+			// it must have been supplied
3072
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3073
+		}
3074
+		// we can't return a  primary key because there is none. instead return
3075
+		// a unique string indicating this model
3076
+		return $this->get_index_primary_key_string($fields_n_values);
3077
+	}
3078
+
3079
+
3080
+
3081
+	/**
3082
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3083
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3084
+	 * and there is no default, we pass it along. WPDB will take care of it)
3085
+	 *
3086
+	 * @param EE_Model_Field_Base $field_obj
3087
+	 * @param array               $fields_n_values
3088
+	 * @return mixed string|int|float depending on what the table column will be expecting
3089
+	 * @throws EE_Error
3090
+	 */
3091
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3092
+	{
3093
+		// if this field doesn't allow nullable, don't allow it
3094
+		if (
3095
+			! $field_obj->is_nullable()
3096
+			&& (
3097
+				! isset($fields_n_values[ $field_obj->get_name() ])
3098
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3099
+			)
3100
+		) {
3101
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3102
+		}
3103
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3104
+			? $fields_n_values[ $field_obj->get_name() ]
3105
+			: null;
3106
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3107
+	}
3108
+
3109
+
3110
+
3111
+	/**
3112
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3113
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3114
+	 * the field's prepare_for_set() method.
3115
+	 *
3116
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3117
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3118
+	 *                                   top of file)
3119
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3120
+	 *                                   $value is a custom selection
3121
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3122
+	 */
3123
+	private function _prepare_value_for_use_in_db($value, $field)
3124
+	{
3125
+		if ($field && $field instanceof EE_Model_Field_Base) {
3126
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3127
+			switch ($this->_values_already_prepared_by_model_object) {
3128
+				/** @noinspection PhpMissingBreakStatementInspection */
3129
+				case self::not_prepared_by_model_object:
3130
+					$value = $field->prepare_for_set($value);
3131
+				// purposefully left out "return"
3132
+				case self::prepared_by_model_object:
3133
+					/** @noinspection SuspiciousAssignmentsInspection */
3134
+					$value = $field->prepare_for_use_in_db($value);
3135
+				case self::prepared_for_use_in_db:
3136
+					// leave the value alone
3137
+			}
3138
+			return $value;
3139
+			// phpcs:enable
3140
+		}
3141
+		return $value;
3142
+	}
3143
+
3144
+
3145
+
3146
+	/**
3147
+	 * Returns the main table on this model
3148
+	 *
3149
+	 * @return EE_Primary_Table
3150
+	 * @throws EE_Error
3151
+	 */
3152
+	protected function _get_main_table()
3153
+	{
3154
+		foreach ($this->_tables as $table) {
3155
+			if ($table instanceof EE_Primary_Table) {
3156
+				return $table;
3157
+			}
3158
+		}
3159
+		throw new EE_Error(sprintf(__(
3160
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3161
+			'event_espresso'
3162
+		), get_class($this)));
3163
+	}
3164
+
3165
+
3166
+
3167
+	/**
3168
+	 * table
3169
+	 * returns EE_Primary_Table table name
3170
+	 *
3171
+	 * @return string
3172
+	 * @throws EE_Error
3173
+	 */
3174
+	public function table()
3175
+	{
3176
+		return $this->_get_main_table()->get_table_name();
3177
+	}
3178
+
3179
+
3180
+
3181
+	/**
3182
+	 * table
3183
+	 * returns first EE_Secondary_Table table name
3184
+	 *
3185
+	 * @return string
3186
+	 */
3187
+	public function second_table()
3188
+	{
3189
+		// grab second table from tables array
3190
+		$second_table = end($this->_tables);
3191
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3192
+	}
3193
+
3194
+
3195
+
3196
+	/**
3197
+	 * get_table_obj_by_alias
3198
+	 * returns table name given it's alias
3199
+	 *
3200
+	 * @param string $table_alias
3201
+	 * @return EE_Primary_Table | EE_Secondary_Table
3202
+	 */
3203
+	public function get_table_obj_by_alias($table_alias = '')
3204
+	{
3205
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3206
+	}
3207
+
3208
+
3209
+
3210
+	/**
3211
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3212
+	 *
3213
+	 * @return EE_Secondary_Table[]
3214
+	 */
3215
+	protected function _get_other_tables()
3216
+	{
3217
+		$other_tables = array();
3218
+		foreach ($this->_tables as $table_alias => $table) {
3219
+			if ($table instanceof EE_Secondary_Table) {
3220
+				$other_tables[ $table_alias ] = $table;
3221
+			}
3222
+		}
3223
+		return $other_tables;
3224
+	}
3225
+
3226
+
3227
+
3228
+	/**
3229
+	 * Finds all the fields that correspond to the given table
3230
+	 *
3231
+	 * @param string $table_alias , array key in EEM_Base::_tables
3232
+	 * @return EE_Model_Field_Base[]
3233
+	 */
3234
+	public function _get_fields_for_table($table_alias)
3235
+	{
3236
+		return $this->_fields[ $table_alias ];
3237
+	}
3238
+
3239
+
3240
+
3241
+	/**
3242
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3243
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3244
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3245
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3246
+	 * related Registration, Transaction, and Payment models.
3247
+	 *
3248
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3249
+	 * @return EE_Model_Query_Info_Carrier
3250
+	 * @throws EE_Error
3251
+	 */
3252
+	public function _extract_related_models_from_query($query_params)
3253
+	{
3254
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3255
+		if (array_key_exists(0, $query_params)) {
3256
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3257
+		}
3258
+		if (array_key_exists('group_by', $query_params)) {
3259
+			if (is_array($query_params['group_by'])) {
3260
+				$this->_extract_related_models_from_sub_params_array_values(
3261
+					$query_params['group_by'],
3262
+					$query_info_carrier,
3263
+					'group_by'
3264
+				);
3265
+			} elseif (! empty($query_params['group_by'])) {
3266
+				$this->_extract_related_model_info_from_query_param(
3267
+					$query_params['group_by'],
3268
+					$query_info_carrier,
3269
+					'group_by'
3270
+				);
3271
+			}
3272
+		}
3273
+		if (array_key_exists('having', $query_params)) {
3274
+			$this->_extract_related_models_from_sub_params_array_keys(
3275
+				$query_params[0],
3276
+				$query_info_carrier,
3277
+				'having'
3278
+			);
3279
+		}
3280
+		if (array_key_exists('order_by', $query_params)) {
3281
+			if (is_array($query_params['order_by'])) {
3282
+				$this->_extract_related_models_from_sub_params_array_keys(
3283
+					$query_params['order_by'],
3284
+					$query_info_carrier,
3285
+					'order_by'
3286
+				);
3287
+			} elseif (! empty($query_params['order_by'])) {
3288
+				$this->_extract_related_model_info_from_query_param(
3289
+					$query_params['order_by'],
3290
+					$query_info_carrier,
3291
+					'order_by'
3292
+				);
3293
+			}
3294
+		}
3295
+		if (array_key_exists('force_join', $query_params)) {
3296
+			$this->_extract_related_models_from_sub_params_array_values(
3297
+				$query_params['force_join'],
3298
+				$query_info_carrier,
3299
+				'force_join'
3300
+			);
3301
+		}
3302
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3303
+		return $query_info_carrier;
3304
+	}
3305
+
3306
+
3307
+
3308
+	/**
3309
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3310
+	 *
3311
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3312
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3313
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3314
+	 * @throws EE_Error
3315
+	 * @return \EE_Model_Query_Info_Carrier
3316
+	 */
3317
+	private function _extract_related_models_from_sub_params_array_keys(
3318
+		$sub_query_params,
3319
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3320
+		$query_param_type
3321
+	) {
3322
+		if (! empty($sub_query_params)) {
3323
+			$sub_query_params = (array) $sub_query_params;
3324
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3325
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3326
+				$this->_extract_related_model_info_from_query_param(
3327
+					$param,
3328
+					$model_query_info_carrier,
3329
+					$query_param_type
3330
+				);
3331
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3332
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3333
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3334
+				// of array('Registration.TXN_ID'=>23)
3335
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3336
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3337
+					if (! is_array($possibly_array_of_params)) {
3338
+						throw new EE_Error(sprintf(
3339
+							__(
3340
+								"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'))",
3341
+								"event_espresso"
3342
+							),
3343
+							$param,
3344
+							$possibly_array_of_params
3345
+						));
3346
+					}
3347
+					$this->_extract_related_models_from_sub_params_array_keys(
3348
+						$possibly_array_of_params,
3349
+						$model_query_info_carrier,
3350
+						$query_param_type
3351
+					);
3352
+				} elseif (
3353
+					$query_param_type === 0 // ie WHERE
3354
+						  && is_array($possibly_array_of_params)
3355
+						  && isset($possibly_array_of_params[2])
3356
+						  && $possibly_array_of_params[2] == true
3357
+				) {
3358
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3359
+					// indicating that $possible_array_of_params[1] is actually a field name,
3360
+					// from which we should extract query parameters!
3361
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3362
+						throw new EE_Error(sprintf(__(
3363
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3364
+							"event_espresso"
3365
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3366
+					}
3367
+					$this->_extract_related_model_info_from_query_param(
3368
+						$possibly_array_of_params[1],
3369
+						$model_query_info_carrier,
3370
+						$query_param_type
3371
+					);
3372
+				}
3373
+			}
3374
+		}
3375
+		return $model_query_info_carrier;
3376
+	}
3377
+
3378
+
3379
+
3380
+	/**
3381
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3382
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3383
+	 *
3384
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3385
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3386
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3387
+	 * @throws EE_Error
3388
+	 * @return \EE_Model_Query_Info_Carrier
3389
+	 */
3390
+	private function _extract_related_models_from_sub_params_array_values(
3391
+		$sub_query_params,
3392
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3393
+		$query_param_type
3394
+	) {
3395
+		if (! empty($sub_query_params)) {
3396
+			if (! is_array($sub_query_params)) {
3397
+				throw new EE_Error(sprintf(
3398
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399
+					$sub_query_params
3400
+				));
3401
+			}
3402
+			foreach ($sub_query_params as $param) {
3403
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3404
+				$this->_extract_related_model_info_from_query_param(
3405
+					$param,
3406
+					$model_query_info_carrier,
3407
+					$query_param_type
3408
+				);
3409
+			}
3410
+		}
3411
+		return $model_query_info_carrier;
3412
+	}
3413
+
3414
+
3415
+	/**
3416
+	 * Extract all the query parts from  model query params
3417
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3418
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3419
+	 * but use them in a different order. Eg, we need to know what models we are querying
3420
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3421
+	 * other models before we can finalize the where clause SQL.
3422
+	 *
3423
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3424
+	 * @throws EE_Error
3425
+	 * @return EE_Model_Query_Info_Carrier
3426
+	 * @throws ModelConfigurationException
3427
+	 */
3428
+	public function _create_model_query_info_carrier($query_params)
3429
+	{
3430
+		if (! is_array($query_params)) {
3431
+			EE_Error::doing_it_wrong(
3432
+				'EEM_Base::_create_model_query_info_carrier',
3433
+				sprintf(
3434
+					__(
3435
+						'$query_params should be an array, you passed a variable of type %s',
3436
+						'event_espresso'
3437
+					),
3438
+					gettype($query_params)
3439
+				),
3440
+				'4.6.0'
3441
+			);
3442
+			$query_params = array();
3443
+		}
3444
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3445
+		// first check if we should alter the query to account for caps or not
3446
+		// because the caps might require us to do extra joins
3447
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3448
+			$query_params[0] = array_replace_recursive(
3449
+				$query_params[0],
3450
+				$this->caps_where_conditions(
3451
+					$query_params['caps']
3452
+				)
3453
+			);
3454
+		}
3455
+
3456
+		// check if we should alter the query to remove data related to protected
3457
+		// custom post types
3458
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3459
+			$where_param_key_for_password = $this->modelChainAndPassword();
3460
+			// only include if related to a cpt where no password has been set
3461
+			$query_params[0]['OR*nopassword'] = array(
3462
+				$where_param_key_for_password => '',
3463
+				$where_param_key_for_password . '*' => array('IS_NULL')
3464
+			);
3465
+		}
3466
+		$query_object = $this->_extract_related_models_from_query($query_params);
3467
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3468
+		foreach ($query_params[0] as $key => $value) {
3469
+			if (is_int($key)) {
3470
+				throw new EE_Error(
3471
+					sprintf(
3472
+						__(
3473
+							"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.",
3474
+							"event_espresso"
3475
+						),
3476
+						$key,
3477
+						var_export($value, true),
3478
+						var_export($query_params, true),
3479
+						get_class($this)
3480
+					)
3481
+				);
3482
+			}
3483
+		}
3484
+		if (
3485
+			array_key_exists('default_where_conditions', $query_params)
3486
+			&& ! empty($query_params['default_where_conditions'])
3487
+		) {
3488
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3489
+		} else {
3490
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3491
+		}
3492
+		$query_params[0] = array_merge(
3493
+			$this->_get_default_where_conditions_for_models_in_query(
3494
+				$query_object,
3495
+				$use_default_where_conditions,
3496
+				$query_params[0]
3497
+			),
3498
+			$query_params[0]
3499
+		);
3500
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3501
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3502
+		// So we need to setup a subquery and use that for the main join.
3503
+		// Note for now this only works on the primary table for the model.
3504
+		// So for instance, you could set the limit array like this:
3505
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3506
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3507
+			$query_object->set_main_model_join_sql(
3508
+				$this->_construct_limit_join_select(
3509
+					$query_params['on_join_limit'][0],
3510
+					$query_params['on_join_limit'][1]
3511
+				)
3512
+			);
3513
+		}
3514
+		// set limit
3515
+		if (array_key_exists('limit', $query_params)) {
3516
+			if (is_array($query_params['limit'])) {
3517
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3518
+					$e = sprintf(
3519
+						__(
3520
+							"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)",
3521
+							"event_espresso"
3522
+						),
3523
+						http_build_query($query_params['limit'])
3524
+					);
3525
+					throw new EE_Error($e . "|" . $e);
3526
+				}
3527
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3528
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3529
+			} elseif (! empty($query_params['limit'])) {
3530
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3531
+			}
3532
+		}
3533
+		// set order by
3534
+		if (array_key_exists('order_by', $query_params)) {
3535
+			if (is_array($query_params['order_by'])) {
3536
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3537
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3538
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3539
+				if (array_key_exists('order', $query_params)) {
3540
+					throw new EE_Error(
3541
+						sprintf(
3542
+							__(
3543
+								"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 ",
3544
+								"event_espresso"
3545
+							),
3546
+							get_class($this),
3547
+							implode(", ", array_keys($query_params['order_by'])),
3548
+							implode(", ", $query_params['order_by']),
3549
+							$query_params['order']
3550
+						)
3551
+					);
3552
+				}
3553
+				$this->_extract_related_models_from_sub_params_array_keys(
3554
+					$query_params['order_by'],
3555
+					$query_object,
3556
+					'order_by'
3557
+				);
3558
+				// assume it's an array of fields to order by
3559
+				$order_array = array();
3560
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3561
+					$order = $this->_extract_order($order);
3562
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3563
+				}
3564
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3565
+			} elseif (! empty($query_params['order_by'])) {
3566
+				$this->_extract_related_model_info_from_query_param(
3567
+					$query_params['order_by'],
3568
+					$query_object,
3569
+					'order',
3570
+					$query_params['order_by']
3571
+				);
3572
+				$order = isset($query_params['order'])
3573
+					? $this->_extract_order($query_params['order'])
3574
+					: 'DESC';
3575
+				$query_object->set_order_by_sql(
3576
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3577
+				);
3578
+			}
3579
+		}
3580
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3581
+		if (
3582
+			! array_key_exists('order_by', $query_params)
3583
+			&& array_key_exists('order', $query_params)
3584
+			&& ! empty($query_params['order'])
3585
+		) {
3586
+			$pk_field = $this->get_primary_key_field();
3587
+			$order = $this->_extract_order($query_params['order']);
3588
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3589
+		}
3590
+		// set group by
3591
+		if (array_key_exists('group_by', $query_params)) {
3592
+			if (is_array($query_params['group_by'])) {
3593
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3594
+				$group_by_array = array();
3595
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597
+				}
3598
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
+			} elseif (! empty($query_params['group_by'])) {
3600
+				$query_object->set_group_by_sql(
3601
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3602
+				);
3603
+			}
3604
+		}
3605
+		// set having
3606
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3607
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3608
+		}
3609
+		// now, just verify they didn't pass anything wack
3610
+		foreach ($query_params as $query_key => $query_value) {
3611
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3612
+				throw new EE_Error(
3613
+					sprintf(
3614
+						__(
3615
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3616
+							'event_espresso'
3617
+						),
3618
+						$query_key,
3619
+						get_class($this),
3620
+						//                      print_r( $this->_allowed_query_params, TRUE )
3621
+						implode(',', $this->_allowed_query_params)
3622
+					)
3623
+				);
3624
+			}
3625
+		}
3626
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3627
+		if (empty($main_model_join_sql)) {
3628
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3629
+		}
3630
+		return $query_object;
3631
+	}
3632
+
3633
+
3634
+
3635
+	/**
3636
+	 * Gets the where conditions that should be imposed on the query based on the
3637
+	 * context (eg reading frontend, backend, edit or delete).
3638
+	 *
3639
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3640
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3641
+	 * @throws EE_Error
3642
+	 */
3643
+	public function caps_where_conditions($context = self::caps_read)
3644
+	{
3645
+		EEM_Base::verify_is_valid_cap_context($context);
3646
+		$cap_where_conditions = array();
3647
+		$cap_restrictions = $this->caps_missing($context);
3648
+		/**
3649
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3650
+		 */
3651
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3652
+			$cap_where_conditions = array_replace_recursive(
3653
+				$cap_where_conditions,
3654
+				$restriction_if_no_cap->get_default_where_conditions()
3655
+			);
3656
+		}
3657
+		return apply_filters(
3658
+			'FHEE__EEM_Base__caps_where_conditions__return',
3659
+			$cap_where_conditions,
3660
+			$this,
3661
+			$context,
3662
+			$cap_restrictions
3663
+		);
3664
+	}
3665
+
3666
+
3667
+
3668
+	/**
3669
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3670
+	 * otherwise throws an exception
3671
+	 *
3672
+	 * @param string $should_be_order_string
3673
+	 * @return string either ASC, asc, DESC or desc
3674
+	 * @throws EE_Error
3675
+	 */
3676
+	private function _extract_order($should_be_order_string)
3677
+	{
3678
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3679
+			return $should_be_order_string;
3680
+		}
3681
+		throw new EE_Error(
3682
+			sprintf(
3683
+				__(
3684
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3685
+					"event_espresso"
3686
+				),
3687
+				get_class($this),
3688
+				$should_be_order_string
3689
+			)
3690
+		);
3691
+	}
3692
+
3693
+
3694
+
3695
+	/**
3696
+	 * Looks at all the models which are included in this query, and asks each
3697
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3698
+	 * so they can be merged
3699
+	 *
3700
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3701
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3702
+	 *                                                                  'none' means NO default where conditions will
3703
+	 *                                                                  be used AT ALL during this query.
3704
+	 *                                                                  'other_models_only' means default where
3705
+	 *                                                                  conditions from other models will be used, but
3706
+	 *                                                                  not for this primary model. 'all', the default,
3707
+	 *                                                                  means default where conditions will apply as
3708
+	 *                                                                  normal
3709
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3710
+	 * @throws EE_Error
3711
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3712
+	 */
3713
+	private function _get_default_where_conditions_for_models_in_query(
3714
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3715
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3716
+		$where_query_params = array()
3717
+	) {
3718
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720
+			throw new EE_Error(sprintf(
3721
+				__(
3722
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3723
+					"event_espresso"
3724
+				),
3725
+				$use_default_where_conditions,
3726
+				implode(", ", $allowed_used_default_where_conditions_values)
3727
+			));
3728
+		}
3729
+		$universal_query_params = array();
3730
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3731
+			$universal_query_params = $this->_get_default_where_conditions();
3732
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3733
+			$universal_query_params = $this->_get_minimum_where_conditions();
3734
+		}
3735
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3736
+			$related_model = $this->get_related_model_obj($model_name);
3737
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3738
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3739
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3740
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3741
+			} else {
3742
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3743
+				continue;
3744
+			}
3745
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3746
+				$related_model_universal_where_params,
3747
+				$where_query_params,
3748
+				$related_model,
3749
+				$model_relation_path
3750
+			);
3751
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3752
+				$universal_query_params,
3753
+				$overrides
3754
+			);
3755
+		}
3756
+		return $universal_query_params;
3757
+	}
3758
+
3759
+
3760
+
3761
+	/**
3762
+	 * Determines whether or not we should use default where conditions for the model in question
3763
+	 * (this model, or other related models).
3764
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3765
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3766
+	 * We should use default where conditions on related models when they requested to use default where conditions
3767
+	 * on all models, or specifically just on other related models
3768
+	 * @param      $default_where_conditions_value
3769
+	 * @param bool $for_this_model false means this is for OTHER related models
3770
+	 * @return bool
3771
+	 */
3772
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3773
+	{
3774
+		return (
3775
+				   $for_this_model
3776
+				   && in_array(
3777
+					   $default_where_conditions_value,
3778
+					   array(
3779
+						   EEM_Base::default_where_conditions_all,
3780
+						   EEM_Base::default_where_conditions_this_only,
3781
+						   EEM_Base::default_where_conditions_minimum_others,
3782
+					   ),
3783
+					   true
3784
+				   )
3785
+			   )
3786
+			   || (
3787
+				   ! $for_this_model
3788
+				   && in_array(
3789
+					   $default_where_conditions_value,
3790
+					   array(
3791
+						   EEM_Base::default_where_conditions_all,
3792
+						   EEM_Base::default_where_conditions_others_only,
3793
+					   ),
3794
+					   true
3795
+				   )
3796
+			   );
3797
+	}
3798
+
3799
+	/**
3800
+	 * Determines whether or not we should use default minimum conditions for the model in question
3801
+	 * (this model, or other related models).
3802
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3803
+	 * where conditions.
3804
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3805
+	 * on this model or others
3806
+	 * @param      $default_where_conditions_value
3807
+	 * @param bool $for_this_model false means this is for OTHER related models
3808
+	 * @return bool
3809
+	 */
3810
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3811
+	{
3812
+		return (
3813
+				   $for_this_model
3814
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3815
+			   )
3816
+			   || (
3817
+				   ! $for_this_model
3818
+				   && in_array(
3819
+					   $default_where_conditions_value,
3820
+					   array(
3821
+						   EEM_Base::default_where_conditions_minimum_others,
3822
+						   EEM_Base::default_where_conditions_minimum_all,
3823
+					   ),
3824
+					   true
3825
+				   )
3826
+			   );
3827
+	}
3828
+
3829
+
3830
+	/**
3831
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3832
+	 * then we also add a special where condition which allows for that model's primary key
3833
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3834
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3835
+	 *
3836
+	 * @param array    $default_where_conditions
3837
+	 * @param array    $provided_where_conditions
3838
+	 * @param EEM_Base $model
3839
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3840
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3841
+	 * @throws EE_Error
3842
+	 */
3843
+	private function _override_defaults_or_make_null_friendly(
3844
+		$default_where_conditions,
3845
+		$provided_where_conditions,
3846
+		$model,
3847
+		$model_relation_path
3848
+	) {
3849
+		$null_friendly_where_conditions = array();
3850
+		$none_overridden = true;
3851
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3852
+		foreach ($default_where_conditions as $key => $val) {
3853
+			if (isset($provided_where_conditions[ $key ])) {
3854
+				$none_overridden = false;
3855
+			} else {
3856
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3857
+			}
3858
+		}
3859
+		if ($none_overridden && $default_where_conditions) {
3860
+			if ($model->has_primary_key_field()) {
3861
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3862
+																				. "."
3863
+																				. $model->primary_key_name() ] = array('IS NULL');
3864
+			}/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
3867
-        }
3868
-        return $null_friendly_where_conditions;
3869
-    }
3870
-
3871
-
3872
-
3873
-    /**
3874
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3875
-     * default where conditions on all get_all, update, and delete queries done by this model.
3876
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3878
-     *
3879
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3881
-     */
3882
-    private function _get_default_where_conditions($model_relation_path = '')
3883
-    {
3884
-        if ($this->_ignore_where_strategy) {
3885
-            return array();
3886
-        }
3887
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3888
-    }
3889
-
3890
-
3891
-
3892
-    /**
3893
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3897
-     * Similar to _get_default_where_conditions
3898
-     *
3899
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3901
-     */
3902
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3903
-    {
3904
-        if ($this->_ignore_where_strategy) {
3905
-            return array();
3906
-        }
3907
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3908
-    }
3909
-
3910
-
3911
-
3912
-    /**
3913
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3914
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3915
-     *
3916
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3917
-     * @return string
3918
-     * @throws EE_Error
3919
-     */
3920
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3921
-    {
3922
-        $selects = $this->_get_columns_to_select_for_this_model();
3923
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3924
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3925
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3926
-            foreach ($other_model_selects as $key => $value) {
3927
-                $selects[] = $value;
3928
-            }
3929
-        }
3930
-        return implode(", ", $selects);
3931
-    }
3932
-
3933
-
3934
-
3935
-    /**
3936
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3937
-     * So that's going to be the columns for all the fields on the model
3938
-     *
3939
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3940
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3941
-     */
3942
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3943
-    {
3944
-        $fields = $this->field_settings();
3945
-        $selects = array();
3946
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3947
-            $model_relation_chain,
3948
-            $this->get_this_model_name()
3949
-        );
3950
-        foreach ($fields as $field_obj) {
3951
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3952
-                         . $field_obj->get_table_alias()
3953
-                         . "."
3954
-                         . $field_obj->get_table_column()
3955
-                         . " AS '"
3956
-                         . $table_alias_with_model_relation_chain_prefix
3957
-                         . $field_obj->get_table_alias()
3958
-                         . "."
3959
-                         . $field_obj->get_table_column()
3960
-                         . "'";
3961
-        }
3962
-        // make sure we are also getting the PKs of each table
3963
-        $tables = $this->get_tables();
3964
-        if (count($tables) > 1) {
3965
-            foreach ($tables as $table_obj) {
3966
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3967
-                                       . $table_obj->get_fully_qualified_pk_column();
3968
-                if (! in_array($qualified_pk_column, $selects)) {
3969
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3970
-                }
3971
-            }
3972
-        }
3973
-        return $selects;
3974
-    }
3975
-
3976
-
3977
-
3978
-    /**
3979
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3980
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3981
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3982
-     * SQL for joining, and the data types
3983
-     *
3984
-     * @param null|string                 $original_query_param
3985
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3986
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3987
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3988
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3989
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3990
-     *                                                          or 'Registration's
3991
-     * @param string                      $original_query_param what it originally was (eg
3992
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3993
-     *                                                          matches $query_param
3994
-     * @throws EE_Error
3995
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3996
-     */
3997
-    private function _extract_related_model_info_from_query_param(
3998
-        $query_param,
3999
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4000
-        $query_param_type,
4001
-        $original_query_param = null
4002
-    ) {
4003
-        if ($original_query_param === null) {
4004
-            $original_query_param = $query_param;
4005
-        }
4006
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4007
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
4008
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
4009
-        $allow_fields = in_array(
4010
-            $query_param_type,
4011
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
4012
-            true
4013
-        );
4014
-        // check to see if we have a field on this model
4015
-        $this_model_fields = $this->field_settings(true);
4016
-        if (array_key_exists($query_param, $this_model_fields)) {
4017
-            if ($allow_fields) {
4018
-                return;
4019
-            }
4020
-            throw new EE_Error(
4021
-                sprintf(
4022
-                    __(
4023
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4024
-                        "event_espresso"
4025
-                    ),
4026
-                    $query_param,
4027
-                    get_class($this),
4028
-                    $query_param_type,
4029
-                    $original_query_param
4030
-                )
4031
-            );
4032
-        }
4033
-        // check if this is a special logic query param
4034
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4035
-            if ($allow_logic_query_params) {
4036
-                return;
4037
-            }
4038
-            throw new EE_Error(
4039
-                sprintf(
4040
-                    __(
4041
-                        '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',
4042
-                        'event_espresso'
4043
-                    ),
4044
-                    implode('", "', $this->_logic_query_param_keys),
4045
-                    $query_param,
4046
-                    get_class($this),
4047
-                    '<br />',
4048
-                    "\t"
4049
-                    . ' $passed_in_query_info = <pre>'
4050
-                    . print_r($passed_in_query_info, true)
4051
-                    . '</pre>'
4052
-                    . "\n\t"
4053
-                    . ' $query_param_type = '
4054
-                    . $query_param_type
4055
-                    . "\n\t"
4056
-                    . ' $original_query_param = '
4057
-                    . $original_query_param
4058
-                )
4059
-            );
4060
-        }
4061
-        // check if it's a custom selection
4062
-        if (
4063
-            $this->_custom_selections instanceof CustomSelects
4064
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4065
-        ) {
4066
-            return;
4067
-        }
4068
-        // check if has a model name at the beginning
4069
-        // and
4070
-        // check if it's a field on a related model
4071
-        if (
4072
-            $this->extractJoinModelFromQueryParams(
4073
-                $passed_in_query_info,
4074
-                $query_param,
4075
-                $original_query_param,
4076
-                $query_param_type
4077
-            )
4078
-        ) {
4079
-            return;
4080
-        }
4081
-
4082
-        // ok so $query_param didn't start with a model name
4083
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4084
-        // it's wack, that's what it is
4085
-        throw new EE_Error(
4086
-            sprintf(
4087
-                esc_html__(
4088
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4089
-                    "event_espresso"
4090
-                ),
4091
-                $query_param,
4092
-                get_class($this),
4093
-                $query_param_type,
4094
-                $original_query_param
4095
-            )
4096
-        );
4097
-    }
4098
-
4099
-
4100
-    /**
4101
-     * Extracts any possible join model information from the provided possible_join_string.
4102
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4103
-     * parts that should be added to the query.
4104
-     *
4105
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4106
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4107
-     * @param null|string                 $original_query_param
4108
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4109
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4110
-     * @return bool  returns true if a join was added and false if not.
4111
-     * @throws EE_Error
4112
-     */
4113
-    private function extractJoinModelFromQueryParams(
4114
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4115
-        $possible_join_string,
4116
-        $original_query_param,
4117
-        $query_parameter_type
4118
-    ) {
4119
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4120
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4121
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4122
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4123
-                if ($possible_join_string === '') {
4124
-                    // nothing left to $query_param
4125
-                    // we should actually end in a field name, not a model like this!
4126
-                    throw new EE_Error(
4127
-                        sprintf(
4128
-                            esc_html__(
4129
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4130
-                                "event_espresso"
4131
-                            ),
4132
-                            $possible_join_string,
4133
-                            $query_parameter_type,
4134
-                            get_class($this),
4135
-                            $valid_related_model_name
4136
-                        )
4137
-                    );
4138
-                }
4139
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4140
-                $related_model_obj->_extract_related_model_info_from_query_param(
4141
-                    $possible_join_string,
4142
-                    $query_info_carrier,
4143
-                    $query_parameter_type,
4144
-                    $original_query_param
4145
-                );
4146
-                return true;
4147
-            }
4148
-            if ($possible_join_string === $valid_related_model_name) {
4149
-                $this->_add_join_to_model(
4150
-                    $valid_related_model_name,
4151
-                    $query_info_carrier,
4152
-                    $original_query_param
4153
-                );
4154
-                return true;
4155
-            }
4156
-        }
4157
-        return false;
4158
-    }
4159
-
4160
-
4161
-    /**
4162
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4163
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4164
-     * @throws EE_Error
4165
-     */
4166
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4167
-    {
4168
-        if (
4169
-            $this->_custom_selections instanceof CustomSelects
4170
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4171
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4172
-            )
4173
-        ) {
4174
-            $original_selects = $this->_custom_selections->originalSelects();
4175
-            foreach ($original_selects as $alias => $select_configuration) {
4176
-                $this->extractJoinModelFromQueryParams(
4177
-                    $query_info_carrier,
4178
-                    $select_configuration[0],
4179
-                    $select_configuration[0],
4180
-                    'custom_selects'
4181
-                );
4182
-            }
4183
-        }
4184
-    }
4185
-
4186
-
4187
-
4188
-    /**
4189
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4190
-     * and store it on $passed_in_query_info
4191
-     *
4192
-     * @param string                      $model_name
4193
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4194
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4195
-     *                                                          model and $model_name. Eg, if we are querying Event,
4196
-     *                                                          and are adding a join to 'Payment' with the original
4197
-     *                                                          query param key
4198
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4199
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4200
-     *                                                          Payment wants to add default query params so that it
4201
-     *                                                          will know what models to prepend onto its default query
4202
-     *                                                          params or in case it wants to rename tables (in case
4203
-     *                                                          there are multiple joins to the same table)
4204
-     * @return void
4205
-     * @throws EE_Error
4206
-     */
4207
-    private function _add_join_to_model(
4208
-        $model_name,
4209
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4210
-        $original_query_param
4211
-    ) {
4212
-        $relation_obj = $this->related_settings_for($model_name);
4213
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4214
-        // check if the relation is HABTM, because then we're essentially doing two joins
4215
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4216
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4217
-            $join_model_obj = $relation_obj->get_join_model();
4218
-            // replace the model specified with the join model for this relation chain, whi
4219
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4220
-                $model_name,
4221
-                $join_model_obj->get_this_model_name(),
4222
-                $model_relation_chain
4223
-            );
4224
-            $passed_in_query_info->merge(
4225
-                new EE_Model_Query_Info_Carrier(
4226
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4227
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4228
-                )
4229
-            );
4230
-        }
4231
-        // now just join to the other table pointed to by the relation object, and add its data types
4232
-        $passed_in_query_info->merge(
4233
-            new EE_Model_Query_Info_Carrier(
4234
-                array($model_relation_chain => $model_name),
4235
-                $relation_obj->get_join_statement($model_relation_chain)
4236
-            )
4237
-        );
4238
-    }
4239
-
4240
-
4241
-
4242
-    /**
4243
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4244
-     *
4245
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4246
-     * @return string of SQL
4247
-     * @throws EE_Error
4248
-     */
4249
-    private function _construct_where_clause($where_params)
4250
-    {
4251
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4252
-        if ($SQL) {
4253
-            return " WHERE " . $SQL;
4254
-        }
4255
-        return '';
4256
-    }
4257
-
4258
-
4259
-
4260
-    /**
4261
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4262
-     * and should be passed HAVING parameters, not WHERE parameters
4263
-     *
4264
-     * @param array $having_params
4265
-     * @return string
4266
-     * @throws EE_Error
4267
-     */
4268
-    private function _construct_having_clause($having_params)
4269
-    {
4270
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4271
-        if ($SQL) {
4272
-            return " HAVING " . $SQL;
4273
-        }
4274
-        return '';
4275
-    }
4276
-
4277
-
4278
-    /**
4279
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4280
-     * Event_Meta.meta_value = 'foo'))"
4281
-     *
4282
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4283
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4284
-     * @throws EE_Error
4285
-     * @return string of SQL
4286
-     */
4287
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4288
-    {
4289
-        $where_clauses = array();
4290
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4291
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4292
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4293
-                switch ($query_param) {
4294
-                    case 'not':
4295
-                    case 'NOT':
4296
-                        $where_clauses[] = "! ("
4297
-                                           . $this->_construct_condition_clause_recursive(
4298
-                                               $op_and_value_or_sub_condition,
4299
-                                               $glue
4300
-                                           )
4301
-                                           . ")";
4302
-                        break;
4303
-                    case 'and':
4304
-                    case 'AND':
4305
-                        $where_clauses[] = " ("
4306
-                                           . $this->_construct_condition_clause_recursive(
4307
-                                               $op_and_value_or_sub_condition,
4308
-                                               ' AND '
4309
-                                           )
4310
-                                           . ")";
4311
-                        break;
4312
-                    case 'or':
4313
-                    case 'OR':
4314
-                        $where_clauses[] = " ("
4315
-                                           . $this->_construct_condition_clause_recursive(
4316
-                                               $op_and_value_or_sub_condition,
4317
-                                               ' OR '
4318
-                                           )
4319
-                                           . ")";
4320
-                        break;
4321
-                }
4322
-            } else {
4323
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4324
-                // if it's not a normal field, maybe it's a custom selection?
4325
-                if (! $field_obj) {
4326
-                    if ($this->_custom_selections instanceof CustomSelects) {
4327
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4328
-                    } else {
4329
-                        throw new EE_Error(sprintf(__(
4330
-                            "%s is neither a valid model field name, nor a custom selection",
4331
-                            "event_espresso"
4332
-                        ), $query_param));
4333
-                    }
4334
-                }
4335
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4336
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4337
-            }
4338
-        }
4339
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4340
-    }
4341
-
4342
-
4343
-
4344
-    /**
4345
-     * Takes the input parameter and extract the table name (alias) and column name
4346
-     *
4347
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4348
-     * @throws EE_Error
4349
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4350
-     */
4351
-    private function _deduce_column_name_from_query_param($query_param)
4352
-    {
4353
-        $field = $this->_deduce_field_from_query_param($query_param);
4354
-        if ($field) {
4355
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4356
-                $field->get_model_name(),
4357
-                $query_param
4358
-            );
4359
-            return $table_alias_prefix . $field->get_qualified_column();
4360
-        }
4361
-        if (
4362
-            $this->_custom_selections instanceof CustomSelects
4363
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4364
-        ) {
4365
-            // maybe it's custom selection item?
4366
-            // if so, just use it as the "column name"
4367
-            return $query_param;
4368
-        }
4369
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4370
-            ? implode(',', $this->_custom_selections->columnAliases())
4371
-            : '';
4372
-        throw new EE_Error(
4373
-            sprintf(
4374
-                __(
4375
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4376
-                    "event_espresso"
4377
-                ),
4378
-                $query_param,
4379
-                $custom_select_aliases
4380
-            )
4381
-        );
4382
-    }
4383
-
4384
-
4385
-
4386
-    /**
4387
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4388
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4389
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4390
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4391
-     *
4392
-     * @param string $condition_query_param_key
4393
-     * @return string
4394
-     */
4395
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4396
-    {
4397
-        $pos_of_star = strpos($condition_query_param_key, '*');
4398
-        if ($pos_of_star === false) {
4399
-            return $condition_query_param_key;
4400
-        }
4401
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4402
-        return $condition_query_param_sans_star;
4403
-    }
4404
-
4405
-
4406
-
4407
-    /**
4408
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4409
-     *
4410
-     * @param                            mixed      array | string    $op_and_value
4411
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4412
-     * @throws EE_Error
4413
-     * @return string
4414
-     */
4415
-    private function _construct_op_and_value($op_and_value, $field_obj)
4416
-    {
4417
-        if (is_array($op_and_value)) {
4418
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4419
-            if (! $operator) {
4420
-                $php_array_like_string = array();
4421
-                foreach ($op_and_value as $key => $value) {
4422
-                    $php_array_like_string[] = "$key=>$value";
4423
-                }
4424
-                throw new EE_Error(
4425
-                    sprintf(
4426
-                        __(
4427
-                            "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))",
4428
-                            "event_espresso"
4429
-                        ),
4430
-                        implode(",", $php_array_like_string)
4431
-                    )
4432
-                );
4433
-            }
4434
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4435
-        } else {
4436
-            $operator = '=';
4437
-            $value = $op_and_value;
4438
-        }
4439
-        // check to see if the value is actually another field
4440
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4441
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4442
-        }
4443
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4444
-            // in this case, the value should be an array, or at least a comma-separated list
4445
-            // it will need to handle a little differently
4446
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4447
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4448
-            return $operator . SP . $cleaned_value;
4449
-        }
4450
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4451
-            // the value should be an array with count of two.
4452
-            if (count($value) !== 2) {
4453
-                throw new EE_Error(
4454
-                    sprintf(
4455
-                        __(
4456
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4457
-                            'event_espresso'
4458
-                        ),
4459
-                        "BETWEEN"
4460
-                    )
4461
-                );
4462
-            }
4463
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4464
-            return $operator . SP . $cleaned_value;
4465
-        }
4466
-        if (in_array($operator, $this->valid_null_style_operators())) {
4467
-            if ($value !== null) {
4468
-                throw new EE_Error(
4469
-                    sprintf(
4470
-                        __(
4471
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4472
-                            "event_espresso"
4473
-                        ),
4474
-                        $value,
4475
-                        $operator
4476
-                    )
4477
-                );
4478
-            }
4479
-            return $operator;
4480
-        }
4481
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4482
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4483
-            // remove other junk. So just treat it as a string.
4484
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4485
-        }
4486
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4488
-        }
4489
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4490
-            throw new EE_Error(
4491
-                sprintf(
4492
-                    __(
4493
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4494
-                        'event_espresso'
4495
-                    ),
4496
-                    $operator,
4497
-                    $operator
4498
-                )
4499
-            );
4500
-        }
4501
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4502
-            throw new EE_Error(
4503
-                sprintf(
4504
-                    __(
4505
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4506
-                        'event_espresso'
4507
-                    ),
4508
-                    $operator,
4509
-                    $operator
4510
-                )
4511
-            );
4512
-        }
4513
-        throw new EE_Error(
4514
-            sprintf(
4515
-                __(
4516
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4517
-                    "event_espresso"
4518
-                ),
4519
-                http_build_query($op_and_value)
4520
-            )
4521
-        );
4522
-    }
4523
-
4524
-
4525
-
4526
-    /**
4527
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4528
-     *
4529
-     * @param array                      $values
4530
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4531
-     *                                              '%s'
4532
-     * @return string
4533
-     * @throws EE_Error
4534
-     */
4535
-    public function _construct_between_value($values, $field_obj)
4536
-    {
4537
-        $cleaned_values = array();
4538
-        foreach ($values as $value) {
4539
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4540
-        }
4541
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4542
-    }
4543
-
4544
-
4545
-
4546
-    /**
4547
-     * Takes an array or a comma-separated list of $values and cleans them
4548
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4549
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4550
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4551
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4552
-     *
4553
-     * @param mixed                      $values    array or comma-separated string
4554
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4555
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4556
-     * @throws EE_Error
4557
-     */
4558
-    public function _construct_in_value($values, $field_obj)
4559
-    {
4560
-        // check if the value is a CSV list
4561
-        if (is_string($values)) {
4562
-            // in which case, turn it into an array
4563
-            $values = explode(",", $values);
4564
-        }
4565
-        $cleaned_values = array();
4566
-        foreach ($values as $value) {
4567
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4568
-        }
4569
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4570
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4571
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4572
-        if (empty($cleaned_values)) {
4573
-            $all_fields = $this->field_settings();
4574
-            $a_field = array_shift($all_fields);
4575
-            $main_table = $this->_get_main_table();
4576
-            $cleaned_values[] = "SELECT "
4577
-                                . $a_field->get_table_column()
4578
-                                . " FROM "
4579
-                                . $main_table->get_table_name()
4580
-                                . " WHERE FALSE";
4581
-        }
4582
-        return "(" . implode(",", $cleaned_values) . ")";
4583
-    }
4584
-
4585
-
4586
-
4587
-    /**
4588
-     * @param mixed                      $value
4589
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4590
-     * @throws EE_Error
4591
-     * @return false|null|string
4592
-     */
4593
-    private function _wpdb_prepare_using_field($value, $field_obj)
4594
-    {
4595
-        /** @type WPDB $wpdb */
4596
-        global $wpdb;
4597
-        if ($field_obj instanceof EE_Model_Field_Base) {
4598
-            return $wpdb->prepare(
4599
-                $field_obj->get_wpdb_data_type(),
4600
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4601
-            );
4602
-        } //$field_obj should really just be a data type
4603
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4604
-            throw new EE_Error(
4605
-                sprintf(
4606
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4607
-                    $field_obj,
4608
-                    implode(",", $this->_valid_wpdb_data_types)
4609
-                )
4610
-            );
4611
-        }
4612
-        return $wpdb->prepare($field_obj, $value);
4613
-    }
4614
-
4615
-
4616
-
4617
-    /**
4618
-     * Takes the input parameter and finds the model field that it indicates.
4619
-     *
4620
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4621
-     * @throws EE_Error
4622
-     * @return EE_Model_Field_Base
4623
-     */
4624
-    protected function _deduce_field_from_query_param($query_param_name)
4625
-    {
4626
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4627
-        // which will help us find the database table and column
4628
-        $query_param_parts = explode(".", $query_param_name);
4629
-        if (empty($query_param_parts)) {
4630
-            throw new EE_Error(sprintf(__(
4631
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4632
-                'event_espresso'
4633
-            ), $query_param_name));
4634
-        }
4635
-        $number_of_parts = count($query_param_parts);
4636
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4637
-        if ($number_of_parts === 1) {
4638
-            $field_name = $last_query_param_part;
4639
-            $model_obj = $this;
4640
-        } else {// $number_of_parts >= 2
4641
-            // the last part is the column name, and there are only 2parts. therefore...
4642
-            $field_name = $last_query_param_part;
4643
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4644
-        }
4645
-        try {
4646
-            return $model_obj->field_settings_for($field_name);
4647
-        } catch (EE_Error $e) {
4648
-            return null;
4649
-        }
4650
-    }
4651
-
4652
-
4653
-
4654
-    /**
4655
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4656
-     * alias and column which corresponds to it
4657
-     *
4658
-     * @param string $field_name
4659
-     * @throws EE_Error
4660
-     * @return string
4661
-     */
4662
-    public function _get_qualified_column_for_field($field_name)
4663
-    {
4664
-        $all_fields = $this->field_settings();
4665
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4666
-        if ($field) {
4667
-            return $field->get_qualified_column();
4668
-        }
4669
-        throw new EE_Error(
4670
-            sprintf(
4671
-                __(
4672
-                    "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.",
4673
-                    'event_espresso'
4674
-                ),
4675
-                $field_name,
4676
-                get_class($this)
4677
-            )
4678
-        );
4679
-    }
4680
-
4681
-
4682
-
4683
-    /**
4684
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4685
-     * Example usage:
4686
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4687
-     *      array(),
4688
-     *      ARRAY_A,
4689
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4690
-     *  );
4691
-     * is equivalent to
4692
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4693
-     * and
4694
-     *  EEM_Event::instance()->get_all_wpdb_results(
4695
-     *      array(
4696
-     *          array(
4697
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4698
-     *          ),
4699
-     *          ARRAY_A,
4700
-     *          implode(
4701
-     *              ', ',
4702
-     *              array_merge(
4703
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4704
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4705
-     *              )
4706
-     *          )
4707
-     *      )
4708
-     *  );
4709
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4710
-     *
4711
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4712
-     *                                            and the one whose fields you are selecting for example: when querying
4713
-     *                                            tickets model and selecting fields from the tickets model you would
4714
-     *                                            leave this parameter empty, because no models are needed to join
4715
-     *                                            between the queried model and the selected one. Likewise when
4716
-     *                                            querying the datetime model and selecting fields from the tickets
4717
-     *                                            model, it would also be left empty, because there is a direct
4718
-     *                                            relation from datetimes to tickets, so no model is needed to join
4719
-     *                                            them together. However, when querying from the event model and
4720
-     *                                            selecting fields from the ticket model, you should provide the string
4721
-     *                                            'Datetime', indicating that the event model must first join to the
4722
-     *                                            datetime model in order to find its relation to ticket model.
4723
-     *                                            Also, when querying from the venue model and selecting fields from
4724
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4725
-     *                                            indicating you need to join the venue model to the event model,
4726
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4727
-     *                                            This string is used to deduce the prefix that gets added onto the
4728
-     *                                            models' tables qualified columns
4729
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4730
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4731
-     *                                            qualified column names
4732
-     * @return array|string
4733
-     */
4734
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4735
-    {
4736
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4737
-        $qualified_columns = array();
4738
-        foreach ($this->field_settings() as $field_name => $field) {
4739
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4740
-        }
4741
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4742
-    }
4743
-
4744
-
4745
-
4746
-    /**
4747
-     * constructs the select use on special limit joins
4748
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4749
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4750
-     * (as that is typically where the limits would be set).
4751
-     *
4752
-     * @param  string       $table_alias The table the select is being built for
4753
-     * @param  mixed|string $limit       The limit for this select
4754
-     * @return string                The final select join element for the query.
4755
-     */
4756
-    public function _construct_limit_join_select($table_alias, $limit)
4757
-    {
4758
-        $SQL = '';
4759
-        foreach ($this->_tables as $table_obj) {
4760
-            if ($table_obj instanceof EE_Primary_Table) {
4761
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4762
-                    ? $table_obj->get_select_join_limit($limit)
4763
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4764
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4765
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4766
-                    ? $table_obj->get_select_join_limit_join($limit)
4767
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4768
-            }
4769
-        }
4770
-        return $SQL;
4771
-    }
4772
-
4773
-
4774
-
4775
-    /**
4776
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4777
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4778
-     *
4779
-     * @return string SQL
4780
-     * @throws EE_Error
4781
-     */
4782
-    public function _construct_internal_join()
4783
-    {
4784
-        $SQL = $this->_get_main_table()->get_table_sql();
4785
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4786
-        return $SQL;
4787
-    }
4788
-
4789
-
4790
-
4791
-    /**
4792
-     * Constructs the SQL for joining all the tables on this model.
4793
-     * Normally $alias should be the primary table's alias, but in cases where
4794
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4795
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4796
-     * alias, this will construct SQL like:
4797
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4798
-     * With $alias being a secondary table's alias, this will construct SQL like:
4799
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4800
-     *
4801
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4802
-     * @return string
4803
-     */
4804
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4805
-    {
4806
-        $SQL = '';
4807
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4808
-        foreach ($this->_tables as $table_obj) {
4809
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4810
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4811
-                    // so we're joining to this table, meaning the table is already in
4812
-                    // the FROM statement, BUT the primary table isn't. So we want
4813
-                    // to add the inverse join sql
4814
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4815
-                } else {
4816
-                    // just add a regular JOIN to this table from the primary table
4817
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4818
-                }
4819
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4820
-        }
4821
-        return $SQL;
4822
-    }
4823
-
4824
-
4825
-
4826
-    /**
4827
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4828
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4829
-     * their data type (eg, '%s', '%d', etc)
4830
-     *
4831
-     * @return array
4832
-     */
4833
-    public function _get_data_types()
4834
-    {
4835
-        $data_types = array();
4836
-        foreach ($this->field_settings() as $field_obj) {
4837
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4838
-            /** @var $field_obj EE_Model_Field_Base */
4839
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4840
-        }
4841
-        return $data_types;
4842
-    }
4843
-
4844
-
4845
-
4846
-    /**
4847
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4848
-     *
4849
-     * @param string $model_name
4850
-     * @throws EE_Error
4851
-     * @return EEM_Base
4852
-     */
4853
-    public function get_related_model_obj($model_name)
4854
-    {
4855
-        $model_classname = "EEM_" . $model_name;
4856
-        if (! class_exists($model_classname)) {
4857
-            throw new EE_Error(sprintf(__(
4858
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4859
-                'event_espresso'
4860
-            ), $model_name, $model_classname));
4861
-        }
4862
-        return call_user_func($model_classname . "::instance");
4863
-    }
4864
-
4865
-
4866
-
4867
-    /**
4868
-     * Returns the array of EE_ModelRelations for this model.
4869
-     *
4870
-     * @return EE_Model_Relation_Base[]
4871
-     */
4872
-    public function relation_settings()
4873
-    {
4874
-        return $this->_model_relations;
4875
-    }
4876
-
4877
-
4878
-
4879
-    /**
4880
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4881
-     * because without THOSE models, this model probably doesn't have much purpose.
4882
-     * (Eg, without an event, datetimes have little purpose.)
4883
-     *
4884
-     * @return EE_Belongs_To_Relation[]
4885
-     */
4886
-    public function belongs_to_relations()
4887
-    {
4888
-        $belongs_to_relations = array();
4889
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4890
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4891
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4892
-            }
4893
-        }
4894
-        return $belongs_to_relations;
4895
-    }
4896
-
4897
-
4898
-
4899
-    /**
4900
-     * Returns the specified EE_Model_Relation, or throws an exception
4901
-     *
4902
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4903
-     * @throws EE_Error
4904
-     * @return EE_Model_Relation_Base
4905
-     */
4906
-    public function related_settings_for($relation_name)
4907
-    {
4908
-        $relatedModels = $this->relation_settings();
4909
-        if (! array_key_exists($relation_name, $relatedModels)) {
4910
-            throw new EE_Error(
4911
-                sprintf(
4912
-                    __(
4913
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4914
-                        'event_espresso'
4915
-                    ),
4916
-                    $relation_name,
4917
-                    $this->_get_class_name(),
4918
-                    implode(', ', array_keys($relatedModels))
4919
-                )
4920
-            );
4921
-        }
4922
-        return $relatedModels[ $relation_name ];
4923
-    }
4924
-
4925
-
4926
-
4927
-    /**
4928
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4929
-     * fields
4930
-     *
4931
-     * @param string $fieldName
4932
-     * @param boolean $include_db_only_fields
4933
-     * @throws EE_Error
4934
-     * @return EE_Model_Field_Base
4935
-     */
4936
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4937
-    {
4938
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4939
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4940
-            throw new EE_Error(sprintf(
4941
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4942
-                $fieldName,
4943
-                get_class($this)
4944
-            ));
4945
-        }
4946
-        return $fieldSettings[ $fieldName ];
4947
-    }
4948
-
4949
-
4950
-
4951
-    /**
4952
-     * Checks if this field exists on this model
4953
-     *
4954
-     * @param string $fieldName a key in the model's _field_settings array
4955
-     * @return boolean
4956
-     */
4957
-    public function has_field($fieldName)
4958
-    {
4959
-        $fieldSettings = $this->field_settings(true);
4960
-        if (isset($fieldSettings[ $fieldName ])) {
4961
-            return true;
4962
-        }
4963
-        return false;
4964
-    }
4965
-
4966
-
4967
-
4968
-    /**
4969
-     * Returns whether or not this model has a relation to the specified model
4970
-     *
4971
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4972
-     * @return boolean
4973
-     */
4974
-    public function has_relation($relation_name)
4975
-    {
4976
-        $relations = $this->relation_settings();
4977
-        if (isset($relations[ $relation_name ])) {
4978
-            return true;
4979
-        }
4980
-        return false;
4981
-    }
4982
-
4983
-
4984
-
4985
-    /**
4986
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4987
-     * Eg, on EE_Answer that would be ANS_ID field object
4988
-     *
4989
-     * @param $field_obj
4990
-     * @return boolean
4991
-     */
4992
-    public function is_primary_key_field($field_obj)
4993
-    {
4994
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4995
-    }
4996
-
4997
-
4998
-
4999
-    /**
5000
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5001
-     * Eg, on EE_Answer that would be ANS_ID field object
5002
-     *
5003
-     * @return EE_Model_Field_Base
5004
-     * @throws EE_Error
5005
-     */
5006
-    public function get_primary_key_field()
5007
-    {
5008
-        if ($this->_primary_key_field === null) {
5009
-            foreach ($this->field_settings(true) as $field_obj) {
5010
-                if ($this->is_primary_key_field($field_obj)) {
5011
-                    $this->_primary_key_field = $field_obj;
5012
-                    break;
5013
-                }
5014
-            }
5015
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5016
-                throw new EE_Error(sprintf(
5017
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
5018
-                    get_class($this)
5019
-                ));
5020
-            }
5021
-        }
5022
-        return $this->_primary_key_field;
5023
-    }
5024
-
5025
-
5026
-
5027
-    /**
5028
-     * Returns whether or not not there is a primary key on this model.
5029
-     * Internally does some caching.
5030
-     *
5031
-     * @return boolean
5032
-     */
5033
-    public function has_primary_key_field()
5034
-    {
5035
-        if ($this->_has_primary_key_field === null) {
5036
-            try {
5037
-                $this->get_primary_key_field();
5038
-                $this->_has_primary_key_field = true;
5039
-            } catch (EE_Error $e) {
5040
-                $this->_has_primary_key_field = false;
5041
-            }
5042
-        }
5043
-        return $this->_has_primary_key_field;
5044
-    }
5045
-
5046
-
5047
-
5048
-    /**
5049
-     * Finds the first field of type $field_class_name.
5050
-     *
5051
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5052
-     *                                 EE_Foreign_Key_Field, etc
5053
-     * @return EE_Model_Field_Base or null if none is found
5054
-     */
5055
-    public function get_a_field_of_type($field_class_name)
5056
-    {
5057
-        foreach ($this->field_settings() as $field) {
5058
-            if ($field instanceof $field_class_name) {
5059
-                return $field;
5060
-            }
5061
-        }
5062
-        return null;
5063
-    }
5064
-
5065
-
5066
-
5067
-    /**
5068
-     * Gets a foreign key field pointing to model.
5069
-     *
5070
-     * @param string $model_name eg Event, Registration, not EEM_Event
5071
-     * @return EE_Foreign_Key_Field_Base
5072
-     * @throws EE_Error
5073
-     */
5074
-    public function get_foreign_key_to($model_name)
5075
-    {
5076
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5077
-            foreach ($this->field_settings() as $field) {
5078
-                if (
5079
-                    $field instanceof EE_Foreign_Key_Field_Base
5080
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5081
-                ) {
5082
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5083
-                    break;
5084
-                }
5085
-            }
5086
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5087
-                throw new EE_Error(sprintf(__(
5088
-                    "There is no foreign key field pointing to model %s on model %s",
5089
-                    'event_espresso'
5090
-                ), $model_name, get_class($this)));
5091
-            }
5092
-        }
5093
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5094
-    }
5095
-
5096
-
5097
-
5098
-    /**
5099
-     * Gets the table name (including $wpdb->prefix) for the table alias
5100
-     *
5101
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5102
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5103
-     *                            Either one works
5104
-     * @return string
5105
-     */
5106
-    public function get_table_for_alias($table_alias)
5107
-    {
5108
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5109
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5110
-    }
5111
-
5112
-
5113
-
5114
-    /**
5115
-     * Returns a flat array of all field son this model, instead of organizing them
5116
-     * by table_alias as they are in the constructor.
5117
-     *
5118
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5119
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5120
-     */
5121
-    public function field_settings($include_db_only_fields = false)
5122
-    {
5123
-        if ($include_db_only_fields) {
5124
-            if ($this->_cached_fields === null) {
5125
-                $this->_cached_fields = array();
5126
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5127
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5128
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5129
-                    }
5130
-                }
5131
-            }
5132
-            return $this->_cached_fields;
5133
-        }
5134
-        if ($this->_cached_fields_non_db_only === null) {
5135
-            $this->_cached_fields_non_db_only = array();
5136
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5137
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
-                    /** @var $field_obj EE_Model_Field_Base */
5139
-                    if (! $field_obj->is_db_only_field()) {
5140
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5141
-                    }
5142
-                }
5143
-            }
5144
-        }
5145
-        return $this->_cached_fields_non_db_only;
5146
-    }
5147
-
5148
-
5149
-
5150
-    /**
5151
-     *        cycle though array of attendees and create objects out of each item
5152
-     *
5153
-     * @access        private
5154
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5155
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5156
-     *                           numerically indexed)
5157
-     * @throws EE_Error
5158
-     */
5159
-    protected function _create_objects($rows = array())
5160
-    {
5161
-        $array_of_objects = array();
5162
-        if (empty($rows)) {
5163
-            return array();
5164
-        }
5165
-        $count_if_model_has_no_primary_key = 0;
5166
-        $has_primary_key = $this->has_primary_key_field();
5167
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5168
-        foreach ((array) $rows as $row) {
5169
-            if (empty($row)) {
5170
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5171
-                return array();
5172
-            }
5173
-            // check if we've already set this object in the results array,
5174
-            // in which case there's no need to process it further (again)
5175
-            if ($has_primary_key) {
5176
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5177
-                    $row,
5178
-                    $primary_key_field->get_qualified_column(),
5179
-                    $primary_key_field->get_table_column()
5180
-                );
5181
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5182
-                    continue;
5183
-                }
5184
-            }
5185
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5186
-            if (! $classInstance) {
5187
-                throw new EE_Error(
5188
-                    sprintf(
5189
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5190
-                        $this->get_this_model_name(),
5191
-                        http_build_query($row)
5192
-                    )
5193
-                );
5194
-            }
5195
-            // set the timezone on the instantiated objects
5196
-            $classInstance->set_timezone($this->_timezone);
5197
-            // make sure if there is any timezone setting present that we set the timezone for the object
5198
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5199
-            $array_of_objects[ $key ] = $classInstance;
5200
-            // also, for all the relations of type BelongsTo, see if we can cache
5201
-            // those related models
5202
-            // (we could do this for other relations too, but if there are conditions
5203
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5204
-            // so it requires a little more thought than just caching them immediately...)
5205
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5206
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5207
-                    // check if this model's INFO is present. If so, cache it on the model
5208
-                    $other_model = $relation_obj->get_other_model();
5209
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5210
-                    // if we managed to make a model object from the results, cache it on the main model object
5211
-                    if ($other_model_obj_maybe) {
5212
-                        // set timezone on these other model objects if they are present
5213
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5214
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5215
-                    }
5216
-                }
5217
-            }
5218
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5219
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5220
-            // the field in the CustomSelects object
5221
-            if ($this->_custom_selections instanceof CustomSelects) {
5222
-                $classInstance->setCustomSelectsValues(
5223
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5224
-                );
5225
-            }
5226
-        }
5227
-        return $array_of_objects;
5228
-    }
5229
-
5230
-
5231
-    /**
5232
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5233
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5234
-     *
5235
-     * @param array $db_results_row
5236
-     * @return array
5237
-     */
5238
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5239
-    {
5240
-        $results = array();
5241
-        if ($this->_custom_selections instanceof CustomSelects) {
5242
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5243
-                if (isset($db_results_row[ $alias ])) {
5244
-                    $results[ $alias ] = $this->convertValueToDataType(
5245
-                        $db_results_row[ $alias ],
5246
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5247
-                    );
5248
-                }
5249
-            }
5250
-        }
5251
-        return $results;
5252
-    }
5253
-
5254
-
5255
-    /**
5256
-     * This will set the value for the given alias
5257
-     * @param string $value
5258
-     * @param string $datatype (one of %d, %s, %f)
5259
-     * @return int|string|float (int for %d, string for %s, float for %f)
5260
-     */
5261
-    protected function convertValueToDataType($value, $datatype)
5262
-    {
5263
-        switch ($datatype) {
5264
-            case '%f':
5265
-                return (float) $value;
5266
-            case '%d':
5267
-                return (int) $value;
5268
-            default:
5269
-                return (string) $value;
5270
-        }
5271
-    }
5272
-
5273
-
5274
-    /**
5275
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5276
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5277
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5278
-     * object (as set in the model_field!).
5279
-     *
5280
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5281
-     */
5282
-    public function create_default_object()
5283
-    {
5284
-        $this_model_fields_and_values = array();
5285
-        // setup the row using default values;
5286
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5287
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5288
-        }
5289
-        $className = $this->_get_class_name();
5290
-        $classInstance = EE_Registry::instance()
5291
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5292
-        return $classInstance;
5293
-    }
5294
-
5295
-
5296
-
5297
-    /**
5298
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5299
-     *                             or an stdClass where each property is the name of a column,
5300
-     * @return EE_Base_Class
5301
-     * @throws EE_Error
5302
-     */
5303
-    public function instantiate_class_from_array_or_object($cols_n_values)
5304
-    {
5305
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5306
-            $cols_n_values = get_object_vars($cols_n_values);
5307
-        }
5308
-        $primary_key = null;
5309
-        // make sure the array only has keys that are fields/columns on this model
5310
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5311
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5312
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5313
-        }
5314
-        $className = $this->_get_class_name();
5315
-        // check we actually found results that we can use to build our model object
5316
-        // if not, return null
5317
-        if ($this->has_primary_key_field()) {
5318
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5319
-                return null;
5320
-            }
5321
-        } elseif ($this->unique_indexes()) {
5322
-            $first_column = reset($this_model_fields_n_values);
5323
-            if (empty($first_column)) {
5324
-                return null;
5325
-            }
5326
-        }
5327
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5328
-        if ($primary_key) {
5329
-            $classInstance = $this->get_from_entity_map($primary_key);
5330
-            if (! $classInstance) {
5331
-                $classInstance = EE_Registry::instance()
5332
-                                            ->load_class(
5333
-                                                $className,
5334
-                                                array($this_model_fields_n_values, $this->_timezone),
5335
-                                                true,
5336
-                                                false
5337
-                                            );
5338
-                // add this new object to the entity map
5339
-                $classInstance = $this->add_to_entity_map($classInstance);
5340
-            }
5341
-        } else {
5342
-            $classInstance = EE_Registry::instance()
5343
-                                        ->load_class(
5344
-                                            $className,
5345
-                                            array($this_model_fields_n_values, $this->_timezone),
5346
-                                            true,
5347
-                                            false
5348
-                                        );
5349
-        }
5350
-        return $classInstance;
5351
-    }
5352
-
5353
-
5354
-
5355
-    /**
5356
-     * Gets the model object from the  entity map if it exists
5357
-     *
5358
-     * @param int|string $id the ID of the model object
5359
-     * @return EE_Base_Class
5360
-     */
5361
-    public function get_from_entity_map($id)
5362
-    {
5363
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5364
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5365
-    }
5366
-
5367
-
5368
-
5369
-    /**
5370
-     * add_to_entity_map
5371
-     * Adds the object to the model's entity mappings
5372
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5373
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5374
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5375
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5376
-     *        then this method should be called immediately after the update query
5377
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5378
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5379
-     *
5380
-     * @param    EE_Base_Class $object
5381
-     * @throws EE_Error
5382
-     * @return \EE_Base_Class
5383
-     */
5384
-    public function add_to_entity_map(EE_Base_Class $object)
5385
-    {
5386
-        $className = $this->_get_class_name();
5387
-        if (! $object instanceof $className) {
5388
-            throw new EE_Error(sprintf(
5389
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5390
-                is_object($object) ? get_class($object) : $object,
5391
-                $className
5392
-            ));
5393
-        }
5394
-        /** @var $object EE_Base_Class */
5395
-        if (! $object->ID()) {
5396
-            throw new EE_Error(sprintf(__(
5397
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5398
-                "event_espresso"
5399
-            ), get_class($this)));
5400
-        }
5401
-        // double check it's not already there
5402
-        $classInstance = $this->get_from_entity_map($object->ID());
5403
-        if ($classInstance) {
5404
-            return $classInstance;
5405
-        }
5406
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5407
-        return $object;
5408
-    }
5409
-
5410
-
5411
-
5412
-    /**
5413
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5414
-     * if no identifier is provided, then the entire entity map is emptied
5415
-     *
5416
-     * @param int|string $id the ID of the model object
5417
-     * @return boolean
5418
-     */
5419
-    public function clear_entity_map($id = null)
5420
-    {
5421
-        if (empty($id)) {
5422
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5423
-            return true;
5424
-        }
5425
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5426
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5427
-            return true;
5428
-        }
5429
-        return false;
5430
-    }
5431
-
5432
-
5433
-
5434
-    /**
5435
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5436
-     * Given an array where keys are column (or column alias) names and values,
5437
-     * returns an array of their corresponding field names and database values
5438
-     *
5439
-     * @param array $cols_n_values
5440
-     * @return array
5441
-     */
5442
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5443
-    {
5444
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5445
-    }
5446
-
5447
-
5448
-
5449
-    /**
5450
-     * _deduce_fields_n_values_from_cols_n_values
5451
-     * Given an array where keys are column (or column alias) names and values,
5452
-     * returns an array of their corresponding field names and database values
5453
-     *
5454
-     * @param string $cols_n_values
5455
-     * @return array
5456
-     */
5457
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5458
-    {
5459
-        $this_model_fields_n_values = array();
5460
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5461
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5462
-                $cols_n_values,
5463
-                $table_obj->get_fully_qualified_pk_column(),
5464
-                $table_obj->get_pk_column()
5465
-            );
5466
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5467
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5468
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5469
-                    if (! $field_obj->is_db_only_field()) {
5470
-                        // prepare field as if its coming from db
5471
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5472
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5473
-                    }
5474
-                }
5475
-            } else {
5476
-                // the table's rows existed. Use their values
5477
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5478
-                    if (! $field_obj->is_db_only_field()) {
5479
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5480
-                            $cols_n_values,
5481
-                            $field_obj->get_qualified_column(),
5482
-                            $field_obj->get_table_column()
5483
-                        );
5484
-                    }
5485
-                }
5486
-            }
5487
-        }
5488
-        return $this_model_fields_n_values;
5489
-    }
5490
-
5491
-
5492
-    /**
5493
-     * @param $cols_n_values
5494
-     * @param $qualified_column
5495
-     * @param $regular_column
5496
-     * @return null
5497
-     * @throws EE_Error
5498
-     * @throws ReflectionException
5499
-     */
5500
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5501
-    {
5502
-        $value = null;
5503
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5504
-        // does the field on the model relate to this column retrieved from the db?
5505
-        // or is it a db-only field? (not relating to the model)
5506
-        if (isset($cols_n_values[ $qualified_column ])) {
5507
-            $value = $cols_n_values[ $qualified_column ];
5508
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5509
-            $value = $cols_n_values[ $regular_column ];
5510
-        } elseif (! empty($this->foreign_key_aliases)) {
5511
-            // no PK?  ok check if there is a foreign key alias set for this table
5512
-            // then check if that alias exists in the incoming data
5513
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5514
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5515
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5516
-                    $value = $cols_n_values[ $FK_alias ];
5517
-                    [$pk_class] = explode('.', $PK_column);
5518
-                    $pk_model_name = "EEM_{$pk_class}";
5519
-                    /** @var EEM_Base $pk_model */
5520
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5521
-                    if ($pk_model instanceof EEM_Base) {
5522
-                        // make sure object is pulled from db and added to entity map
5523
-                        $pk_model->get_one_by_ID($value);
5524
-                    }
5525
-                    break;
5526
-                }
5527
-            }
5528
-        }
5529
-        return $value;
5530
-    }
5531
-
5532
-
5533
-
5534
-    /**
5535
-     * refresh_entity_map_from_db
5536
-     * Makes sure the model object in the entity map at $id assumes the values
5537
-     * of the database (opposite of EE_base_Class::save())
5538
-     *
5539
-     * @param int|string $id
5540
-     * @return EE_Base_Class
5541
-     * @throws EE_Error
5542
-     */
5543
-    public function refresh_entity_map_from_db($id)
5544
-    {
5545
-        $obj_in_map = $this->get_from_entity_map($id);
5546
-        if ($obj_in_map) {
5547
-            $wpdb_results = $this->_get_all_wpdb_results(
5548
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5549
-            );
5550
-            if ($wpdb_results && is_array($wpdb_results)) {
5551
-                $one_row = reset($wpdb_results);
5552
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5553
-                    $obj_in_map->set_from_db($field_name, $db_value);
5554
-                }
5555
-                // clear the cache of related model objects
5556
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5557
-                    $obj_in_map->clear_cache($relation_name, null, true);
5558
-                }
5559
-            }
5560
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5561
-            return $obj_in_map;
5562
-        }
5563
-        return $this->get_one_by_ID($id);
5564
-    }
5565
-
5566
-
5567
-
5568
-    /**
5569
-     * refresh_entity_map_with
5570
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5571
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5572
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5573
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5574
-     *
5575
-     * @param int|string    $id
5576
-     * @param EE_Base_Class $replacing_model_obj
5577
-     * @return \EE_Base_Class
5578
-     * @throws EE_Error
5579
-     */
5580
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5581
-    {
5582
-        $obj_in_map = $this->get_from_entity_map($id);
5583
-        if ($obj_in_map) {
5584
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5585
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5586
-                    $obj_in_map->set($field_name, $value);
5587
-                }
5588
-                // make the model object in the entity map's cache match the $replacing_model_obj
5589
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5590
-                    $obj_in_map->clear_cache($relation_name, null, true);
5591
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5592
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5593
-                    }
5594
-                }
5595
-            }
5596
-            return $obj_in_map;
5597
-        }
5598
-        $this->add_to_entity_map($replacing_model_obj);
5599
-        return $replacing_model_obj;
5600
-    }
5601
-
5602
-
5603
-
5604
-    /**
5605
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5606
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5607
-     * require_once($this->_getClassName().".class.php");
5608
-     *
5609
-     * @return string
5610
-     */
5611
-    private function _get_class_name()
5612
-    {
5613
-        return "EE_" . $this->get_this_model_name();
5614
-    }
5615
-
5616
-
5617
-
5618
-    /**
5619
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5620
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5621
-     * it would be 'Events'.
5622
-     *
5623
-     * @param int $quantity
5624
-     * @return string
5625
-     */
5626
-    public function item_name($quantity = 1)
5627
-    {
5628
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5629
-    }
5630
-
5631
-
5632
-
5633
-    /**
5634
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5635
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5636
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5637
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5638
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5639
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5640
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5641
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5642
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5643
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5644
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5645
-     *        return $previousReturnValue.$returnString;
5646
-     * }
5647
-     * require('EEM_Answer.model.php');
5648
-     * $answer=EEM_Answer::instance();
5649
-     * echo $answer->my_callback('monkeys',100);
5650
-     * //will output "you called my_callback! and passed args:monkeys,100"
5651
-     *
5652
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5653
-     * @param array  $args       array of original arguments passed to the function
5654
-     * @throws EE_Error
5655
-     * @return mixed whatever the plugin which calls add_filter decides
5656
-     */
5657
-    public function __call($methodName, $args)
5658
-    {
5659
-        $className = get_class($this);
5660
-        $tagName = "FHEE__{$className}__{$methodName}";
5661
-        if (! has_filter($tagName)) {
5662
-            throw new EE_Error(
5663
-                sprintf(
5664
-                    __(
5665
-                        '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 );',
5666
-                        'event_espresso'
5667
-                    ),
5668
-                    $methodName,
5669
-                    $className,
5670
-                    $tagName,
5671
-                    '<br />'
5672
-                )
5673
-            );
5674
-        }
5675
-        return apply_filters($tagName, null, $this, $args);
5676
-    }
5677
-
5678
-
5679
-
5680
-    /**
5681
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5682
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5683
-     *
5684
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5685
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5686
-     *                                                       the object's class name
5687
-     *                                                       or object's ID
5688
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5689
-     *                                                       exists in the database. If it does not, we add it
5690
-     * @throws EE_Error
5691
-     * @return EE_Base_Class
5692
-     */
5693
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5694
-    {
5695
-        $className = $this->_get_class_name();
5696
-        if ($base_class_obj_or_id instanceof $className) {
5697
-            $model_object = $base_class_obj_or_id;
5698
-        } else {
5699
-            $primary_key_field = $this->get_primary_key_field();
5700
-            if (
5701
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5702
-                && (
5703
-                    is_int($base_class_obj_or_id)
5704
-                    || is_string($base_class_obj_or_id)
5705
-                )
5706
-            ) {
5707
-                // assume it's an ID.
5708
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5709
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5710
-            } elseif (
5711
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5712
-                && is_string($base_class_obj_or_id)
5713
-            ) {
5714
-                // assume its a string representation of the object
5715
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5716
-            } else {
5717
-                throw new EE_Error(
5718
-                    sprintf(
5719
-                        __(
5720
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5721
-                            'event_espresso'
5722
-                        ),
5723
-                        $base_class_obj_or_id,
5724
-                        $this->_get_class_name(),
5725
-                        print_r($base_class_obj_or_id, true)
5726
-                    )
5727
-                );
5728
-            }
5729
-        }
5730
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5731
-            $model_object->save();
5732
-        }
5733
-        return $model_object;
5734
-    }
5735
-
5736
-
5737
-
5738
-    /**
5739
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5740
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5741
-     * returns it ID.
5742
-     *
5743
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5744
-     * @return int|string depending on the type of this model object's ID
5745
-     * @throws EE_Error
5746
-     */
5747
-    public function ensure_is_ID($base_class_obj_or_id)
5748
-    {
5749
-        $className = $this->_get_class_name();
5750
-        if ($base_class_obj_or_id instanceof $className) {
5751
-            /** @var $base_class_obj_or_id EE_Base_Class */
5752
-            $id = $base_class_obj_or_id->ID();
5753
-        } elseif (is_int($base_class_obj_or_id)) {
5754
-            // assume it's an ID
5755
-            $id = $base_class_obj_or_id;
5756
-        } elseif (is_string($base_class_obj_or_id)) {
5757
-            // assume its a string representation of the object
5758
-            $id = $base_class_obj_or_id;
5759
-        } else {
5760
-            throw new EE_Error(sprintf(
5761
-                __(
5762
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5763
-                    'event_espresso'
5764
-                ),
5765
-                $base_class_obj_or_id,
5766
-                $this->_get_class_name(),
5767
-                print_r($base_class_obj_or_id, true)
5768
-            ));
5769
-        }
5770
-        return $id;
5771
-    }
5772
-
5773
-
5774
-
5775
-    /**
5776
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5777
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5778
-     * been sanitized and converted into the appropriate domain.
5779
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5780
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5781
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5782
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5783
-     * $EVT = EEM_Event::instance(); $old_setting =
5784
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5785
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5786
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5787
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5788
-     *
5789
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5790
-     * @return void
5791
-     */
5792
-    public function assume_values_already_prepared_by_model_object(
5793
-        $values_already_prepared = self::not_prepared_by_model_object
5794
-    ) {
5795
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5796
-    }
5797
-
5798
-
5799
-
5800
-    /**
5801
-     * Read comments for assume_values_already_prepared_by_model_object()
5802
-     *
5803
-     * @return int
5804
-     */
5805
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5806
-    {
5807
-        return $this->_values_already_prepared_by_model_object;
5808
-    }
5809
-
5810
-
5811
-
5812
-    /**
5813
-     * Gets all the indexes on this model
5814
-     *
5815
-     * @return EE_Index[]
5816
-     */
5817
-    public function indexes()
5818
-    {
5819
-        return $this->_indexes;
5820
-    }
5821
-
5822
-
5823
-
5824
-    /**
5825
-     * Gets all the Unique Indexes on this model
5826
-     *
5827
-     * @return EE_Unique_Index[]
5828
-     */
5829
-    public function unique_indexes()
5830
-    {
5831
-        $unique_indexes = array();
5832
-        foreach ($this->_indexes as $name => $index) {
5833
-            if ($index instanceof EE_Unique_Index) {
5834
-                $unique_indexes [ $name ] = $index;
5835
-            }
5836
-        }
5837
-        return $unique_indexes;
5838
-    }
5839
-
5840
-
5841
-
5842
-    /**
5843
-     * Gets all the fields which, when combined, make the primary key.
5844
-     * This is usually just an array with 1 element (the primary key), but in cases
5845
-     * where there is no primary key, it's a combination of fields as defined
5846
-     * on a primary index
5847
-     *
5848
-     * @return EE_Model_Field_Base[] indexed by the field's name
5849
-     * @throws EE_Error
5850
-     */
5851
-    public function get_combined_primary_key_fields()
5852
-    {
5853
-        foreach ($this->indexes() as $index) {
5854
-            if ($index instanceof EE_Primary_Key_Index) {
5855
-                return $index->fields();
5856
-            }
5857
-        }
5858
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5859
-    }
5860
-
5861
-
5862
-
5863
-    /**
5864
-     * Used to build a primary key string (when the model has no primary key),
5865
-     * which can be used a unique string to identify this model object.
5866
-     *
5867
-     * @param array $fields_n_values keys are field names, values are their values.
5868
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5869
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5870
-     *                               before passing it to this function (that will convert it from columns-n-values
5871
-     *                               to field-names-n-values).
5872
-     * @return string
5873
-     * @throws EE_Error
5874
-     */
5875
-    public function get_index_primary_key_string($fields_n_values)
5876
-    {
5877
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5878
-            $fields_n_values,
5879
-            $this->get_combined_primary_key_fields()
5880
-        );
5881
-        return http_build_query($cols_n_values_for_primary_key_index);
5882
-    }
5883
-
5884
-
5885
-
5886
-    /**
5887
-     * Gets the field values from the primary key string
5888
-     *
5889
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5890
-     * @param string $index_primary_key_string
5891
-     * @return null|array
5892
-     * @throws EE_Error
5893
-     */
5894
-    public function parse_index_primary_key_string($index_primary_key_string)
5895
-    {
5896
-        $key_fields = $this->get_combined_primary_key_fields();
5897
-        // check all of them are in the $id
5898
-        $key_vals_in_combined_pk = array();
5899
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5900
-        foreach ($key_fields as $key_field_name => $field_obj) {
5901
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5902
-                return null;
5903
-            }
5904
-        }
5905
-        return $key_vals_in_combined_pk;
5906
-    }
5907
-
5908
-
5909
-
5910
-    /**
5911
-     * verifies that an array of key-value pairs for model fields has a key
5912
-     * for each field comprising the primary key index
5913
-     *
5914
-     * @param array $key_vals
5915
-     * @return boolean
5916
-     * @throws EE_Error
5917
-     */
5918
-    public function has_all_combined_primary_key_fields($key_vals)
5919
-    {
5920
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5921
-        foreach ($keys_it_should_have as $key) {
5922
-            if (! isset($key_vals[ $key ])) {
5923
-                return false;
5924
-            }
5925
-        }
5926
-        return true;
5927
-    }
5928
-
5929
-
5930
-
5931
-    /**
5932
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5933
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5934
-     *
5935
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5936
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5937
-     * @throws EE_Error
5938
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5939
-     *                                                              indexed)
5940
-     */
5941
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5942
-    {
5943
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5944
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5945
-        } elseif (is_array($model_object_or_attributes_array)) {
5946
-            $attributes_array = $model_object_or_attributes_array;
5947
-        } else {
5948
-            throw new EE_Error(sprintf(__(
5949
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5950
-                "event_espresso"
5951
-            ), $model_object_or_attributes_array));
5952
-        }
5953
-        // even copies obviously won't have the same ID, so remove the primary key
5954
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
-            unset($attributes_array[ $this->primary_key_name() ]);
5957
-        }
5958
-        if (isset($query_params[0])) {
5959
-            $query_params[0] = array_merge($attributes_array, $query_params);
5960
-        } else {
5961
-            $query_params[0] = $attributes_array;
5962
-        }
5963
-        return $this->get_all($query_params);
5964
-    }
5965
-
5966
-
5967
-
5968
-    /**
5969
-     * Gets the first copy we find. See get_all_copies for more details
5970
-     *
5971
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5972
-     * @param array $query_params
5973
-     * @return EE_Base_Class
5974
-     * @throws EE_Error
5975
-     */
5976
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5977
-    {
5978
-        if (! is_array($query_params)) {
5979
-            EE_Error::doing_it_wrong(
5980
-                'EEM_Base::get_one_copy',
5981
-                sprintf(
5982
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5983
-                    gettype($query_params)
5984
-                ),
5985
-                '4.6.0'
5986
-            );
5987
-            $query_params = array();
5988
-        }
5989
-        $query_params['limit'] = 1;
5990
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5991
-        if (is_array($copies)) {
5992
-            return array_shift($copies);
5993
-        }
5994
-        return null;
5995
-    }
5996
-
5997
-
5998
-
5999
-    /**
6000
-     * Updates the item with the specified id. Ignores default query parameters because
6001
-     * we have specified the ID, and its assumed we KNOW what we're doing
6002
-     *
6003
-     * @param array      $fields_n_values keys are field names, values are their new values
6004
-     * @param int|string $id              the value of the primary key to update
6005
-     * @return int number of rows updated
6006
-     * @throws EE_Error
6007
-     */
6008
-    public function update_by_ID($fields_n_values, $id)
6009
-    {
6010
-        $query_params = array(
6011
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
6012
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6013
-        );
6014
-        return $this->update($fields_n_values, $query_params);
6015
-    }
6016
-
6017
-
6018
-
6019
-    /**
6020
-     * Changes an operator which was supplied to the models into one usable in SQL
6021
-     *
6022
-     * @param string $operator_supplied
6023
-     * @return string an operator which can be used in SQL
6024
-     * @throws EE_Error
6025
-     */
6026
-    private function _prepare_operator_for_sql($operator_supplied)
6027
-    {
6028
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6029
-            : null;
6030
-        if ($sql_operator) {
6031
-            return $sql_operator;
6032
-        }
6033
-        throw new EE_Error(
6034
-            sprintf(
6035
-                __(
6036
-                    "The operator '%s' is not in the list of valid operators: %s",
6037
-                    "event_espresso"
6038
-                ),
6039
-                $operator_supplied,
6040
-                implode(",", array_keys($this->_valid_operators))
6041
-            )
6042
-        );
6043
-    }
6044
-
6045
-
6046
-
6047
-    /**
6048
-     * Gets the valid operators
6049
-     * @return array keys are accepted strings, values are the SQL they are converted to
6050
-     */
6051
-    public function valid_operators()
6052
-    {
6053
-        return $this->_valid_operators;
6054
-    }
6055
-
6056
-
6057
-
6058
-    /**
6059
-     * Gets the between-style operators (take 2 arguments).
6060
-     * @return array keys are accepted strings, values are the SQL they are converted to
6061
-     */
6062
-    public function valid_between_style_operators()
6063
-    {
6064
-        return array_intersect(
6065
-            $this->valid_operators(),
6066
-            $this->_between_style_operators
6067
-        );
6068
-    }
6069
-
6070
-    /**
6071
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6072
-     * @return array keys are accepted strings, values are the SQL they are converted to
6073
-     */
6074
-    public function valid_like_style_operators()
6075
-    {
6076
-        return array_intersect(
6077
-            $this->valid_operators(),
6078
-            $this->_like_style_operators
6079
-        );
6080
-    }
6081
-
6082
-    /**
6083
-     * Gets the "in"-style operators
6084
-     * @return array keys are accepted strings, values are the SQL they are converted to
6085
-     */
6086
-    public function valid_in_style_operators()
6087
-    {
6088
-        return array_intersect(
6089
-            $this->valid_operators(),
6090
-            $this->_in_style_operators
6091
-        );
6092
-    }
6093
-
6094
-    /**
6095
-     * Gets the "null"-style operators (accept no arguments)
6096
-     * @return array keys are accepted strings, values are the SQL they are converted to
6097
-     */
6098
-    public function valid_null_style_operators()
6099
-    {
6100
-        return array_intersect(
6101
-            $this->valid_operators(),
6102
-            $this->_null_style_operators
6103
-        );
6104
-    }
6105
-
6106
-    /**
6107
-     * Gets an array where keys are the primary keys and values are their 'names'
6108
-     * (as determined by the model object's name() function, which is often overridden)
6109
-     *
6110
-     * @param array $query_params like get_all's
6111
-     * @return string[]
6112
-     * @throws EE_Error
6113
-     */
6114
-    public function get_all_names($query_params = array())
6115
-    {
6116
-        $objs = $this->get_all($query_params);
6117
-        $names = array();
6118
-        foreach ($objs as $obj) {
6119
-            $names[ $obj->ID() ] = $obj->name();
6120
-        }
6121
-        return $names;
6122
-    }
6123
-
6124
-
6125
-
6126
-    /**
6127
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6128
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6129
-     * this is duplicated effort and reduces efficiency) you would be better to use
6130
-     * array_keys() on $model_objects.
6131
-     *
6132
-     * @param \EE_Base_Class[] $model_objects
6133
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6134
-     *                                               in the returned array
6135
-     * @return array
6136
-     * @throws EE_Error
6137
-     */
6138
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6139
-    {
6140
-        if (! $this->has_primary_key_field()) {
6141
-            if (WP_DEBUG) {
6142
-                EE_Error::add_error(
6143
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6144
-                    __FILE__,
6145
-                    __FUNCTION__,
6146
-                    __LINE__
6147
-                );
6148
-            }
6149
-        }
6150
-        $IDs = array();
6151
-        foreach ($model_objects as $model_object) {
6152
-            $id = $model_object->ID();
6153
-            if (! $id) {
6154
-                if ($filter_out_empty_ids) {
6155
-                    continue;
6156
-                }
6157
-                if (WP_DEBUG) {
6158
-                    EE_Error::add_error(
6159
-                        __(
6160
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6161
-                            'event_espresso'
6162
-                        ),
6163
-                        __FILE__,
6164
-                        __FUNCTION__,
6165
-                        __LINE__
6166
-                    );
6167
-                }
6168
-            }
6169
-            $IDs[] = $id;
6170
-        }
6171
-        return $IDs;
6172
-    }
6173
-
6174
-
6175
-
6176
-    /**
6177
-     * Returns the string used in capabilities relating to this model. If there
6178
-     * are no capabilities that relate to this model returns false
6179
-     *
6180
-     * @return string|false
6181
-     */
6182
-    public function cap_slug()
6183
-    {
6184
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6185
-    }
6186
-
6187
-
6188
-
6189
-    /**
6190
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6191
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6192
-     * only returns the cap restrictions array in that context (ie, the array
6193
-     * at that key)
6194
-     *
6195
-     * @param string $context
6196
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6197
-     * @throws EE_Error
6198
-     */
6199
-    public function cap_restrictions($context = EEM_Base::caps_read)
6200
-    {
6201
-        EEM_Base::verify_is_valid_cap_context($context);
6202
-        // check if we ought to run the restriction generator first
6203
-        if (
6204
-            isset($this->_cap_restriction_generators[ $context ])
6205
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6206
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6207
-        ) {
6208
-            $this->_cap_restrictions[ $context ] = array_merge(
6209
-                $this->_cap_restrictions[ $context ],
6210
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6211
-            );
6212
-        }
6213
-        // and make sure we've finalized the construction of each restriction
6214
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6215
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6216
-                $where_conditions_obj->_finalize_construct($this);
6217
-            }
6218
-        }
6219
-        return $this->_cap_restrictions[ $context ];
6220
-    }
6221
-
6222
-
6223
-
6224
-    /**
6225
-     * Indicating whether or not this model thinks its a wp core model
6226
-     *
6227
-     * @return boolean
6228
-     */
6229
-    public function is_wp_core_model()
6230
-    {
6231
-        return $this->_wp_core_model;
6232
-    }
6233
-
6234
-
6235
-
6236
-    /**
6237
-     * Gets all the caps that are missing which impose a restriction on
6238
-     * queries made in this context
6239
-     *
6240
-     * @param string $context one of EEM_Base::caps_ constants
6241
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6242
-     * @throws EE_Error
6243
-     */
6244
-    public function caps_missing($context = EEM_Base::caps_read)
6245
-    {
6246
-        $missing_caps = array();
6247
-        $cap_restrictions = $this->cap_restrictions($context);
6248
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6249
-            if (
6250
-                ! EE_Capabilities::instance()
6251
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6252
-            ) {
6253
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6254
-            }
6255
-        }
6256
-        return $missing_caps;
6257
-    }
6258
-
6259
-
6260
-
6261
-    /**
6262
-     * Gets the mapping from capability contexts to action strings used in capability names
6263
-     *
6264
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6265
-     * one of 'read', 'edit', or 'delete'
6266
-     */
6267
-    public function cap_contexts_to_cap_action_map()
6268
-    {
6269
-        return apply_filters(
6270
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6271
-            $this->_cap_contexts_to_cap_action_map,
6272
-            $this
6273
-        );
6274
-    }
6275
-
6276
-
6277
-
6278
-    /**
6279
-     * Gets the action string for the specified capability context
6280
-     *
6281
-     * @param string $context
6282
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6283
-     * @throws EE_Error
6284
-     */
6285
-    public function cap_action_for_context($context)
6286
-    {
6287
-        $mapping = $this->cap_contexts_to_cap_action_map();
6288
-        if (isset($mapping[ $context ])) {
6289
-            return $mapping[ $context ];
6290
-        }
6291
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6292
-            return $action;
6293
-        }
6294
-        throw new EE_Error(
6295
-            sprintf(
6296
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6297
-                $context,
6298
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6299
-            )
6300
-        );
6301
-    }
6302
-
6303
-
6304
-
6305
-    /**
6306
-     * Returns all the capability contexts which are valid when querying models
6307
-     *
6308
-     * @return array
6309
-     */
6310
-    public static function valid_cap_contexts()
6311
-    {
6312
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6313
-            self::caps_read,
6314
-            self::caps_read_admin,
6315
-            self::caps_edit,
6316
-            self::caps_delete,
6317
-        ));
6318
-    }
6319
-
6320
-
6321
-
6322
-    /**
6323
-     * Returns all valid options for 'default_where_conditions'
6324
-     *
6325
-     * @return array
6326
-     */
6327
-    public static function valid_default_where_conditions()
6328
-    {
6329
-        return array(
6330
-            EEM_Base::default_where_conditions_all,
6331
-            EEM_Base::default_where_conditions_this_only,
6332
-            EEM_Base::default_where_conditions_others_only,
6333
-            EEM_Base::default_where_conditions_minimum_all,
6334
-            EEM_Base::default_where_conditions_minimum_others,
6335
-            EEM_Base::default_where_conditions_none
6336
-        );
6337
-    }
6338
-
6339
-    // public static function default_where_conditions_full
6340
-    /**
6341
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6342
-     *
6343
-     * @param string $context
6344
-     * @return bool
6345
-     * @throws EE_Error
6346
-     */
6347
-    public static function verify_is_valid_cap_context($context)
6348
-    {
6349
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6350
-        if (in_array($context, $valid_cap_contexts)) {
6351
-            return true;
6352
-        }
6353
-        throw new EE_Error(
6354
-            sprintf(
6355
-                __(
6356
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6357
-                    'event_espresso'
6358
-                ),
6359
-                $context,
6360
-                'EEM_Base',
6361
-                implode(',', $valid_cap_contexts)
6362
-            )
6363
-        );
6364
-    }
6365
-
6366
-
6367
-
6368
-    /**
6369
-     * Clears all the models field caches. This is only useful when a sub-class
6370
-     * might have added a field or something and these caches might be invalidated
6371
-     */
6372
-    protected function _invalidate_field_caches()
6373
-    {
6374
-        $this->_cache_foreign_key_to_fields = array();
6375
-        $this->_cached_fields = null;
6376
-        $this->_cached_fields_non_db_only = null;
6377
-    }
6378
-
6379
-
6380
-
6381
-    /**
6382
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6383
-     * (eg "and", "or", "not").
6384
-     *
6385
-     * @return array
6386
-     */
6387
-    public function logic_query_param_keys()
6388
-    {
6389
-        return $this->_logic_query_param_keys;
6390
-    }
6391
-
6392
-
6393
-
6394
-    /**
6395
-     * Determines whether or not the where query param array key is for a logic query param.
6396
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6397
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6398
-     *
6399
-     * @param $query_param_key
6400
-     * @return bool
6401
-     */
6402
-    public function is_logic_query_param_key($query_param_key)
6403
-    {
6404
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6405
-            if (
6406
-                $query_param_key === $logic_query_param_key
6407
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6408
-            ) {
6409
-                return true;
6410
-            }
6411
-        }
6412
-        return false;
6413
-    }
6414
-
6415
-    /**
6416
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6417
-     * @since 4.9.74.p
6418
-     * @return boolean
6419
-     */
6420
-    public function hasPassword()
6421
-    {
6422
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6423
-        if ($this->has_password_field === null) {
6424
-            $password_field = $this->getPasswordField();
6425
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6426
-        }
6427
-        return $this->has_password_field;
6428
-    }
6429
-
6430
-    /**
6431
-     * Returns the password field on this model, if there is one
6432
-     * @since 4.9.74.p
6433
-     * @return EE_Password_Field|null
6434
-     */
6435
-    public function getPasswordField()
6436
-    {
6437
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6438
-        // there's no need to search for it. If we don't know yet, then find out
6439
-        if ($this->has_password_field === null && $this->password_field === null) {
6440
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6441
-        }
6442
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6443
-        return $this->password_field;
6444
-    }
6445
-
6446
-
6447
-    /**
6448
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6449
-     * @since 4.9.74.p
6450
-     * @return EE_Model_Field_Base[]
6451
-     * @throws EE_Error
6452
-     */
6453
-    public function getPasswordProtectedFields()
6454
-    {
6455
-        $password_field = $this->getPasswordField();
6456
-        $fields = array();
6457
-        if ($password_field instanceof EE_Password_Field) {
6458
-            $field_names = $password_field->protectedFields();
6459
-            foreach ($field_names as $field_name) {
6460
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6461
-            }
6462
-        }
6463
-        return $fields;
6464
-    }
6465
-
6466
-
6467
-    /**
6468
-     * Checks if the current user can perform the requested action on this model
6469
-     * @since 4.9.74.p
6470
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6471
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6472
-     * @return bool
6473
-     * @throws EE_Error
6474
-     * @throws InvalidArgumentException
6475
-     * @throws InvalidDataTypeException
6476
-     * @throws InvalidInterfaceException
6477
-     * @throws ReflectionException
6478
-     * @throws UnexpectedEntityException
6479
-     */
6480
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6481
-    {
6482
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6483
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6484
-        }
6485
-        if (!is_array($model_obj_or_fields_n_values)) {
6486
-            throw new UnexpectedEntityException(
6487
-                $model_obj_or_fields_n_values,
6488
-                'EE_Base_Class',
6489
-                sprintf(
6490
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6491
-                    __FUNCTION__
6492
-                )
6493
-            );
6494
-        }
6495
-        return $this->exists(
6496
-            $this->alter_query_params_to_restrict_by_ID(
6497
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6498
-                array(
6499
-                    'default_where_conditions' => 'none',
6500
-                    'caps'                     => $cap_to_check,
6501
-                )
6502
-            )
6503
-        );
6504
-    }
6505
-
6506
-    /**
6507
-     * Returns the query param where conditions key to the password affecting this model.
6508
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6509
-     * @since 4.9.74.p
6510
-     * @return null|string
6511
-     * @throws EE_Error
6512
-     * @throws InvalidArgumentException
6513
-     * @throws InvalidDataTypeException
6514
-     * @throws InvalidInterfaceException
6515
-     * @throws ModelConfigurationException
6516
-     * @throws ReflectionException
6517
-     */
6518
-    public function modelChainAndPassword()
6519
-    {
6520
-        if ($this->model_chain_to_password === null) {
6521
-            throw new ModelConfigurationException(
6522
-                $this,
6523
-                esc_html_x(
6524
-                // @codingStandardsIgnoreStart
6525
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6526
-                    // @codingStandardsIgnoreEnd
6527
-                    '1: model name',
6528
-                    'event_espresso'
6529
-                )
6530
-            );
6531
-        }
6532
-        if ($this->model_chain_to_password === '') {
6533
-            $model_with_password = $this;
6534
-        } else {
6535
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6536
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6537
-            } else {
6538
-                $last_model_in_chain = $this->model_chain_to_password;
6539
-            }
6540
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6541
-        }
6542
-
6543
-        $password_field = $model_with_password->getPasswordField();
6544
-        if ($password_field instanceof EE_Password_Field) {
6545
-            $password_field_name = $password_field->get_name();
6546
-        } else {
6547
-            throw new ModelConfigurationException(
6548
-                $this,
6549
-                sprintf(
6550
-                    esc_html_x(
6551
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6552
-                        '1: model name, 2: special string',
6553
-                        'event_espresso'
6554
-                    ),
6555
-                    $model_with_password->get_this_model_name(),
6556
-                    $this->model_chain_to_password
6557
-                )
6558
-            );
6559
-        }
6560
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6561
-    }
6562
-
6563
-    /**
6564
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6565
-     * or if this model itself has a password affecting access to some of its other fields.
6566
-     * @since 4.9.74.p
6567
-     * @return boolean
6568
-     */
6569
-    public function restrictedByRelatedModelPassword()
6570
-    {
6571
-        return $this->model_chain_to_password !== null;
6572
-    }
3867
+		}
3868
+		return $null_friendly_where_conditions;
3869
+	}
3870
+
3871
+
3872
+
3873
+	/**
3874
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3875
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3876
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3877
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3878
+	 *
3879
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3880
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3881
+	 */
3882
+	private function _get_default_where_conditions($model_relation_path = '')
3883
+	{
3884
+		if ($this->_ignore_where_strategy) {
3885
+			return array();
3886
+		}
3887
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3888
+	}
3889
+
3890
+
3891
+
3892
+	/**
3893
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3897
+	 * Similar to _get_default_where_conditions
3898
+	 *
3899
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3901
+	 */
3902
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3903
+	{
3904
+		if ($this->_ignore_where_strategy) {
3905
+			return array();
3906
+		}
3907
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3908
+	}
3909
+
3910
+
3911
+
3912
+	/**
3913
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3914
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3915
+	 *
3916
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3917
+	 * @return string
3918
+	 * @throws EE_Error
3919
+	 */
3920
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3921
+	{
3922
+		$selects = $this->_get_columns_to_select_for_this_model();
3923
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included) {
3924
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3925
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3926
+			foreach ($other_model_selects as $key => $value) {
3927
+				$selects[] = $value;
3928
+			}
3929
+		}
3930
+		return implode(", ", $selects);
3931
+	}
3932
+
3933
+
3934
+
3935
+	/**
3936
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3937
+	 * So that's going to be the columns for all the fields on the model
3938
+	 *
3939
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3940
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3941
+	 */
3942
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3943
+	{
3944
+		$fields = $this->field_settings();
3945
+		$selects = array();
3946
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3947
+			$model_relation_chain,
3948
+			$this->get_this_model_name()
3949
+		);
3950
+		foreach ($fields as $field_obj) {
3951
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3952
+						 . $field_obj->get_table_alias()
3953
+						 . "."
3954
+						 . $field_obj->get_table_column()
3955
+						 . " AS '"
3956
+						 . $table_alias_with_model_relation_chain_prefix
3957
+						 . $field_obj->get_table_alias()
3958
+						 . "."
3959
+						 . $field_obj->get_table_column()
3960
+						 . "'";
3961
+		}
3962
+		// make sure we are also getting the PKs of each table
3963
+		$tables = $this->get_tables();
3964
+		if (count($tables) > 1) {
3965
+			foreach ($tables as $table_obj) {
3966
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3967
+									   . $table_obj->get_fully_qualified_pk_column();
3968
+				if (! in_array($qualified_pk_column, $selects)) {
3969
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3970
+				}
3971
+			}
3972
+		}
3973
+		return $selects;
3974
+	}
3975
+
3976
+
3977
+
3978
+	/**
3979
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3980
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3981
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3982
+	 * SQL for joining, and the data types
3983
+	 *
3984
+	 * @param null|string                 $original_query_param
3985
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3986
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3987
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3988
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3989
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3990
+	 *                                                          or 'Registration's
3991
+	 * @param string                      $original_query_param what it originally was (eg
3992
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3993
+	 *                                                          matches $query_param
3994
+	 * @throws EE_Error
3995
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3996
+	 */
3997
+	private function _extract_related_model_info_from_query_param(
3998
+		$query_param,
3999
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4000
+		$query_param_type,
4001
+		$original_query_param = null
4002
+	) {
4003
+		if ($original_query_param === null) {
4004
+			$original_query_param = $query_param;
4005
+		}
4006
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4007
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
4008
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
4009
+		$allow_fields = in_array(
4010
+			$query_param_type,
4011
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
4012
+			true
4013
+		);
4014
+		// check to see if we have a field on this model
4015
+		$this_model_fields = $this->field_settings(true);
4016
+		if (array_key_exists($query_param, $this_model_fields)) {
4017
+			if ($allow_fields) {
4018
+				return;
4019
+			}
4020
+			throw new EE_Error(
4021
+				sprintf(
4022
+					__(
4023
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4024
+						"event_espresso"
4025
+					),
4026
+					$query_param,
4027
+					get_class($this),
4028
+					$query_param_type,
4029
+					$original_query_param
4030
+				)
4031
+			);
4032
+		}
4033
+		// check if this is a special logic query param
4034
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4035
+			if ($allow_logic_query_params) {
4036
+				return;
4037
+			}
4038
+			throw new EE_Error(
4039
+				sprintf(
4040
+					__(
4041
+						'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',
4042
+						'event_espresso'
4043
+					),
4044
+					implode('", "', $this->_logic_query_param_keys),
4045
+					$query_param,
4046
+					get_class($this),
4047
+					'<br />',
4048
+					"\t"
4049
+					. ' $passed_in_query_info = <pre>'
4050
+					. print_r($passed_in_query_info, true)
4051
+					. '</pre>'
4052
+					. "\n\t"
4053
+					. ' $query_param_type = '
4054
+					. $query_param_type
4055
+					. "\n\t"
4056
+					. ' $original_query_param = '
4057
+					. $original_query_param
4058
+				)
4059
+			);
4060
+		}
4061
+		// check if it's a custom selection
4062
+		if (
4063
+			$this->_custom_selections instanceof CustomSelects
4064
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4065
+		) {
4066
+			return;
4067
+		}
4068
+		// check if has a model name at the beginning
4069
+		// and
4070
+		// check if it's a field on a related model
4071
+		if (
4072
+			$this->extractJoinModelFromQueryParams(
4073
+				$passed_in_query_info,
4074
+				$query_param,
4075
+				$original_query_param,
4076
+				$query_param_type
4077
+			)
4078
+		) {
4079
+			return;
4080
+		}
4081
+
4082
+		// ok so $query_param didn't start with a model name
4083
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4084
+		// it's wack, that's what it is
4085
+		throw new EE_Error(
4086
+			sprintf(
4087
+				esc_html__(
4088
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4089
+					"event_espresso"
4090
+				),
4091
+				$query_param,
4092
+				get_class($this),
4093
+				$query_param_type,
4094
+				$original_query_param
4095
+			)
4096
+		);
4097
+	}
4098
+
4099
+
4100
+	/**
4101
+	 * Extracts any possible join model information from the provided possible_join_string.
4102
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4103
+	 * parts that should be added to the query.
4104
+	 *
4105
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4106
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4107
+	 * @param null|string                 $original_query_param
4108
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4109
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4110
+	 * @return bool  returns true if a join was added and false if not.
4111
+	 * @throws EE_Error
4112
+	 */
4113
+	private function extractJoinModelFromQueryParams(
4114
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4115
+		$possible_join_string,
4116
+		$original_query_param,
4117
+		$query_parameter_type
4118
+	) {
4119
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4120
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4121
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4122
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4123
+				if ($possible_join_string === '') {
4124
+					// nothing left to $query_param
4125
+					// we should actually end in a field name, not a model like this!
4126
+					throw new EE_Error(
4127
+						sprintf(
4128
+							esc_html__(
4129
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4130
+								"event_espresso"
4131
+							),
4132
+							$possible_join_string,
4133
+							$query_parameter_type,
4134
+							get_class($this),
4135
+							$valid_related_model_name
4136
+						)
4137
+					);
4138
+				}
4139
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4140
+				$related_model_obj->_extract_related_model_info_from_query_param(
4141
+					$possible_join_string,
4142
+					$query_info_carrier,
4143
+					$query_parameter_type,
4144
+					$original_query_param
4145
+				);
4146
+				return true;
4147
+			}
4148
+			if ($possible_join_string === $valid_related_model_name) {
4149
+				$this->_add_join_to_model(
4150
+					$valid_related_model_name,
4151
+					$query_info_carrier,
4152
+					$original_query_param
4153
+				);
4154
+				return true;
4155
+			}
4156
+		}
4157
+		return false;
4158
+	}
4159
+
4160
+
4161
+	/**
4162
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4163
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4164
+	 * @throws EE_Error
4165
+	 */
4166
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4167
+	{
4168
+		if (
4169
+			$this->_custom_selections instanceof CustomSelects
4170
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4171
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4172
+			)
4173
+		) {
4174
+			$original_selects = $this->_custom_selections->originalSelects();
4175
+			foreach ($original_selects as $alias => $select_configuration) {
4176
+				$this->extractJoinModelFromQueryParams(
4177
+					$query_info_carrier,
4178
+					$select_configuration[0],
4179
+					$select_configuration[0],
4180
+					'custom_selects'
4181
+				);
4182
+			}
4183
+		}
4184
+	}
4185
+
4186
+
4187
+
4188
+	/**
4189
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4190
+	 * and store it on $passed_in_query_info
4191
+	 *
4192
+	 * @param string                      $model_name
4193
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4194
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4195
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4196
+	 *                                                          and are adding a join to 'Payment' with the original
4197
+	 *                                                          query param key
4198
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4199
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4200
+	 *                                                          Payment wants to add default query params so that it
4201
+	 *                                                          will know what models to prepend onto its default query
4202
+	 *                                                          params or in case it wants to rename tables (in case
4203
+	 *                                                          there are multiple joins to the same table)
4204
+	 * @return void
4205
+	 * @throws EE_Error
4206
+	 */
4207
+	private function _add_join_to_model(
4208
+		$model_name,
4209
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4210
+		$original_query_param
4211
+	) {
4212
+		$relation_obj = $this->related_settings_for($model_name);
4213
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4214
+		// check if the relation is HABTM, because then we're essentially doing two joins
4215
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4216
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4217
+			$join_model_obj = $relation_obj->get_join_model();
4218
+			// replace the model specified with the join model for this relation chain, whi
4219
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4220
+				$model_name,
4221
+				$join_model_obj->get_this_model_name(),
4222
+				$model_relation_chain
4223
+			);
4224
+			$passed_in_query_info->merge(
4225
+				new EE_Model_Query_Info_Carrier(
4226
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4227
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4228
+				)
4229
+			);
4230
+		}
4231
+		// now just join to the other table pointed to by the relation object, and add its data types
4232
+		$passed_in_query_info->merge(
4233
+			new EE_Model_Query_Info_Carrier(
4234
+				array($model_relation_chain => $model_name),
4235
+				$relation_obj->get_join_statement($model_relation_chain)
4236
+			)
4237
+		);
4238
+	}
4239
+
4240
+
4241
+
4242
+	/**
4243
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4244
+	 *
4245
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4246
+	 * @return string of SQL
4247
+	 * @throws EE_Error
4248
+	 */
4249
+	private function _construct_where_clause($where_params)
4250
+	{
4251
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4252
+		if ($SQL) {
4253
+			return " WHERE " . $SQL;
4254
+		}
4255
+		return '';
4256
+	}
4257
+
4258
+
4259
+
4260
+	/**
4261
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4262
+	 * and should be passed HAVING parameters, not WHERE parameters
4263
+	 *
4264
+	 * @param array $having_params
4265
+	 * @return string
4266
+	 * @throws EE_Error
4267
+	 */
4268
+	private function _construct_having_clause($having_params)
4269
+	{
4270
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4271
+		if ($SQL) {
4272
+			return " HAVING " . $SQL;
4273
+		}
4274
+		return '';
4275
+	}
4276
+
4277
+
4278
+	/**
4279
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4280
+	 * Event_Meta.meta_value = 'foo'))"
4281
+	 *
4282
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4283
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4284
+	 * @throws EE_Error
4285
+	 * @return string of SQL
4286
+	 */
4287
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4288
+	{
4289
+		$where_clauses = array();
4290
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4291
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4292
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4293
+				switch ($query_param) {
4294
+					case 'not':
4295
+					case 'NOT':
4296
+						$where_clauses[] = "! ("
4297
+										   . $this->_construct_condition_clause_recursive(
4298
+											   $op_and_value_or_sub_condition,
4299
+											   $glue
4300
+										   )
4301
+										   . ")";
4302
+						break;
4303
+					case 'and':
4304
+					case 'AND':
4305
+						$where_clauses[] = " ("
4306
+										   . $this->_construct_condition_clause_recursive(
4307
+											   $op_and_value_or_sub_condition,
4308
+											   ' AND '
4309
+										   )
4310
+										   . ")";
4311
+						break;
4312
+					case 'or':
4313
+					case 'OR':
4314
+						$where_clauses[] = " ("
4315
+										   . $this->_construct_condition_clause_recursive(
4316
+											   $op_and_value_or_sub_condition,
4317
+											   ' OR '
4318
+										   )
4319
+										   . ")";
4320
+						break;
4321
+				}
4322
+			} else {
4323
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4324
+				// if it's not a normal field, maybe it's a custom selection?
4325
+				if (! $field_obj) {
4326
+					if ($this->_custom_selections instanceof CustomSelects) {
4327
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4328
+					} else {
4329
+						throw new EE_Error(sprintf(__(
4330
+							"%s is neither a valid model field name, nor a custom selection",
4331
+							"event_espresso"
4332
+						), $query_param));
4333
+					}
4334
+				}
4335
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4336
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4337
+			}
4338
+		}
4339
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4340
+	}
4341
+
4342
+
4343
+
4344
+	/**
4345
+	 * Takes the input parameter and extract the table name (alias) and column name
4346
+	 *
4347
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4348
+	 * @throws EE_Error
4349
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4350
+	 */
4351
+	private function _deduce_column_name_from_query_param($query_param)
4352
+	{
4353
+		$field = $this->_deduce_field_from_query_param($query_param);
4354
+		if ($field) {
4355
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4356
+				$field->get_model_name(),
4357
+				$query_param
4358
+			);
4359
+			return $table_alias_prefix . $field->get_qualified_column();
4360
+		}
4361
+		if (
4362
+			$this->_custom_selections instanceof CustomSelects
4363
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4364
+		) {
4365
+			// maybe it's custom selection item?
4366
+			// if so, just use it as the "column name"
4367
+			return $query_param;
4368
+		}
4369
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4370
+			? implode(',', $this->_custom_selections->columnAliases())
4371
+			: '';
4372
+		throw new EE_Error(
4373
+			sprintf(
4374
+				__(
4375
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4376
+					"event_espresso"
4377
+				),
4378
+				$query_param,
4379
+				$custom_select_aliases
4380
+			)
4381
+		);
4382
+	}
4383
+
4384
+
4385
+
4386
+	/**
4387
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4388
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4389
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4390
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4391
+	 *
4392
+	 * @param string $condition_query_param_key
4393
+	 * @return string
4394
+	 */
4395
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4396
+	{
4397
+		$pos_of_star = strpos($condition_query_param_key, '*');
4398
+		if ($pos_of_star === false) {
4399
+			return $condition_query_param_key;
4400
+		}
4401
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4402
+		return $condition_query_param_sans_star;
4403
+	}
4404
+
4405
+
4406
+
4407
+	/**
4408
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4409
+	 *
4410
+	 * @param                            mixed      array | string    $op_and_value
4411
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4412
+	 * @throws EE_Error
4413
+	 * @return string
4414
+	 */
4415
+	private function _construct_op_and_value($op_and_value, $field_obj)
4416
+	{
4417
+		if (is_array($op_and_value)) {
4418
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4419
+			if (! $operator) {
4420
+				$php_array_like_string = array();
4421
+				foreach ($op_and_value as $key => $value) {
4422
+					$php_array_like_string[] = "$key=>$value";
4423
+				}
4424
+				throw new EE_Error(
4425
+					sprintf(
4426
+						__(
4427
+							"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))",
4428
+							"event_espresso"
4429
+						),
4430
+						implode(",", $php_array_like_string)
4431
+					)
4432
+				);
4433
+			}
4434
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4435
+		} else {
4436
+			$operator = '=';
4437
+			$value = $op_and_value;
4438
+		}
4439
+		// check to see if the value is actually another field
4440
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4441
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4442
+		}
4443
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4444
+			// in this case, the value should be an array, or at least a comma-separated list
4445
+			// it will need to handle a little differently
4446
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4447
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4448
+			return $operator . SP . $cleaned_value;
4449
+		}
4450
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4451
+			// the value should be an array with count of two.
4452
+			if (count($value) !== 2) {
4453
+				throw new EE_Error(
4454
+					sprintf(
4455
+						__(
4456
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4457
+							'event_espresso'
4458
+						),
4459
+						"BETWEEN"
4460
+					)
4461
+				);
4462
+			}
4463
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4464
+			return $operator . SP . $cleaned_value;
4465
+		}
4466
+		if (in_array($operator, $this->valid_null_style_operators())) {
4467
+			if ($value !== null) {
4468
+				throw new EE_Error(
4469
+					sprintf(
4470
+						__(
4471
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4472
+							"event_espresso"
4473
+						),
4474
+						$value,
4475
+						$operator
4476
+					)
4477
+				);
4478
+			}
4479
+			return $operator;
4480
+		}
4481
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4482
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4483
+			// remove other junk. So just treat it as a string.
4484
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4485
+		}
4486
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4488
+		}
4489
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4490
+			throw new EE_Error(
4491
+				sprintf(
4492
+					__(
4493
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4494
+						'event_espresso'
4495
+					),
4496
+					$operator,
4497
+					$operator
4498
+				)
4499
+			);
4500
+		}
4501
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4502
+			throw new EE_Error(
4503
+				sprintf(
4504
+					__(
4505
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4506
+						'event_espresso'
4507
+					),
4508
+					$operator,
4509
+					$operator
4510
+				)
4511
+			);
4512
+		}
4513
+		throw new EE_Error(
4514
+			sprintf(
4515
+				__(
4516
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4517
+					"event_espresso"
4518
+				),
4519
+				http_build_query($op_and_value)
4520
+			)
4521
+		);
4522
+	}
4523
+
4524
+
4525
+
4526
+	/**
4527
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4528
+	 *
4529
+	 * @param array                      $values
4530
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4531
+	 *                                              '%s'
4532
+	 * @return string
4533
+	 * @throws EE_Error
4534
+	 */
4535
+	public function _construct_between_value($values, $field_obj)
4536
+	{
4537
+		$cleaned_values = array();
4538
+		foreach ($values as $value) {
4539
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4540
+		}
4541
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4542
+	}
4543
+
4544
+
4545
+
4546
+	/**
4547
+	 * Takes an array or a comma-separated list of $values and cleans them
4548
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4549
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4550
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4551
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4552
+	 *
4553
+	 * @param mixed                      $values    array or comma-separated string
4554
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4555
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4556
+	 * @throws EE_Error
4557
+	 */
4558
+	public function _construct_in_value($values, $field_obj)
4559
+	{
4560
+		// check if the value is a CSV list
4561
+		if (is_string($values)) {
4562
+			// in which case, turn it into an array
4563
+			$values = explode(",", $values);
4564
+		}
4565
+		$cleaned_values = array();
4566
+		foreach ($values as $value) {
4567
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4568
+		}
4569
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4570
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4571
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4572
+		if (empty($cleaned_values)) {
4573
+			$all_fields = $this->field_settings();
4574
+			$a_field = array_shift($all_fields);
4575
+			$main_table = $this->_get_main_table();
4576
+			$cleaned_values[] = "SELECT "
4577
+								. $a_field->get_table_column()
4578
+								. " FROM "
4579
+								. $main_table->get_table_name()
4580
+								. " WHERE FALSE";
4581
+		}
4582
+		return "(" . implode(",", $cleaned_values) . ")";
4583
+	}
4584
+
4585
+
4586
+
4587
+	/**
4588
+	 * @param mixed                      $value
4589
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4590
+	 * @throws EE_Error
4591
+	 * @return false|null|string
4592
+	 */
4593
+	private function _wpdb_prepare_using_field($value, $field_obj)
4594
+	{
4595
+		/** @type WPDB $wpdb */
4596
+		global $wpdb;
4597
+		if ($field_obj instanceof EE_Model_Field_Base) {
4598
+			return $wpdb->prepare(
4599
+				$field_obj->get_wpdb_data_type(),
4600
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4601
+			);
4602
+		} //$field_obj should really just be a data type
4603
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4604
+			throw new EE_Error(
4605
+				sprintf(
4606
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4607
+					$field_obj,
4608
+					implode(",", $this->_valid_wpdb_data_types)
4609
+				)
4610
+			);
4611
+		}
4612
+		return $wpdb->prepare($field_obj, $value);
4613
+	}
4614
+
4615
+
4616
+
4617
+	/**
4618
+	 * Takes the input parameter and finds the model field that it indicates.
4619
+	 *
4620
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4621
+	 * @throws EE_Error
4622
+	 * @return EE_Model_Field_Base
4623
+	 */
4624
+	protected function _deduce_field_from_query_param($query_param_name)
4625
+	{
4626
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4627
+		// which will help us find the database table and column
4628
+		$query_param_parts = explode(".", $query_param_name);
4629
+		if (empty($query_param_parts)) {
4630
+			throw new EE_Error(sprintf(__(
4631
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4632
+				'event_espresso'
4633
+			), $query_param_name));
4634
+		}
4635
+		$number_of_parts = count($query_param_parts);
4636
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4637
+		if ($number_of_parts === 1) {
4638
+			$field_name = $last_query_param_part;
4639
+			$model_obj = $this;
4640
+		} else {// $number_of_parts >= 2
4641
+			// the last part is the column name, and there are only 2parts. therefore...
4642
+			$field_name = $last_query_param_part;
4643
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4644
+		}
4645
+		try {
4646
+			return $model_obj->field_settings_for($field_name);
4647
+		} catch (EE_Error $e) {
4648
+			return null;
4649
+		}
4650
+	}
4651
+
4652
+
4653
+
4654
+	/**
4655
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4656
+	 * alias and column which corresponds to it
4657
+	 *
4658
+	 * @param string $field_name
4659
+	 * @throws EE_Error
4660
+	 * @return string
4661
+	 */
4662
+	public function _get_qualified_column_for_field($field_name)
4663
+	{
4664
+		$all_fields = $this->field_settings();
4665
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4666
+		if ($field) {
4667
+			return $field->get_qualified_column();
4668
+		}
4669
+		throw new EE_Error(
4670
+			sprintf(
4671
+				__(
4672
+					"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.",
4673
+					'event_espresso'
4674
+				),
4675
+				$field_name,
4676
+				get_class($this)
4677
+			)
4678
+		);
4679
+	}
4680
+
4681
+
4682
+
4683
+	/**
4684
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4685
+	 * Example usage:
4686
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4687
+	 *      array(),
4688
+	 *      ARRAY_A,
4689
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4690
+	 *  );
4691
+	 * is equivalent to
4692
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4693
+	 * and
4694
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4695
+	 *      array(
4696
+	 *          array(
4697
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4698
+	 *          ),
4699
+	 *          ARRAY_A,
4700
+	 *          implode(
4701
+	 *              ', ',
4702
+	 *              array_merge(
4703
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4704
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4705
+	 *              )
4706
+	 *          )
4707
+	 *      )
4708
+	 *  );
4709
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4710
+	 *
4711
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4712
+	 *                                            and the one whose fields you are selecting for example: when querying
4713
+	 *                                            tickets model and selecting fields from the tickets model you would
4714
+	 *                                            leave this parameter empty, because no models are needed to join
4715
+	 *                                            between the queried model and the selected one. Likewise when
4716
+	 *                                            querying the datetime model and selecting fields from the tickets
4717
+	 *                                            model, it would also be left empty, because there is a direct
4718
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4719
+	 *                                            them together. However, when querying from the event model and
4720
+	 *                                            selecting fields from the ticket model, you should provide the string
4721
+	 *                                            'Datetime', indicating that the event model must first join to the
4722
+	 *                                            datetime model in order to find its relation to ticket model.
4723
+	 *                                            Also, when querying from the venue model and selecting fields from
4724
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4725
+	 *                                            indicating you need to join the venue model to the event model,
4726
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4727
+	 *                                            This string is used to deduce the prefix that gets added onto the
4728
+	 *                                            models' tables qualified columns
4729
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4730
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4731
+	 *                                            qualified column names
4732
+	 * @return array|string
4733
+	 */
4734
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4735
+	{
4736
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4737
+		$qualified_columns = array();
4738
+		foreach ($this->field_settings() as $field_name => $field) {
4739
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4740
+		}
4741
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4742
+	}
4743
+
4744
+
4745
+
4746
+	/**
4747
+	 * constructs the select use on special limit joins
4748
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4749
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4750
+	 * (as that is typically where the limits would be set).
4751
+	 *
4752
+	 * @param  string       $table_alias The table the select is being built for
4753
+	 * @param  mixed|string $limit       The limit for this select
4754
+	 * @return string                The final select join element for the query.
4755
+	 */
4756
+	public function _construct_limit_join_select($table_alias, $limit)
4757
+	{
4758
+		$SQL = '';
4759
+		foreach ($this->_tables as $table_obj) {
4760
+			if ($table_obj instanceof EE_Primary_Table) {
4761
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4762
+					? $table_obj->get_select_join_limit($limit)
4763
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4764
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4765
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4766
+					? $table_obj->get_select_join_limit_join($limit)
4767
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4768
+			}
4769
+		}
4770
+		return $SQL;
4771
+	}
4772
+
4773
+
4774
+
4775
+	/**
4776
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4777
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4778
+	 *
4779
+	 * @return string SQL
4780
+	 * @throws EE_Error
4781
+	 */
4782
+	public function _construct_internal_join()
4783
+	{
4784
+		$SQL = $this->_get_main_table()->get_table_sql();
4785
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4786
+		return $SQL;
4787
+	}
4788
+
4789
+
4790
+
4791
+	/**
4792
+	 * Constructs the SQL for joining all the tables on this model.
4793
+	 * Normally $alias should be the primary table's alias, but in cases where
4794
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4795
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4796
+	 * alias, this will construct SQL like:
4797
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4798
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4799
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4800
+	 *
4801
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4802
+	 * @return string
4803
+	 */
4804
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4805
+	{
4806
+		$SQL = '';
4807
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4808
+		foreach ($this->_tables as $table_obj) {
4809
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4810
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4811
+					// so we're joining to this table, meaning the table is already in
4812
+					// the FROM statement, BUT the primary table isn't. So we want
4813
+					// to add the inverse join sql
4814
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4815
+				} else {
4816
+					// just add a regular JOIN to this table from the primary table
4817
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4818
+				}
4819
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4820
+		}
4821
+		return $SQL;
4822
+	}
4823
+
4824
+
4825
+
4826
+	/**
4827
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4828
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4829
+	 * their data type (eg, '%s', '%d', etc)
4830
+	 *
4831
+	 * @return array
4832
+	 */
4833
+	public function _get_data_types()
4834
+	{
4835
+		$data_types = array();
4836
+		foreach ($this->field_settings() as $field_obj) {
4837
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4838
+			/** @var $field_obj EE_Model_Field_Base */
4839
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4840
+		}
4841
+		return $data_types;
4842
+	}
4843
+
4844
+
4845
+
4846
+	/**
4847
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4848
+	 *
4849
+	 * @param string $model_name
4850
+	 * @throws EE_Error
4851
+	 * @return EEM_Base
4852
+	 */
4853
+	public function get_related_model_obj($model_name)
4854
+	{
4855
+		$model_classname = "EEM_" . $model_name;
4856
+		if (! class_exists($model_classname)) {
4857
+			throw new EE_Error(sprintf(__(
4858
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4859
+				'event_espresso'
4860
+			), $model_name, $model_classname));
4861
+		}
4862
+		return call_user_func($model_classname . "::instance");
4863
+	}
4864
+
4865
+
4866
+
4867
+	/**
4868
+	 * Returns the array of EE_ModelRelations for this model.
4869
+	 *
4870
+	 * @return EE_Model_Relation_Base[]
4871
+	 */
4872
+	public function relation_settings()
4873
+	{
4874
+		return $this->_model_relations;
4875
+	}
4876
+
4877
+
4878
+
4879
+	/**
4880
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4881
+	 * because without THOSE models, this model probably doesn't have much purpose.
4882
+	 * (Eg, without an event, datetimes have little purpose.)
4883
+	 *
4884
+	 * @return EE_Belongs_To_Relation[]
4885
+	 */
4886
+	public function belongs_to_relations()
4887
+	{
4888
+		$belongs_to_relations = array();
4889
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4890
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4891
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4892
+			}
4893
+		}
4894
+		return $belongs_to_relations;
4895
+	}
4896
+
4897
+
4898
+
4899
+	/**
4900
+	 * Returns the specified EE_Model_Relation, or throws an exception
4901
+	 *
4902
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4903
+	 * @throws EE_Error
4904
+	 * @return EE_Model_Relation_Base
4905
+	 */
4906
+	public function related_settings_for($relation_name)
4907
+	{
4908
+		$relatedModels = $this->relation_settings();
4909
+		if (! array_key_exists($relation_name, $relatedModels)) {
4910
+			throw new EE_Error(
4911
+				sprintf(
4912
+					__(
4913
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4914
+						'event_espresso'
4915
+					),
4916
+					$relation_name,
4917
+					$this->_get_class_name(),
4918
+					implode(', ', array_keys($relatedModels))
4919
+				)
4920
+			);
4921
+		}
4922
+		return $relatedModels[ $relation_name ];
4923
+	}
4924
+
4925
+
4926
+
4927
+	/**
4928
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4929
+	 * fields
4930
+	 *
4931
+	 * @param string $fieldName
4932
+	 * @param boolean $include_db_only_fields
4933
+	 * @throws EE_Error
4934
+	 * @return EE_Model_Field_Base
4935
+	 */
4936
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4937
+	{
4938
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4939
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4940
+			throw new EE_Error(sprintf(
4941
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4942
+				$fieldName,
4943
+				get_class($this)
4944
+			));
4945
+		}
4946
+		return $fieldSettings[ $fieldName ];
4947
+	}
4948
+
4949
+
4950
+
4951
+	/**
4952
+	 * Checks if this field exists on this model
4953
+	 *
4954
+	 * @param string $fieldName a key in the model's _field_settings array
4955
+	 * @return boolean
4956
+	 */
4957
+	public function has_field($fieldName)
4958
+	{
4959
+		$fieldSettings = $this->field_settings(true);
4960
+		if (isset($fieldSettings[ $fieldName ])) {
4961
+			return true;
4962
+		}
4963
+		return false;
4964
+	}
4965
+
4966
+
4967
+
4968
+	/**
4969
+	 * Returns whether or not this model has a relation to the specified model
4970
+	 *
4971
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4972
+	 * @return boolean
4973
+	 */
4974
+	public function has_relation($relation_name)
4975
+	{
4976
+		$relations = $this->relation_settings();
4977
+		if (isset($relations[ $relation_name ])) {
4978
+			return true;
4979
+		}
4980
+		return false;
4981
+	}
4982
+
4983
+
4984
+
4985
+	/**
4986
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4987
+	 * Eg, on EE_Answer that would be ANS_ID field object
4988
+	 *
4989
+	 * @param $field_obj
4990
+	 * @return boolean
4991
+	 */
4992
+	public function is_primary_key_field($field_obj)
4993
+	{
4994
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4995
+	}
4996
+
4997
+
4998
+
4999
+	/**
5000
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5001
+	 * Eg, on EE_Answer that would be ANS_ID field object
5002
+	 *
5003
+	 * @return EE_Model_Field_Base
5004
+	 * @throws EE_Error
5005
+	 */
5006
+	public function get_primary_key_field()
5007
+	{
5008
+		if ($this->_primary_key_field === null) {
5009
+			foreach ($this->field_settings(true) as $field_obj) {
5010
+				if ($this->is_primary_key_field($field_obj)) {
5011
+					$this->_primary_key_field = $field_obj;
5012
+					break;
5013
+				}
5014
+			}
5015
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5016
+				throw new EE_Error(sprintf(
5017
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
5018
+					get_class($this)
5019
+				));
5020
+			}
5021
+		}
5022
+		return $this->_primary_key_field;
5023
+	}
5024
+
5025
+
5026
+
5027
+	/**
5028
+	 * Returns whether or not not there is a primary key on this model.
5029
+	 * Internally does some caching.
5030
+	 *
5031
+	 * @return boolean
5032
+	 */
5033
+	public function has_primary_key_field()
5034
+	{
5035
+		if ($this->_has_primary_key_field === null) {
5036
+			try {
5037
+				$this->get_primary_key_field();
5038
+				$this->_has_primary_key_field = true;
5039
+			} catch (EE_Error $e) {
5040
+				$this->_has_primary_key_field = false;
5041
+			}
5042
+		}
5043
+		return $this->_has_primary_key_field;
5044
+	}
5045
+
5046
+
5047
+
5048
+	/**
5049
+	 * Finds the first field of type $field_class_name.
5050
+	 *
5051
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5052
+	 *                                 EE_Foreign_Key_Field, etc
5053
+	 * @return EE_Model_Field_Base or null if none is found
5054
+	 */
5055
+	public function get_a_field_of_type($field_class_name)
5056
+	{
5057
+		foreach ($this->field_settings() as $field) {
5058
+			if ($field instanceof $field_class_name) {
5059
+				return $field;
5060
+			}
5061
+		}
5062
+		return null;
5063
+	}
5064
+
5065
+
5066
+
5067
+	/**
5068
+	 * Gets a foreign key field pointing to model.
5069
+	 *
5070
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5071
+	 * @return EE_Foreign_Key_Field_Base
5072
+	 * @throws EE_Error
5073
+	 */
5074
+	public function get_foreign_key_to($model_name)
5075
+	{
5076
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5077
+			foreach ($this->field_settings() as $field) {
5078
+				if (
5079
+					$field instanceof EE_Foreign_Key_Field_Base
5080
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5081
+				) {
5082
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5083
+					break;
5084
+				}
5085
+			}
5086
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5087
+				throw new EE_Error(sprintf(__(
5088
+					"There is no foreign key field pointing to model %s on model %s",
5089
+					'event_espresso'
5090
+				), $model_name, get_class($this)));
5091
+			}
5092
+		}
5093
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5094
+	}
5095
+
5096
+
5097
+
5098
+	/**
5099
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5100
+	 *
5101
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5102
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5103
+	 *                            Either one works
5104
+	 * @return string
5105
+	 */
5106
+	public function get_table_for_alias($table_alias)
5107
+	{
5108
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5109
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5110
+	}
5111
+
5112
+
5113
+
5114
+	/**
5115
+	 * Returns a flat array of all field son this model, instead of organizing them
5116
+	 * by table_alias as they are in the constructor.
5117
+	 *
5118
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5119
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5120
+	 */
5121
+	public function field_settings($include_db_only_fields = false)
5122
+	{
5123
+		if ($include_db_only_fields) {
5124
+			if ($this->_cached_fields === null) {
5125
+				$this->_cached_fields = array();
5126
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5127
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5128
+						$this->_cached_fields[ $field_name ] = $field_obj;
5129
+					}
5130
+				}
5131
+			}
5132
+			return $this->_cached_fields;
5133
+		}
5134
+		if ($this->_cached_fields_non_db_only === null) {
5135
+			$this->_cached_fields_non_db_only = array();
5136
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5137
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138
+					/** @var $field_obj EE_Model_Field_Base */
5139
+					if (! $field_obj->is_db_only_field()) {
5140
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5141
+					}
5142
+				}
5143
+			}
5144
+		}
5145
+		return $this->_cached_fields_non_db_only;
5146
+	}
5147
+
5148
+
5149
+
5150
+	/**
5151
+	 *        cycle though array of attendees and create objects out of each item
5152
+	 *
5153
+	 * @access        private
5154
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5155
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5156
+	 *                           numerically indexed)
5157
+	 * @throws EE_Error
5158
+	 */
5159
+	protected function _create_objects($rows = array())
5160
+	{
5161
+		$array_of_objects = array();
5162
+		if (empty($rows)) {
5163
+			return array();
5164
+		}
5165
+		$count_if_model_has_no_primary_key = 0;
5166
+		$has_primary_key = $this->has_primary_key_field();
5167
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5168
+		foreach ((array) $rows as $row) {
5169
+			if (empty($row)) {
5170
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5171
+				return array();
5172
+			}
5173
+			// check if we've already set this object in the results array,
5174
+			// in which case there's no need to process it further (again)
5175
+			if ($has_primary_key) {
5176
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5177
+					$row,
5178
+					$primary_key_field->get_qualified_column(),
5179
+					$primary_key_field->get_table_column()
5180
+				);
5181
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5182
+					continue;
5183
+				}
5184
+			}
5185
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5186
+			if (! $classInstance) {
5187
+				throw new EE_Error(
5188
+					sprintf(
5189
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5190
+						$this->get_this_model_name(),
5191
+						http_build_query($row)
5192
+					)
5193
+				);
5194
+			}
5195
+			// set the timezone on the instantiated objects
5196
+			$classInstance->set_timezone($this->_timezone);
5197
+			// make sure if there is any timezone setting present that we set the timezone for the object
5198
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5199
+			$array_of_objects[ $key ] = $classInstance;
5200
+			// also, for all the relations of type BelongsTo, see if we can cache
5201
+			// those related models
5202
+			// (we could do this for other relations too, but if there are conditions
5203
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5204
+			// so it requires a little more thought than just caching them immediately...)
5205
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5206
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5207
+					// check if this model's INFO is present. If so, cache it on the model
5208
+					$other_model = $relation_obj->get_other_model();
5209
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5210
+					// if we managed to make a model object from the results, cache it on the main model object
5211
+					if ($other_model_obj_maybe) {
5212
+						// set timezone on these other model objects if they are present
5213
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5214
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5215
+					}
5216
+				}
5217
+			}
5218
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5219
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5220
+			// the field in the CustomSelects object
5221
+			if ($this->_custom_selections instanceof CustomSelects) {
5222
+				$classInstance->setCustomSelectsValues(
5223
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5224
+				);
5225
+			}
5226
+		}
5227
+		return $array_of_objects;
5228
+	}
5229
+
5230
+
5231
+	/**
5232
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5233
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5234
+	 *
5235
+	 * @param array $db_results_row
5236
+	 * @return array
5237
+	 */
5238
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5239
+	{
5240
+		$results = array();
5241
+		if ($this->_custom_selections instanceof CustomSelects) {
5242
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5243
+				if (isset($db_results_row[ $alias ])) {
5244
+					$results[ $alias ] = $this->convertValueToDataType(
5245
+						$db_results_row[ $alias ],
5246
+						$this->_custom_selections->getDataTypeForAlias($alias)
5247
+					);
5248
+				}
5249
+			}
5250
+		}
5251
+		return $results;
5252
+	}
5253
+
5254
+
5255
+	/**
5256
+	 * This will set the value for the given alias
5257
+	 * @param string $value
5258
+	 * @param string $datatype (one of %d, %s, %f)
5259
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5260
+	 */
5261
+	protected function convertValueToDataType($value, $datatype)
5262
+	{
5263
+		switch ($datatype) {
5264
+			case '%f':
5265
+				return (float) $value;
5266
+			case '%d':
5267
+				return (int) $value;
5268
+			default:
5269
+				return (string) $value;
5270
+		}
5271
+	}
5272
+
5273
+
5274
+	/**
5275
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5276
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5277
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5278
+	 * object (as set in the model_field!).
5279
+	 *
5280
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5281
+	 */
5282
+	public function create_default_object()
5283
+	{
5284
+		$this_model_fields_and_values = array();
5285
+		// setup the row using default values;
5286
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5287
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5288
+		}
5289
+		$className = $this->_get_class_name();
5290
+		$classInstance = EE_Registry::instance()
5291
+									->load_class($className, array($this_model_fields_and_values), false, false);
5292
+		return $classInstance;
5293
+	}
5294
+
5295
+
5296
+
5297
+	/**
5298
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5299
+	 *                             or an stdClass where each property is the name of a column,
5300
+	 * @return EE_Base_Class
5301
+	 * @throws EE_Error
5302
+	 */
5303
+	public function instantiate_class_from_array_or_object($cols_n_values)
5304
+	{
5305
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5306
+			$cols_n_values = get_object_vars($cols_n_values);
5307
+		}
5308
+		$primary_key = null;
5309
+		// make sure the array only has keys that are fields/columns on this model
5310
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5311
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5312
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5313
+		}
5314
+		$className = $this->_get_class_name();
5315
+		// check we actually found results that we can use to build our model object
5316
+		// if not, return null
5317
+		if ($this->has_primary_key_field()) {
5318
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5319
+				return null;
5320
+			}
5321
+		} elseif ($this->unique_indexes()) {
5322
+			$first_column = reset($this_model_fields_n_values);
5323
+			if (empty($first_column)) {
5324
+				return null;
5325
+			}
5326
+		}
5327
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5328
+		if ($primary_key) {
5329
+			$classInstance = $this->get_from_entity_map($primary_key);
5330
+			if (! $classInstance) {
5331
+				$classInstance = EE_Registry::instance()
5332
+											->load_class(
5333
+												$className,
5334
+												array($this_model_fields_n_values, $this->_timezone),
5335
+												true,
5336
+												false
5337
+											);
5338
+				// add this new object to the entity map
5339
+				$classInstance = $this->add_to_entity_map($classInstance);
5340
+			}
5341
+		} else {
5342
+			$classInstance = EE_Registry::instance()
5343
+										->load_class(
5344
+											$className,
5345
+											array($this_model_fields_n_values, $this->_timezone),
5346
+											true,
5347
+											false
5348
+										);
5349
+		}
5350
+		return $classInstance;
5351
+	}
5352
+
5353
+
5354
+
5355
+	/**
5356
+	 * Gets the model object from the  entity map if it exists
5357
+	 *
5358
+	 * @param int|string $id the ID of the model object
5359
+	 * @return EE_Base_Class
5360
+	 */
5361
+	public function get_from_entity_map($id)
5362
+	{
5363
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5364
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5365
+	}
5366
+
5367
+
5368
+
5369
+	/**
5370
+	 * add_to_entity_map
5371
+	 * Adds the object to the model's entity mappings
5372
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5373
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5374
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5375
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5376
+	 *        then this method should be called immediately after the update query
5377
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5378
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5379
+	 *
5380
+	 * @param    EE_Base_Class $object
5381
+	 * @throws EE_Error
5382
+	 * @return \EE_Base_Class
5383
+	 */
5384
+	public function add_to_entity_map(EE_Base_Class $object)
5385
+	{
5386
+		$className = $this->_get_class_name();
5387
+		if (! $object instanceof $className) {
5388
+			throw new EE_Error(sprintf(
5389
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5390
+				is_object($object) ? get_class($object) : $object,
5391
+				$className
5392
+			));
5393
+		}
5394
+		/** @var $object EE_Base_Class */
5395
+		if (! $object->ID()) {
5396
+			throw new EE_Error(sprintf(__(
5397
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5398
+				"event_espresso"
5399
+			), get_class($this)));
5400
+		}
5401
+		// double check it's not already there
5402
+		$classInstance = $this->get_from_entity_map($object->ID());
5403
+		if ($classInstance) {
5404
+			return $classInstance;
5405
+		}
5406
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5407
+		return $object;
5408
+	}
5409
+
5410
+
5411
+
5412
+	/**
5413
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5414
+	 * if no identifier is provided, then the entire entity map is emptied
5415
+	 *
5416
+	 * @param int|string $id the ID of the model object
5417
+	 * @return boolean
5418
+	 */
5419
+	public function clear_entity_map($id = null)
5420
+	{
5421
+		if (empty($id)) {
5422
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5423
+			return true;
5424
+		}
5425
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5426
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5427
+			return true;
5428
+		}
5429
+		return false;
5430
+	}
5431
+
5432
+
5433
+
5434
+	/**
5435
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5436
+	 * Given an array where keys are column (or column alias) names and values,
5437
+	 * returns an array of their corresponding field names and database values
5438
+	 *
5439
+	 * @param array $cols_n_values
5440
+	 * @return array
5441
+	 */
5442
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5443
+	{
5444
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5445
+	}
5446
+
5447
+
5448
+
5449
+	/**
5450
+	 * _deduce_fields_n_values_from_cols_n_values
5451
+	 * Given an array where keys are column (or column alias) names and values,
5452
+	 * returns an array of their corresponding field names and database values
5453
+	 *
5454
+	 * @param string $cols_n_values
5455
+	 * @return array
5456
+	 */
5457
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5458
+	{
5459
+		$this_model_fields_n_values = array();
5460
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5461
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5462
+				$cols_n_values,
5463
+				$table_obj->get_fully_qualified_pk_column(),
5464
+				$table_obj->get_pk_column()
5465
+			);
5466
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5467
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5468
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5469
+					if (! $field_obj->is_db_only_field()) {
5470
+						// prepare field as if its coming from db
5471
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5472
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5473
+					}
5474
+				}
5475
+			} else {
5476
+				// the table's rows existed. Use their values
5477
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5478
+					if (! $field_obj->is_db_only_field()) {
5479
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5480
+							$cols_n_values,
5481
+							$field_obj->get_qualified_column(),
5482
+							$field_obj->get_table_column()
5483
+						);
5484
+					}
5485
+				}
5486
+			}
5487
+		}
5488
+		return $this_model_fields_n_values;
5489
+	}
5490
+
5491
+
5492
+	/**
5493
+	 * @param $cols_n_values
5494
+	 * @param $qualified_column
5495
+	 * @param $regular_column
5496
+	 * @return null
5497
+	 * @throws EE_Error
5498
+	 * @throws ReflectionException
5499
+	 */
5500
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5501
+	{
5502
+		$value = null;
5503
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5504
+		// does the field on the model relate to this column retrieved from the db?
5505
+		// or is it a db-only field? (not relating to the model)
5506
+		if (isset($cols_n_values[ $qualified_column ])) {
5507
+			$value = $cols_n_values[ $qualified_column ];
5508
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5509
+			$value = $cols_n_values[ $regular_column ];
5510
+		} elseif (! empty($this->foreign_key_aliases)) {
5511
+			// no PK?  ok check if there is a foreign key alias set for this table
5512
+			// then check if that alias exists in the incoming data
5513
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5514
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5515
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5516
+					$value = $cols_n_values[ $FK_alias ];
5517
+					[$pk_class] = explode('.', $PK_column);
5518
+					$pk_model_name = "EEM_{$pk_class}";
5519
+					/** @var EEM_Base $pk_model */
5520
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5521
+					if ($pk_model instanceof EEM_Base) {
5522
+						// make sure object is pulled from db and added to entity map
5523
+						$pk_model->get_one_by_ID($value);
5524
+					}
5525
+					break;
5526
+				}
5527
+			}
5528
+		}
5529
+		return $value;
5530
+	}
5531
+
5532
+
5533
+
5534
+	/**
5535
+	 * refresh_entity_map_from_db
5536
+	 * Makes sure the model object in the entity map at $id assumes the values
5537
+	 * of the database (opposite of EE_base_Class::save())
5538
+	 *
5539
+	 * @param int|string $id
5540
+	 * @return EE_Base_Class
5541
+	 * @throws EE_Error
5542
+	 */
5543
+	public function refresh_entity_map_from_db($id)
5544
+	{
5545
+		$obj_in_map = $this->get_from_entity_map($id);
5546
+		if ($obj_in_map) {
5547
+			$wpdb_results = $this->_get_all_wpdb_results(
5548
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5549
+			);
5550
+			if ($wpdb_results && is_array($wpdb_results)) {
5551
+				$one_row = reset($wpdb_results);
5552
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5553
+					$obj_in_map->set_from_db($field_name, $db_value);
5554
+				}
5555
+				// clear the cache of related model objects
5556
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5557
+					$obj_in_map->clear_cache($relation_name, null, true);
5558
+				}
5559
+			}
5560
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5561
+			return $obj_in_map;
5562
+		}
5563
+		return $this->get_one_by_ID($id);
5564
+	}
5565
+
5566
+
5567
+
5568
+	/**
5569
+	 * refresh_entity_map_with
5570
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5571
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5572
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5573
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5574
+	 *
5575
+	 * @param int|string    $id
5576
+	 * @param EE_Base_Class $replacing_model_obj
5577
+	 * @return \EE_Base_Class
5578
+	 * @throws EE_Error
5579
+	 */
5580
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5581
+	{
5582
+		$obj_in_map = $this->get_from_entity_map($id);
5583
+		if ($obj_in_map) {
5584
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5585
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5586
+					$obj_in_map->set($field_name, $value);
5587
+				}
5588
+				// make the model object in the entity map's cache match the $replacing_model_obj
5589
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5590
+					$obj_in_map->clear_cache($relation_name, null, true);
5591
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5592
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5593
+					}
5594
+				}
5595
+			}
5596
+			return $obj_in_map;
5597
+		}
5598
+		$this->add_to_entity_map($replacing_model_obj);
5599
+		return $replacing_model_obj;
5600
+	}
5601
+
5602
+
5603
+
5604
+	/**
5605
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5606
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5607
+	 * require_once($this->_getClassName().".class.php");
5608
+	 *
5609
+	 * @return string
5610
+	 */
5611
+	private function _get_class_name()
5612
+	{
5613
+		return "EE_" . $this->get_this_model_name();
5614
+	}
5615
+
5616
+
5617
+
5618
+	/**
5619
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5620
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5621
+	 * it would be 'Events'.
5622
+	 *
5623
+	 * @param int $quantity
5624
+	 * @return string
5625
+	 */
5626
+	public function item_name($quantity = 1)
5627
+	{
5628
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5629
+	}
5630
+
5631
+
5632
+
5633
+	/**
5634
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5635
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5636
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5637
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5638
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5639
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5640
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5641
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5642
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5643
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5644
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5645
+	 *        return $previousReturnValue.$returnString;
5646
+	 * }
5647
+	 * require('EEM_Answer.model.php');
5648
+	 * $answer=EEM_Answer::instance();
5649
+	 * echo $answer->my_callback('monkeys',100);
5650
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5651
+	 *
5652
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5653
+	 * @param array  $args       array of original arguments passed to the function
5654
+	 * @throws EE_Error
5655
+	 * @return mixed whatever the plugin which calls add_filter decides
5656
+	 */
5657
+	public function __call($methodName, $args)
5658
+	{
5659
+		$className = get_class($this);
5660
+		$tagName = "FHEE__{$className}__{$methodName}";
5661
+		if (! has_filter($tagName)) {
5662
+			throw new EE_Error(
5663
+				sprintf(
5664
+					__(
5665
+						'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 );',
5666
+						'event_espresso'
5667
+					),
5668
+					$methodName,
5669
+					$className,
5670
+					$tagName,
5671
+					'<br />'
5672
+				)
5673
+			);
5674
+		}
5675
+		return apply_filters($tagName, null, $this, $args);
5676
+	}
5677
+
5678
+
5679
+
5680
+	/**
5681
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5682
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5683
+	 *
5684
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5685
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5686
+	 *                                                       the object's class name
5687
+	 *                                                       or object's ID
5688
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5689
+	 *                                                       exists in the database. If it does not, we add it
5690
+	 * @throws EE_Error
5691
+	 * @return EE_Base_Class
5692
+	 */
5693
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5694
+	{
5695
+		$className = $this->_get_class_name();
5696
+		if ($base_class_obj_or_id instanceof $className) {
5697
+			$model_object = $base_class_obj_or_id;
5698
+		} else {
5699
+			$primary_key_field = $this->get_primary_key_field();
5700
+			if (
5701
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5702
+				&& (
5703
+					is_int($base_class_obj_or_id)
5704
+					|| is_string($base_class_obj_or_id)
5705
+				)
5706
+			) {
5707
+				// assume it's an ID.
5708
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5709
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5710
+			} elseif (
5711
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5712
+				&& is_string($base_class_obj_or_id)
5713
+			) {
5714
+				// assume its a string representation of the object
5715
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5716
+			} else {
5717
+				throw new EE_Error(
5718
+					sprintf(
5719
+						__(
5720
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5721
+							'event_espresso'
5722
+						),
5723
+						$base_class_obj_or_id,
5724
+						$this->_get_class_name(),
5725
+						print_r($base_class_obj_or_id, true)
5726
+					)
5727
+				);
5728
+			}
5729
+		}
5730
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5731
+			$model_object->save();
5732
+		}
5733
+		return $model_object;
5734
+	}
5735
+
5736
+
5737
+
5738
+	/**
5739
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5740
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5741
+	 * returns it ID.
5742
+	 *
5743
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5744
+	 * @return int|string depending on the type of this model object's ID
5745
+	 * @throws EE_Error
5746
+	 */
5747
+	public function ensure_is_ID($base_class_obj_or_id)
5748
+	{
5749
+		$className = $this->_get_class_name();
5750
+		if ($base_class_obj_or_id instanceof $className) {
5751
+			/** @var $base_class_obj_or_id EE_Base_Class */
5752
+			$id = $base_class_obj_or_id->ID();
5753
+		} elseif (is_int($base_class_obj_or_id)) {
5754
+			// assume it's an ID
5755
+			$id = $base_class_obj_or_id;
5756
+		} elseif (is_string($base_class_obj_or_id)) {
5757
+			// assume its a string representation of the object
5758
+			$id = $base_class_obj_or_id;
5759
+		} else {
5760
+			throw new EE_Error(sprintf(
5761
+				__(
5762
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5763
+					'event_espresso'
5764
+				),
5765
+				$base_class_obj_or_id,
5766
+				$this->_get_class_name(),
5767
+				print_r($base_class_obj_or_id, true)
5768
+			));
5769
+		}
5770
+		return $id;
5771
+	}
5772
+
5773
+
5774
+
5775
+	/**
5776
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5777
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5778
+	 * been sanitized and converted into the appropriate domain.
5779
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5780
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5781
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5782
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5783
+	 * $EVT = EEM_Event::instance(); $old_setting =
5784
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5785
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5786
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5787
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5788
+	 *
5789
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5790
+	 * @return void
5791
+	 */
5792
+	public function assume_values_already_prepared_by_model_object(
5793
+		$values_already_prepared = self::not_prepared_by_model_object
5794
+	) {
5795
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5796
+	}
5797
+
5798
+
5799
+
5800
+	/**
5801
+	 * Read comments for assume_values_already_prepared_by_model_object()
5802
+	 *
5803
+	 * @return int
5804
+	 */
5805
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5806
+	{
5807
+		return $this->_values_already_prepared_by_model_object;
5808
+	}
5809
+
5810
+
5811
+
5812
+	/**
5813
+	 * Gets all the indexes on this model
5814
+	 *
5815
+	 * @return EE_Index[]
5816
+	 */
5817
+	public function indexes()
5818
+	{
5819
+		return $this->_indexes;
5820
+	}
5821
+
5822
+
5823
+
5824
+	/**
5825
+	 * Gets all the Unique Indexes on this model
5826
+	 *
5827
+	 * @return EE_Unique_Index[]
5828
+	 */
5829
+	public function unique_indexes()
5830
+	{
5831
+		$unique_indexes = array();
5832
+		foreach ($this->_indexes as $name => $index) {
5833
+			if ($index instanceof EE_Unique_Index) {
5834
+				$unique_indexes [ $name ] = $index;
5835
+			}
5836
+		}
5837
+		return $unique_indexes;
5838
+	}
5839
+
5840
+
5841
+
5842
+	/**
5843
+	 * Gets all the fields which, when combined, make the primary key.
5844
+	 * This is usually just an array with 1 element (the primary key), but in cases
5845
+	 * where there is no primary key, it's a combination of fields as defined
5846
+	 * on a primary index
5847
+	 *
5848
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5849
+	 * @throws EE_Error
5850
+	 */
5851
+	public function get_combined_primary_key_fields()
5852
+	{
5853
+		foreach ($this->indexes() as $index) {
5854
+			if ($index instanceof EE_Primary_Key_Index) {
5855
+				return $index->fields();
5856
+			}
5857
+		}
5858
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5859
+	}
5860
+
5861
+
5862
+
5863
+	/**
5864
+	 * Used to build a primary key string (when the model has no primary key),
5865
+	 * which can be used a unique string to identify this model object.
5866
+	 *
5867
+	 * @param array $fields_n_values keys are field names, values are their values.
5868
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5869
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5870
+	 *                               before passing it to this function (that will convert it from columns-n-values
5871
+	 *                               to field-names-n-values).
5872
+	 * @return string
5873
+	 * @throws EE_Error
5874
+	 */
5875
+	public function get_index_primary_key_string($fields_n_values)
5876
+	{
5877
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5878
+			$fields_n_values,
5879
+			$this->get_combined_primary_key_fields()
5880
+		);
5881
+		return http_build_query($cols_n_values_for_primary_key_index);
5882
+	}
5883
+
5884
+
5885
+
5886
+	/**
5887
+	 * Gets the field values from the primary key string
5888
+	 *
5889
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5890
+	 * @param string $index_primary_key_string
5891
+	 * @return null|array
5892
+	 * @throws EE_Error
5893
+	 */
5894
+	public function parse_index_primary_key_string($index_primary_key_string)
5895
+	{
5896
+		$key_fields = $this->get_combined_primary_key_fields();
5897
+		// check all of them are in the $id
5898
+		$key_vals_in_combined_pk = array();
5899
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5900
+		foreach ($key_fields as $key_field_name => $field_obj) {
5901
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5902
+				return null;
5903
+			}
5904
+		}
5905
+		return $key_vals_in_combined_pk;
5906
+	}
5907
+
5908
+
5909
+
5910
+	/**
5911
+	 * verifies that an array of key-value pairs for model fields has a key
5912
+	 * for each field comprising the primary key index
5913
+	 *
5914
+	 * @param array $key_vals
5915
+	 * @return boolean
5916
+	 * @throws EE_Error
5917
+	 */
5918
+	public function has_all_combined_primary_key_fields($key_vals)
5919
+	{
5920
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5921
+		foreach ($keys_it_should_have as $key) {
5922
+			if (! isset($key_vals[ $key ])) {
5923
+				return false;
5924
+			}
5925
+		}
5926
+		return true;
5927
+	}
5928
+
5929
+
5930
+
5931
+	/**
5932
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5933
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5934
+	 *
5935
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5936
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5937
+	 * @throws EE_Error
5938
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5939
+	 *                                                              indexed)
5940
+	 */
5941
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5942
+	{
5943
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5944
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5945
+		} elseif (is_array($model_object_or_attributes_array)) {
5946
+			$attributes_array = $model_object_or_attributes_array;
5947
+		} else {
5948
+			throw new EE_Error(sprintf(__(
5949
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5950
+				"event_espresso"
5951
+			), $model_object_or_attributes_array));
5952
+		}
5953
+		// even copies obviously won't have the same ID, so remove the primary key
5954
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
+			unset($attributes_array[ $this->primary_key_name() ]);
5957
+		}
5958
+		if (isset($query_params[0])) {
5959
+			$query_params[0] = array_merge($attributes_array, $query_params);
5960
+		} else {
5961
+			$query_params[0] = $attributes_array;
5962
+		}
5963
+		return $this->get_all($query_params);
5964
+	}
5965
+
5966
+
5967
+
5968
+	/**
5969
+	 * Gets the first copy we find. See get_all_copies for more details
5970
+	 *
5971
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5972
+	 * @param array $query_params
5973
+	 * @return EE_Base_Class
5974
+	 * @throws EE_Error
5975
+	 */
5976
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5977
+	{
5978
+		if (! is_array($query_params)) {
5979
+			EE_Error::doing_it_wrong(
5980
+				'EEM_Base::get_one_copy',
5981
+				sprintf(
5982
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5983
+					gettype($query_params)
5984
+				),
5985
+				'4.6.0'
5986
+			);
5987
+			$query_params = array();
5988
+		}
5989
+		$query_params['limit'] = 1;
5990
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5991
+		if (is_array($copies)) {
5992
+			return array_shift($copies);
5993
+		}
5994
+		return null;
5995
+	}
5996
+
5997
+
5998
+
5999
+	/**
6000
+	 * Updates the item with the specified id. Ignores default query parameters because
6001
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6002
+	 *
6003
+	 * @param array      $fields_n_values keys are field names, values are their new values
6004
+	 * @param int|string $id              the value of the primary key to update
6005
+	 * @return int number of rows updated
6006
+	 * @throws EE_Error
6007
+	 */
6008
+	public function update_by_ID($fields_n_values, $id)
6009
+	{
6010
+		$query_params = array(
6011
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
6012
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6013
+		);
6014
+		return $this->update($fields_n_values, $query_params);
6015
+	}
6016
+
6017
+
6018
+
6019
+	/**
6020
+	 * Changes an operator which was supplied to the models into one usable in SQL
6021
+	 *
6022
+	 * @param string $operator_supplied
6023
+	 * @return string an operator which can be used in SQL
6024
+	 * @throws EE_Error
6025
+	 */
6026
+	private function _prepare_operator_for_sql($operator_supplied)
6027
+	{
6028
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6029
+			: null;
6030
+		if ($sql_operator) {
6031
+			return $sql_operator;
6032
+		}
6033
+		throw new EE_Error(
6034
+			sprintf(
6035
+				__(
6036
+					"The operator '%s' is not in the list of valid operators: %s",
6037
+					"event_espresso"
6038
+				),
6039
+				$operator_supplied,
6040
+				implode(",", array_keys($this->_valid_operators))
6041
+			)
6042
+		);
6043
+	}
6044
+
6045
+
6046
+
6047
+	/**
6048
+	 * Gets the valid operators
6049
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6050
+	 */
6051
+	public function valid_operators()
6052
+	{
6053
+		return $this->_valid_operators;
6054
+	}
6055
+
6056
+
6057
+
6058
+	/**
6059
+	 * Gets the between-style operators (take 2 arguments).
6060
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6061
+	 */
6062
+	public function valid_between_style_operators()
6063
+	{
6064
+		return array_intersect(
6065
+			$this->valid_operators(),
6066
+			$this->_between_style_operators
6067
+		);
6068
+	}
6069
+
6070
+	/**
6071
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6072
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6073
+	 */
6074
+	public function valid_like_style_operators()
6075
+	{
6076
+		return array_intersect(
6077
+			$this->valid_operators(),
6078
+			$this->_like_style_operators
6079
+		);
6080
+	}
6081
+
6082
+	/**
6083
+	 * Gets the "in"-style operators
6084
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6085
+	 */
6086
+	public function valid_in_style_operators()
6087
+	{
6088
+		return array_intersect(
6089
+			$this->valid_operators(),
6090
+			$this->_in_style_operators
6091
+		);
6092
+	}
6093
+
6094
+	/**
6095
+	 * Gets the "null"-style operators (accept no arguments)
6096
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6097
+	 */
6098
+	public function valid_null_style_operators()
6099
+	{
6100
+		return array_intersect(
6101
+			$this->valid_operators(),
6102
+			$this->_null_style_operators
6103
+		);
6104
+	}
6105
+
6106
+	/**
6107
+	 * Gets an array where keys are the primary keys and values are their 'names'
6108
+	 * (as determined by the model object's name() function, which is often overridden)
6109
+	 *
6110
+	 * @param array $query_params like get_all's
6111
+	 * @return string[]
6112
+	 * @throws EE_Error
6113
+	 */
6114
+	public function get_all_names($query_params = array())
6115
+	{
6116
+		$objs = $this->get_all($query_params);
6117
+		$names = array();
6118
+		foreach ($objs as $obj) {
6119
+			$names[ $obj->ID() ] = $obj->name();
6120
+		}
6121
+		return $names;
6122
+	}
6123
+
6124
+
6125
+
6126
+	/**
6127
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6128
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6129
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6130
+	 * array_keys() on $model_objects.
6131
+	 *
6132
+	 * @param \EE_Base_Class[] $model_objects
6133
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6134
+	 *                                               in the returned array
6135
+	 * @return array
6136
+	 * @throws EE_Error
6137
+	 */
6138
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6139
+	{
6140
+		if (! $this->has_primary_key_field()) {
6141
+			if (WP_DEBUG) {
6142
+				EE_Error::add_error(
6143
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6144
+					__FILE__,
6145
+					__FUNCTION__,
6146
+					__LINE__
6147
+				);
6148
+			}
6149
+		}
6150
+		$IDs = array();
6151
+		foreach ($model_objects as $model_object) {
6152
+			$id = $model_object->ID();
6153
+			if (! $id) {
6154
+				if ($filter_out_empty_ids) {
6155
+					continue;
6156
+				}
6157
+				if (WP_DEBUG) {
6158
+					EE_Error::add_error(
6159
+						__(
6160
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6161
+							'event_espresso'
6162
+						),
6163
+						__FILE__,
6164
+						__FUNCTION__,
6165
+						__LINE__
6166
+					);
6167
+				}
6168
+			}
6169
+			$IDs[] = $id;
6170
+		}
6171
+		return $IDs;
6172
+	}
6173
+
6174
+
6175
+
6176
+	/**
6177
+	 * Returns the string used in capabilities relating to this model. If there
6178
+	 * are no capabilities that relate to this model returns false
6179
+	 *
6180
+	 * @return string|false
6181
+	 */
6182
+	public function cap_slug()
6183
+	{
6184
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6185
+	}
6186
+
6187
+
6188
+
6189
+	/**
6190
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6191
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6192
+	 * only returns the cap restrictions array in that context (ie, the array
6193
+	 * at that key)
6194
+	 *
6195
+	 * @param string $context
6196
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6197
+	 * @throws EE_Error
6198
+	 */
6199
+	public function cap_restrictions($context = EEM_Base::caps_read)
6200
+	{
6201
+		EEM_Base::verify_is_valid_cap_context($context);
6202
+		// check if we ought to run the restriction generator first
6203
+		if (
6204
+			isset($this->_cap_restriction_generators[ $context ])
6205
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6206
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6207
+		) {
6208
+			$this->_cap_restrictions[ $context ] = array_merge(
6209
+				$this->_cap_restrictions[ $context ],
6210
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6211
+			);
6212
+		}
6213
+		// and make sure we've finalized the construction of each restriction
6214
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6215
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6216
+				$where_conditions_obj->_finalize_construct($this);
6217
+			}
6218
+		}
6219
+		return $this->_cap_restrictions[ $context ];
6220
+	}
6221
+
6222
+
6223
+
6224
+	/**
6225
+	 * Indicating whether or not this model thinks its a wp core model
6226
+	 *
6227
+	 * @return boolean
6228
+	 */
6229
+	public function is_wp_core_model()
6230
+	{
6231
+		return $this->_wp_core_model;
6232
+	}
6233
+
6234
+
6235
+
6236
+	/**
6237
+	 * Gets all the caps that are missing which impose a restriction on
6238
+	 * queries made in this context
6239
+	 *
6240
+	 * @param string $context one of EEM_Base::caps_ constants
6241
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6242
+	 * @throws EE_Error
6243
+	 */
6244
+	public function caps_missing($context = EEM_Base::caps_read)
6245
+	{
6246
+		$missing_caps = array();
6247
+		$cap_restrictions = $this->cap_restrictions($context);
6248
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6249
+			if (
6250
+				! EE_Capabilities::instance()
6251
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6252
+			) {
6253
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6254
+			}
6255
+		}
6256
+		return $missing_caps;
6257
+	}
6258
+
6259
+
6260
+
6261
+	/**
6262
+	 * Gets the mapping from capability contexts to action strings used in capability names
6263
+	 *
6264
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6265
+	 * one of 'read', 'edit', or 'delete'
6266
+	 */
6267
+	public function cap_contexts_to_cap_action_map()
6268
+	{
6269
+		return apply_filters(
6270
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6271
+			$this->_cap_contexts_to_cap_action_map,
6272
+			$this
6273
+		);
6274
+	}
6275
+
6276
+
6277
+
6278
+	/**
6279
+	 * Gets the action string for the specified capability context
6280
+	 *
6281
+	 * @param string $context
6282
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6283
+	 * @throws EE_Error
6284
+	 */
6285
+	public function cap_action_for_context($context)
6286
+	{
6287
+		$mapping = $this->cap_contexts_to_cap_action_map();
6288
+		if (isset($mapping[ $context ])) {
6289
+			return $mapping[ $context ];
6290
+		}
6291
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6292
+			return $action;
6293
+		}
6294
+		throw new EE_Error(
6295
+			sprintf(
6296
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6297
+				$context,
6298
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6299
+			)
6300
+		);
6301
+	}
6302
+
6303
+
6304
+
6305
+	/**
6306
+	 * Returns all the capability contexts which are valid when querying models
6307
+	 *
6308
+	 * @return array
6309
+	 */
6310
+	public static function valid_cap_contexts()
6311
+	{
6312
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6313
+			self::caps_read,
6314
+			self::caps_read_admin,
6315
+			self::caps_edit,
6316
+			self::caps_delete,
6317
+		));
6318
+	}
6319
+
6320
+
6321
+
6322
+	/**
6323
+	 * Returns all valid options for 'default_where_conditions'
6324
+	 *
6325
+	 * @return array
6326
+	 */
6327
+	public static function valid_default_where_conditions()
6328
+	{
6329
+		return array(
6330
+			EEM_Base::default_where_conditions_all,
6331
+			EEM_Base::default_where_conditions_this_only,
6332
+			EEM_Base::default_where_conditions_others_only,
6333
+			EEM_Base::default_where_conditions_minimum_all,
6334
+			EEM_Base::default_where_conditions_minimum_others,
6335
+			EEM_Base::default_where_conditions_none
6336
+		);
6337
+	}
6338
+
6339
+	// public static function default_where_conditions_full
6340
+	/**
6341
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6342
+	 *
6343
+	 * @param string $context
6344
+	 * @return bool
6345
+	 * @throws EE_Error
6346
+	 */
6347
+	public static function verify_is_valid_cap_context($context)
6348
+	{
6349
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6350
+		if (in_array($context, $valid_cap_contexts)) {
6351
+			return true;
6352
+		}
6353
+		throw new EE_Error(
6354
+			sprintf(
6355
+				__(
6356
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6357
+					'event_espresso'
6358
+				),
6359
+				$context,
6360
+				'EEM_Base',
6361
+				implode(',', $valid_cap_contexts)
6362
+			)
6363
+		);
6364
+	}
6365
+
6366
+
6367
+
6368
+	/**
6369
+	 * Clears all the models field caches. This is only useful when a sub-class
6370
+	 * might have added a field or something and these caches might be invalidated
6371
+	 */
6372
+	protected function _invalidate_field_caches()
6373
+	{
6374
+		$this->_cache_foreign_key_to_fields = array();
6375
+		$this->_cached_fields = null;
6376
+		$this->_cached_fields_non_db_only = null;
6377
+	}
6378
+
6379
+
6380
+
6381
+	/**
6382
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6383
+	 * (eg "and", "or", "not").
6384
+	 *
6385
+	 * @return array
6386
+	 */
6387
+	public function logic_query_param_keys()
6388
+	{
6389
+		return $this->_logic_query_param_keys;
6390
+	}
6391
+
6392
+
6393
+
6394
+	/**
6395
+	 * Determines whether or not the where query param array key is for a logic query param.
6396
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6397
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6398
+	 *
6399
+	 * @param $query_param_key
6400
+	 * @return bool
6401
+	 */
6402
+	public function is_logic_query_param_key($query_param_key)
6403
+	{
6404
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6405
+			if (
6406
+				$query_param_key === $logic_query_param_key
6407
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6408
+			) {
6409
+				return true;
6410
+			}
6411
+		}
6412
+		return false;
6413
+	}
6414
+
6415
+	/**
6416
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6417
+	 * @since 4.9.74.p
6418
+	 * @return boolean
6419
+	 */
6420
+	public function hasPassword()
6421
+	{
6422
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6423
+		if ($this->has_password_field === null) {
6424
+			$password_field = $this->getPasswordField();
6425
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6426
+		}
6427
+		return $this->has_password_field;
6428
+	}
6429
+
6430
+	/**
6431
+	 * Returns the password field on this model, if there is one
6432
+	 * @since 4.9.74.p
6433
+	 * @return EE_Password_Field|null
6434
+	 */
6435
+	public function getPasswordField()
6436
+	{
6437
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6438
+		// there's no need to search for it. If we don't know yet, then find out
6439
+		if ($this->has_password_field === null && $this->password_field === null) {
6440
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6441
+		}
6442
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6443
+		return $this->password_field;
6444
+	}
6445
+
6446
+
6447
+	/**
6448
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6449
+	 * @since 4.9.74.p
6450
+	 * @return EE_Model_Field_Base[]
6451
+	 * @throws EE_Error
6452
+	 */
6453
+	public function getPasswordProtectedFields()
6454
+	{
6455
+		$password_field = $this->getPasswordField();
6456
+		$fields = array();
6457
+		if ($password_field instanceof EE_Password_Field) {
6458
+			$field_names = $password_field->protectedFields();
6459
+			foreach ($field_names as $field_name) {
6460
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6461
+			}
6462
+		}
6463
+		return $fields;
6464
+	}
6465
+
6466
+
6467
+	/**
6468
+	 * Checks if the current user can perform the requested action on this model
6469
+	 * @since 4.9.74.p
6470
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6471
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6472
+	 * @return bool
6473
+	 * @throws EE_Error
6474
+	 * @throws InvalidArgumentException
6475
+	 * @throws InvalidDataTypeException
6476
+	 * @throws InvalidInterfaceException
6477
+	 * @throws ReflectionException
6478
+	 * @throws UnexpectedEntityException
6479
+	 */
6480
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6481
+	{
6482
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6483
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6484
+		}
6485
+		if (!is_array($model_obj_or_fields_n_values)) {
6486
+			throw new UnexpectedEntityException(
6487
+				$model_obj_or_fields_n_values,
6488
+				'EE_Base_Class',
6489
+				sprintf(
6490
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6491
+					__FUNCTION__
6492
+				)
6493
+			);
6494
+		}
6495
+		return $this->exists(
6496
+			$this->alter_query_params_to_restrict_by_ID(
6497
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6498
+				array(
6499
+					'default_where_conditions' => 'none',
6500
+					'caps'                     => $cap_to_check,
6501
+				)
6502
+			)
6503
+		);
6504
+	}
6505
+
6506
+	/**
6507
+	 * Returns the query param where conditions key to the password affecting this model.
6508
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6509
+	 * @since 4.9.74.p
6510
+	 * @return null|string
6511
+	 * @throws EE_Error
6512
+	 * @throws InvalidArgumentException
6513
+	 * @throws InvalidDataTypeException
6514
+	 * @throws InvalidInterfaceException
6515
+	 * @throws ModelConfigurationException
6516
+	 * @throws ReflectionException
6517
+	 */
6518
+	public function modelChainAndPassword()
6519
+	{
6520
+		if ($this->model_chain_to_password === null) {
6521
+			throw new ModelConfigurationException(
6522
+				$this,
6523
+				esc_html_x(
6524
+				// @codingStandardsIgnoreStart
6525
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6526
+					// @codingStandardsIgnoreEnd
6527
+					'1: model name',
6528
+					'event_espresso'
6529
+				)
6530
+			);
6531
+		}
6532
+		if ($this->model_chain_to_password === '') {
6533
+			$model_with_password = $this;
6534
+		} else {
6535
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6536
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6537
+			} else {
6538
+				$last_model_in_chain = $this->model_chain_to_password;
6539
+			}
6540
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6541
+		}
6542
+
6543
+		$password_field = $model_with_password->getPasswordField();
6544
+		if ($password_field instanceof EE_Password_Field) {
6545
+			$password_field_name = $password_field->get_name();
6546
+		} else {
6547
+			throw new ModelConfigurationException(
6548
+				$this,
6549
+				sprintf(
6550
+					esc_html_x(
6551
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6552
+						'1: model name, 2: special string',
6553
+						'event_espresso'
6554
+					),
6555
+					$model_with_password->get_this_model_name(),
6556
+					$this->model_chain_to_password
6557
+				)
6558
+			);
6559
+		}
6560
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6561
+	}
6562
+
6563
+	/**
6564
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6565
+	 * or if this model itself has a password affecting access to some of its other fields.
6566
+	 * @since 4.9.74.p
6567
+	 * @return boolean
6568
+	 */
6569
+	public function restrictedByRelatedModelPassword()
6570
+	{
6571
+		return $this->model_chain_to_password !== null;
6572
+	}
6573 6573
 }
Please login to merge, or discard this patch.
Spacing   +229 added lines, -229 removed lines patch added patch discarded remove patch
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
     protected function __construct($timezone = null)
566 566
     {
567 567
         // check that the model has not been loaded too soon
568
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
568
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
569 569
             throw new EE_Error(
570 570
                 sprintf(
571 571
                     __(
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
          *
589 589
          * @var EE_Table_Base[] $_tables
590 590
          */
591
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
591
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
592 592
         foreach ($this->_tables as $table_alias => $table_obj) {
593 593
             /** @var $table_obj EE_Table_Base */
594 594
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -603,10 +603,10 @@  discard block
 block discarded – undo
603 603
          *
604 604
          * @param EE_Model_Field_Base[] $_fields
605 605
          */
606
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
606
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
607 607
         $this->_invalidate_field_caches();
608 608
         foreach ($this->_fields as $table_alias => $fields_for_table) {
609
-            if (! array_key_exists($table_alias, $this->_tables)) {
609
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
610 610
                 throw new EE_Error(sprintf(__(
611 611
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
612 612
                     'event_espresso'
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
          * @param EE_Model_Relation_Base[] $_model_relations
638 638
          */
639 639
         $this->_model_relations = (array) apply_filters(
640
-            'FHEE__' . get_class($this) . '__construct__model_relations',
640
+            'FHEE__'.get_class($this).'__construct__model_relations',
641 641
             $this->_model_relations
642 642
         );
643 643
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -649,12 +649,12 @@  discard block
 block discarded – undo
649 649
         }
650 650
         $this->set_timezone($timezone);
651 651
         // finalize default where condition strategy, or set default
652
-        if (! $this->_default_where_conditions_strategy) {
652
+        if ( ! $this->_default_where_conditions_strategy) {
653 653
             // nothing was set during child constructor, so set default
654 654
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
655 655
         }
656 656
         $this->_default_where_conditions_strategy->_finalize_construct($this);
657
-        if (! $this->_minimum_where_conditions_strategy) {
657
+        if ( ! $this->_minimum_where_conditions_strategy) {
658 658
             // nothing was set during child constructor, so set default
659 659
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
660 660
         }
@@ -667,8 +667,8 @@  discard block
 block discarded – undo
667 667
         // initialize the standard cap restriction generators if none were specified by the child constructor
668 668
         if (is_array($this->_cap_restriction_generators)) {
669 669
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
670
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
671
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
670
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
671
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
672 672
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
673 673
                         new EE_Restriction_Generator_Protected(),
674 674
                         $cap_context,
@@ -680,10 +680,10 @@  discard block
 block discarded – undo
680 680
         // if there are cap restriction generators, use them to make the default cap restrictions
681 681
         if (is_array($this->_cap_restriction_generators)) {
682 682
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
683
-                if (! $generator_object) {
683
+                if ( ! $generator_object) {
684 684
                     continue;
685 685
                 }
686
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
686
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
687 687
                     throw new EE_Error(
688 688
                         sprintf(
689 689
                             __(
@@ -696,12 +696,12 @@  discard block
 block discarded – undo
696 696
                     );
697 697
                 }
698 698
                 $action = $this->cap_action_for_context($context);
699
-                if (! $generator_object->construction_finalized()) {
699
+                if ( ! $generator_object->construction_finalized()) {
700 700
                     $generator_object->_construct_finalize($this, $action);
701 701
                 }
702 702
             }
703 703
         }
704
-        do_action('AHEE__' . get_class($this) . '__construct__end');
704
+        do_action('AHEE__'.get_class($this).'__construct__end');
705 705
     }
706 706
 
707 707
 
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
      */
714 714
     protected static function getLoader(): LoaderInterface
715 715
     {
716
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
716
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
717 717
             EEM_Base::$loader = LoaderFactory::getLoader();
718 718
         }
719 719
         return EEM_Base::$loader;
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
      */
727 727
     private static function getMirror(): Mirror
728 728
     {
729
-        if (! EEM_Base::$mirror instanceof Mirror) {
729
+        if ( ! EEM_Base::$mirror instanceof Mirror) {
730 730
             EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
731 731
         }
732 732
         return EEM_Base::$mirror;
@@ -782,14 +782,14 @@  discard block
 block discarded – undo
782 782
     public static function instance($timezone = null)
783 783
     {
784 784
         // check if instance of Espresso_model already exists
785
-        if (! static::$_instance instanceof static) {
785
+        if ( ! static::$_instance instanceof static) {
786 786
             $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
787 787
             $model = new static(...$arguments);
788 788
             EEM_Base::getLoader()->share(static::class, $model, $arguments);
789 789
             static::$_instance = $model;
790 790
         }
791 791
         // we might have a timezone set, let set_timezone decide what to do with it
792
-        if ($timezone){
792
+        if ($timezone) {
793 793
             static::$_instance->set_timezone($timezone);
794 794
         }
795 795
         // Espresso_model object
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
      */
813 813
     public static function reset($timezone = null)
814 814
     {
815
-        if (! static::$_instance instanceof EEM_Base) {
815
+        if ( ! static::$_instance instanceof EEM_Base) {
816 816
             return null;
817 817
         }
818 818
         // Let's NOT swap out the current instance for a new one
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
         foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
824 824
             // don't set instance to null like it was originally,
825 825
             // but it's static anyways, and we're ignoring static properties (for now at least)
826
-            if (! isset($static_properties[ $property ])) {
826
+            if ( ! isset($static_properties[$property])) {
827 827
                 static::$_instance->{$property} = $value;
828 828
             }
829 829
         }
@@ -872,7 +872,7 @@  discard block
 block discarded – undo
872 872
      */
873 873
     public function status_array($translated = false)
874 874
     {
875
-        if (! array_key_exists('Status', $this->_model_relations)) {
875
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
876 876
             return array();
877 877
         }
878 878
         $model_name = $this->get_this_model_name();
@@ -880,7 +880,7 @@  discard block
 block discarded – undo
880 880
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
881 881
         $status_array = array();
882 882
         foreach ($stati as $status) {
883
-            $status_array[ $status->ID() ] = $status->get('STS_code');
883
+            $status_array[$status->ID()] = $status->get('STS_code');
884 884
         }
885 885
         return $translated
886 886
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -941,7 +941,7 @@  discard block
 block discarded – undo
941 941
     {
942 942
         $wp_user_field_name = $this->wp_user_field_name();
943 943
         if ($wp_user_field_name) {
944
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
944
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
945 945
         }
946 946
         return $query_params;
947 947
     }
@@ -959,17 +959,17 @@  discard block
 block discarded – undo
959 959
     public function wp_user_field_name()
960 960
     {
961 961
         try {
962
-            if (! empty($this->_model_chain_to_wp_user)) {
962
+            if ( ! empty($this->_model_chain_to_wp_user)) {
963 963
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
964 964
                 $last_model_name = end($models_to_follow_to_wp_users);
965 965
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
966
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
966
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
967 967
             } else {
968 968
                 $model_with_fk_to_wp_users = $this;
969 969
                 $model_chain_to_wp_user = '';
970 970
             }
971 971
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
972
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
972
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
973 973
         } catch (EE_Error $e) {
974 974
             return false;
975 975
         }
@@ -1046,11 +1046,11 @@  discard block
 block discarded – undo
1046 1046
         if ($this->_custom_selections instanceof CustomSelects) {
1047 1047
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1048 1048
             $select_expressions .= $select_expressions
1049
-                ? ', ' . $custom_expressions
1049
+                ? ', '.$custom_expressions
1050 1050
                 : $custom_expressions;
1051 1051
         }
1052 1052
 
1053
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1053
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1054 1054
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1055 1055
     }
1056 1056
 
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
      */
1068 1068
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1069 1069
     {
1070
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1070
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1071 1071
             return null;
1072 1072
         }
1073 1073
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1116,7 +1116,7 @@  discard block
 block discarded – undo
1116 1116
         if (is_array($columns_to_select)) {
1117 1117
             $select_sql_array = array();
1118 1118
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1119
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1120 1120
                     throw new EE_Error(
1121 1121
                         sprintf(
1122 1122
                             __(
@@ -1128,7 +1128,7 @@  discard block
 block discarded – undo
1128 1128
                         )
1129 1129
                     );
1130 1130
                 }
1131
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1131
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1132 1132
                     throw new EE_Error(
1133 1133
                         sprintf(
1134 1134
                             esc_html__(
@@ -1207,12 +1207,12 @@  discard block
 block discarded – undo
1207 1207
      */
1208 1208
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1209 1209
     {
1210
-        if (! isset($query_params[0])) {
1210
+        if ( ! isset($query_params[0])) {
1211 1211
             $query_params[0] = array();
1212 1212
         }
1213 1213
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1214 1214
         if ($conditions_from_id === null) {
1215
-            $query_params[0][ $this->primary_key_name() ] = $id;
1215
+            $query_params[0][$this->primary_key_name()] = $id;
1216 1216
         } else {
1217 1217
             // no primary key, so the $id must be from the get_index_primary_key_string()
1218 1218
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1232,7 +1232,7 @@  discard block
 block discarded – undo
1232 1232
      */
1233 1233
     public function get_one($query_params = array())
1234 1234
     {
1235
-        if (! is_array($query_params)) {
1235
+        if ( ! is_array($query_params)) {
1236 1236
             EE_Error::doing_it_wrong(
1237 1237
                 'EEM_Base::get_one',
1238 1238
                 sprintf(
@@ -1430,7 +1430,7 @@  discard block
 block discarded – undo
1430 1430
                 return array();
1431 1431
             }
1432 1432
         }
1433
-        if (! is_array($query_params)) {
1433
+        if ( ! is_array($query_params)) {
1434 1434
             EE_Error::doing_it_wrong(
1435 1435
                 'EEM_Base::_get_consecutive',
1436 1436
                 sprintf(
@@ -1442,7 +1442,7 @@  discard block
 block discarded – undo
1442 1442
             $query_params = array();
1443 1443
         }
1444 1444
         // let's add the where query param for consecutive look up.
1445
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1445
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1446 1446
         $query_params['limit'] = $limit;
1447 1447
         // set direction
1448 1448
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1523,7 +1523,7 @@  discard block
 block discarded – undo
1523 1523
     {
1524 1524
         $field_settings = $this->field_settings_for($field_name);
1525 1525
         // if not a valid EE_Datetime_Field then throw error
1526
-        if (! $field_settings instanceof EE_Datetime_Field) {
1526
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1527 1527
             throw new EE_Error(sprintf(__(
1528 1528
                 '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.',
1529 1529
                 'event_espresso'
@@ -1672,7 +1672,7 @@  discard block
 block discarded – undo
1672 1672
      */
1673 1673
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674 1674
     {
1675
-        if (! is_array($query_params)) {
1675
+        if ( ! is_array($query_params)) {
1676 1676
             EE_Error::doing_it_wrong(
1677 1677
                 'EEM_Base::update',
1678 1678
                 sprintf(
@@ -1720,7 +1720,7 @@  discard block
 block discarded – undo
1720 1720
             $wpdb_result = (array) $wpdb_result;
1721 1721
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1722 1722
             if ($this->has_primary_key_field()) {
1723
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1723
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1724 1724
             } else {
1725 1725
                 // 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)
1726 1726
                 $main_table_pk_value = null;
@@ -1736,7 +1736,7 @@  discard block
 block discarded – undo
1736 1736
                     // in this table, right? so insert a row in the current table, using any fields available
1737 1737
                     if (
1738 1738
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1739
-                           && $wpdb_result[ $this_table_pk_column ])
1739
+                           && $wpdb_result[$this_table_pk_column])
1740 1740
                     ) {
1741 1741
                         $success = $this->_insert_into_specific_table(
1742 1742
                             $table_obj,
@@ -1744,7 +1744,7 @@  discard block
 block discarded – undo
1744 1744
                             $main_table_pk_value
1745 1745
                         );
1746 1746
                         // if we died here, report the error
1747
-                        if (! $success) {
1747
+                        if ( ! $success) {
1748 1748
                             return false;
1749 1749
                         }
1750 1750
                     }
@@ -1772,10 +1772,10 @@  discard block
 block discarded – undo
1772 1772
                 $model_objs_affected_ids = array();
1773 1773
                 foreach ($models_affected_key_columns as $row) {
1774 1774
                     $combined_index_key = $this->get_index_primary_key_string($row);
1775
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1775
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1776 1776
                 }
1777 1777
             }
1778
-            if (! $model_objs_affected_ids) {
1778
+            if ( ! $model_objs_affected_ids) {
1779 1779
                 // wait wait wait- if nothing was affected let's stop here
1780 1780
                 return 0;
1781 1781
             }
@@ -1802,7 +1802,7 @@  discard block
 block discarded – undo
1802 1802
                . $model_query_info->get_full_join_sql()
1803 1803
                . " SET "
1804 1804
                . $this->_construct_update_sql($fields_n_values)
1805
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1805
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1806 1806
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1807 1807
         /**
1808 1808
          * Action called after a model update call has been made.
@@ -1813,7 +1813,7 @@  discard block
 block discarded – undo
1813 1813
          * @param int      $rows_affected
1814 1814
          */
1815 1815
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1816
-        return $rows_affected;// how many supposedly got updated
1816
+        return $rows_affected; // how many supposedly got updated
1817 1817
     }
1818 1818
 
1819 1819
 
@@ -1841,7 +1841,7 @@  discard block
 block discarded – undo
1841 1841
         }
1842 1842
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1843 1843
         $select_expressions = $field->get_qualified_column();
1844
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1844
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1845 1845
         return $this->_do_wpdb_query('get_col', array($SQL));
1846 1846
     }
1847 1847
 
@@ -1859,7 +1859,7 @@  discard block
 block discarded – undo
1859 1859
     {
1860 1860
         $query_params['limit'] = 1;
1861 1861
         $col = $this->get_col($query_params, $field_to_select);
1862
-        if (! empty($col)) {
1862
+        if ( ! empty($col)) {
1863 1863
             return reset($col);
1864 1864
         }
1865 1865
         return null;
@@ -1890,7 +1890,7 @@  discard block
 block discarded – undo
1890 1890
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1891 1891
             $value_sql = $prepared_value === null ? 'NULL'
1892 1892
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1893
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1893
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1894 1894
         }
1895 1895
         return implode(",", $cols_n_values);
1896 1896
     }
@@ -2034,12 +2034,12 @@  discard block
 block discarded – undo
2034 2034
         if (
2035 2035
             $this->has_primary_key_field()
2036 2036
             && $rows_deleted !== false
2037
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2037
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2038 2038
         ) {
2039
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2039
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2040 2040
             foreach ($ids_for_removal as $id) {
2041
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2042
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2041
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2042
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2043 2043
                 }
2044 2044
             }
2045 2045
 
@@ -2076,7 +2076,7 @@  discard block
 block discarded – undo
2076 2076
          * @param int      $rows_deleted
2077 2077
          */
2078 2078
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2079
-        return $rows_deleted;// how many supposedly got deleted
2079
+        return $rows_deleted; // how many supposedly got deleted
2080 2080
     }
2081 2081
 
2082 2082
 
@@ -2170,15 +2170,15 @@  discard block
 block discarded – undo
2170 2170
                 if (
2171 2171
                     $allow_blocking
2172 2172
                     && $this->delete_is_blocked_by_related_models(
2173
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2173
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2174 2174
                     )
2175 2175
                 ) {
2176 2176
                     continue;
2177 2177
                 }
2178 2178
                 // primary table deletes
2179
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2180
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2181
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2179
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2180
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2181
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2182 2182
                 }
2183 2183
             }
2184 2184
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2187,8 +2187,8 @@  discard block
 block discarded – undo
2187 2187
                 $ids_to_delete_indexed_by_column_for_row = array();
2188 2188
                 foreach ($fields as $cpk_field) {
2189 2189
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2190
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2191
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2190
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2191
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2192 2192
                     }
2193 2193
                 }
2194 2194
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2228,7 +2228,7 @@  discard block
 block discarded – undo
2228 2228
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2229 2229
                 // make sure we have unique $ids
2230 2230
                 $ids = array_unique($ids);
2231
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2231
+                $query[] = $column.' IN('.implode(',', $ids).')';
2232 2232
             }
2233 2233
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2234 2234
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2236,7 +2236,7 @@  discard block
 block discarded – undo
2236 2236
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2237 2237
                 $values_for_each_combined_primary_key_for_a_row = array();
2238 2238
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2239
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2239
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2240 2240
                 }
2241 2241
                 $ways_to_identify_a_row[] = '('
2242 2242
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2308,8 +2308,8 @@  discard block
 block discarded – undo
2308 2308
                 $column_to_count = '*';
2309 2309
             }
2310 2310
         }
2311
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2312
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2311
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2312
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2313 2313
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2314 2314
     }
2315 2315
 
@@ -2332,7 +2332,7 @@  discard block
 block discarded – undo
2332 2332
             $field_obj = $this->get_primary_key_field();
2333 2333
         }
2334 2334
         $column_to_count = $field_obj->get_qualified_column();
2335
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2335
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2336 2336
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2337 2337
         $data_type = $field_obj->get_wpdb_data_type();
2338 2338
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2359,7 +2359,7 @@  discard block
 block discarded – undo
2359 2359
         // if we're in maintenance mode level 2, DON'T run any queries
2360 2360
         // because level 2 indicates the database needs updating and
2361 2361
         // is probably out of sync with the code
2362
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2362
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2363 2363
             throw new EE_Error(sprintf(__(
2364 2364
                 "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.",
2365 2365
                 "event_espresso"
@@ -2367,7 +2367,7 @@  discard block
 block discarded – undo
2367 2367
         }
2368 2368
         /** @type WPDB $wpdb */
2369 2369
         global $wpdb;
2370
-        if (! method_exists($wpdb, $wpdb_method)) {
2370
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2371 2371
             throw new EE_Error(sprintf(__(
2372 2372
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2373 2373
                 'event_espresso'
@@ -2381,7 +2381,7 @@  discard block
 block discarded – undo
2381 2381
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2382 2382
         if (WP_DEBUG) {
2383 2383
             $wpdb->show_errors($old_show_errors_value);
2384
-            if (! empty($wpdb->last_error)) {
2384
+            if ( ! empty($wpdb->last_error)) {
2385 2385
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2386 2386
             }
2387 2387
             if ($result === false) {
@@ -2447,7 +2447,7 @@  discard block
 block discarded – undo
2447 2447
                     return $result;
2448 2448
                     break;
2449 2449
             }
2450
-            if (! empty($error_message)) {
2450
+            if ( ! empty($error_message)) {
2451 2451
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2452 2452
                 trigger_error($error_message);
2453 2453
             }
@@ -2527,11 +2527,11 @@  discard block
 block discarded – undo
2527 2527
      */
2528 2528
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2529 2529
     {
2530
-        return " FROM " . $model_query_info->get_full_join_sql() .
2531
-               $model_query_info->get_where_sql() .
2532
-               $model_query_info->get_group_by_sql() .
2533
-               $model_query_info->get_having_sql() .
2534
-               $model_query_info->get_order_by_sql() .
2530
+        return " FROM ".$model_query_info->get_full_join_sql().
2531
+               $model_query_info->get_where_sql().
2532
+               $model_query_info->get_group_by_sql().
2533
+               $model_query_info->get_having_sql().
2534
+               $model_query_info->get_order_by_sql().
2535 2535
                $model_query_info->get_limit_sql();
2536 2536
     }
2537 2537
 
@@ -2727,12 +2727,12 @@  discard block
 block discarded – undo
2727 2727
         $related_model = $this->get_related_model_obj($model_name);
2728 2728
         // we're just going to use the query params on the related model's normal get_all query,
2729 2729
         // except add a condition to say to match the current mod
2730
-        if (! isset($query_params['default_where_conditions'])) {
2730
+        if ( ! isset($query_params['default_where_conditions'])) {
2731 2731
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2732 2732
         }
2733 2733
         $this_model_name = $this->get_this_model_name();
2734 2734
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2735
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2735
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2736 2736
         return $related_model->count($query_params, $field_to_count, $distinct);
2737 2737
     }
2738 2738
 
@@ -2752,7 +2752,7 @@  discard block
 block discarded – undo
2752 2752
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2753 2753
     {
2754 2754
         $related_model = $this->get_related_model_obj($model_name);
2755
-        if (! is_array($query_params)) {
2755
+        if ( ! is_array($query_params)) {
2756 2756
             EE_Error::doing_it_wrong(
2757 2757
                 'EEM_Base::sum_related',
2758 2758
                 sprintf(
@@ -2765,12 +2765,12 @@  discard block
 block discarded – undo
2765 2765
         }
2766 2766
         // we're just going to use the query params on the related model's normal get_all query,
2767 2767
         // except add a condition to say to match the current mod
2768
-        if (! isset($query_params['default_where_conditions'])) {
2768
+        if ( ! isset($query_params['default_where_conditions'])) {
2769 2769
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2770 2770
         }
2771 2771
         $this_model_name = $this->get_this_model_name();
2772 2772
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2773
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2773
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2774 2774
         return $related_model->sum($query_params, $field_to_sum);
2775 2775
     }
2776 2776
 
@@ -2823,7 +2823,7 @@  discard block
 block discarded – undo
2823 2823
                 $field_with_model_name = $field;
2824 2824
             }
2825 2825
         }
2826
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2826
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2827 2827
             throw new EE_Error(sprintf(
2828 2828
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2829 2829
                 $this->get_this_model_name()
@@ -2960,13 +2960,13 @@  discard block
 block discarded – undo
2960 2960
                 || $this->get_primary_key_field()
2961 2961
                    instanceof
2962 2962
                    EE_Primary_Key_String_Field)
2963
-            && isset($fields_n_values[ $this->primary_key_name() ])
2963
+            && isset($fields_n_values[$this->primary_key_name()])
2964 2964
         ) {
2965
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2965
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2966 2966
         }
2967 2967
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2968 2968
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2969
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2969
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2970 2970
         }
2971 2971
         // if there is nothing to base this search on, then we shouldn't find anything
2972 2972
         if (empty($query_params)) {
@@ -3044,15 +3044,15 @@  discard block
 block discarded – undo
3044 3044
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3045 3045
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3046 3046
             if ($prepared_value !== null) {
3047
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3047
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3048 3048
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3049 3049
             }
3050 3050
         }
3051 3051
         if ($table instanceof EE_Secondary_Table && $new_id) {
3052 3052
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3053 3053
             // so add the fk to the main table as a column
3054
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3055
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3054
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3055
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3056 3056
         }
3057 3057
         // insert the new entry
3058 3058
         $result = $this->_do_wpdb_query(
@@ -3069,7 +3069,7 @@  discard block
 block discarded – undo
3069 3069
             }
3070 3070
             // it's not an auto-increment primary key, so
3071 3071
             // it must have been supplied
3072
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3072
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3073 3073
         }
3074 3074
         // we can't return a  primary key because there is none. instead return
3075 3075
         // a unique string indicating this model
@@ -3094,14 +3094,14 @@  discard block
 block discarded – undo
3094 3094
         if (
3095 3095
             ! $field_obj->is_nullable()
3096 3096
             && (
3097
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3098
-                || $fields_n_values[ $field_obj->get_name() ] === null
3097
+                ! isset($fields_n_values[$field_obj->get_name()])
3098
+                || $fields_n_values[$field_obj->get_name()] === null
3099 3099
             )
3100 3100
         ) {
3101
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3101
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3102 3102
         }
3103
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3104
-            ? $fields_n_values[ $field_obj->get_name() ]
3103
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3104
+            ? $fields_n_values[$field_obj->get_name()]
3105 3105
             : null;
3106 3106
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3107 3107
     }
@@ -3202,7 +3202,7 @@  discard block
 block discarded – undo
3202 3202
      */
3203 3203
     public function get_table_obj_by_alias($table_alias = '')
3204 3204
     {
3205
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3205
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3206 3206
     }
3207 3207
 
3208 3208
 
@@ -3217,7 +3217,7 @@  discard block
 block discarded – undo
3217 3217
         $other_tables = array();
3218 3218
         foreach ($this->_tables as $table_alias => $table) {
3219 3219
             if ($table instanceof EE_Secondary_Table) {
3220
-                $other_tables[ $table_alias ] = $table;
3220
+                $other_tables[$table_alias] = $table;
3221 3221
             }
3222 3222
         }
3223 3223
         return $other_tables;
@@ -3233,7 +3233,7 @@  discard block
 block discarded – undo
3233 3233
      */
3234 3234
     public function _get_fields_for_table($table_alias)
3235 3235
     {
3236
-        return $this->_fields[ $table_alias ];
3236
+        return $this->_fields[$table_alias];
3237 3237
     }
3238 3238
 
3239 3239
 
@@ -3262,7 +3262,7 @@  discard block
 block discarded – undo
3262 3262
                     $query_info_carrier,
3263 3263
                     'group_by'
3264 3264
                 );
3265
-            } elseif (! empty($query_params['group_by'])) {
3265
+            } elseif ( ! empty($query_params['group_by'])) {
3266 3266
                 $this->_extract_related_model_info_from_query_param(
3267 3267
                     $query_params['group_by'],
3268 3268
                     $query_info_carrier,
@@ -3284,7 +3284,7 @@  discard block
 block discarded – undo
3284 3284
                     $query_info_carrier,
3285 3285
                     'order_by'
3286 3286
                 );
3287
-            } elseif (! empty($query_params['order_by'])) {
3287
+            } elseif ( ! empty($query_params['order_by'])) {
3288 3288
                 $this->_extract_related_model_info_from_query_param(
3289 3289
                     $query_params['order_by'],
3290 3290
                     $query_info_carrier,
@@ -3319,7 +3319,7 @@  discard block
 block discarded – undo
3319 3319
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3320 3320
         $query_param_type
3321 3321
     ) {
3322
-        if (! empty($sub_query_params)) {
3322
+        if ( ! empty($sub_query_params)) {
3323 3323
             $sub_query_params = (array) $sub_query_params;
3324 3324
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3325 3325
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3334,7 +3334,7 @@  discard block
 block discarded – undo
3334 3334
                 // of array('Registration.TXN_ID'=>23)
3335 3335
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3336 3336
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3337
-                    if (! is_array($possibly_array_of_params)) {
3337
+                    if ( ! is_array($possibly_array_of_params)) {
3338 3338
                         throw new EE_Error(sprintf(
3339 3339
                             __(
3340 3340
                                 "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'))",
@@ -3358,7 +3358,7 @@  discard block
 block discarded – undo
3358 3358
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3359 3359
                     // indicating that $possible_array_of_params[1] is actually a field name,
3360 3360
                     // from which we should extract query parameters!
3361
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3361
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3362 3362
                         throw new EE_Error(sprintf(__(
3363 3363
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3364 3364
                             "event_espresso"
@@ -3392,8 +3392,8 @@  discard block
 block discarded – undo
3392 3392
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3393 3393
         $query_param_type
3394 3394
     ) {
3395
-        if (! empty($sub_query_params)) {
3396
-            if (! is_array($sub_query_params)) {
3395
+        if ( ! empty($sub_query_params)) {
3396
+            if ( ! is_array($sub_query_params)) {
3397 3397
                 throw new EE_Error(sprintf(
3398 3398
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3399 3399
                     $sub_query_params
@@ -3427,7 +3427,7 @@  discard block
 block discarded – undo
3427 3427
      */
3428 3428
     public function _create_model_query_info_carrier($query_params)
3429 3429
     {
3430
-        if (! is_array($query_params)) {
3430
+        if ( ! is_array($query_params)) {
3431 3431
             EE_Error::doing_it_wrong(
3432 3432
                 'EEM_Base::_create_model_query_info_carrier',
3433 3433
                 sprintf(
@@ -3460,7 +3460,7 @@  discard block
 block discarded – undo
3460 3460
             // only include if related to a cpt where no password has been set
3461 3461
             $query_params[0]['OR*nopassword'] = array(
3462 3462
                 $where_param_key_for_password => '',
3463
-                $where_param_key_for_password . '*' => array('IS_NULL')
3463
+                $where_param_key_for_password.'*' => array('IS_NULL')
3464 3464
             );
3465 3465
         }
3466 3466
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3514,7 +3514,7 @@  discard block
 block discarded – undo
3514 3514
         // set limit
3515 3515
         if (array_key_exists('limit', $query_params)) {
3516 3516
             if (is_array($query_params['limit'])) {
3517
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3517
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3518 3518
                     $e = sprintf(
3519 3519
                         __(
3520 3520
                             "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)",
@@ -3522,12 +3522,12 @@  discard block
 block discarded – undo
3522 3522
                         ),
3523 3523
                         http_build_query($query_params['limit'])
3524 3524
                     );
3525
-                    throw new EE_Error($e . "|" . $e);
3525
+                    throw new EE_Error($e."|".$e);
3526 3526
                 }
3527 3527
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3528
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3529
-            } elseif (! empty($query_params['limit'])) {
3530
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3528
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3529
+            } elseif ( ! empty($query_params['limit'])) {
3530
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3531 3531
             }
3532 3532
         }
3533 3533
         // set order by
@@ -3559,10 +3559,10 @@  discard block
 block discarded – undo
3559 3559
                 $order_array = array();
3560 3560
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3561 3561
                     $order = $this->_extract_order($order);
3562
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3562
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3563 3563
                 }
3564
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3565
-            } elseif (! empty($query_params['order_by'])) {
3564
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3565
+            } elseif ( ! empty($query_params['order_by'])) {
3566 3566
                 $this->_extract_related_model_info_from_query_param(
3567 3567
                     $query_params['order_by'],
3568 3568
                     $query_object,
@@ -3573,7 +3573,7 @@  discard block
 block discarded – undo
3573 3573
                     ? $this->_extract_order($query_params['order'])
3574 3574
                     : 'DESC';
3575 3575
                 $query_object->set_order_by_sql(
3576
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3576
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3577 3577
                 );
3578 3578
             }
3579 3579
         }
@@ -3585,7 +3585,7 @@  discard block
 block discarded – undo
3585 3585
         ) {
3586 3586
             $pk_field = $this->get_primary_key_field();
3587 3587
             $order = $this->_extract_order($query_params['order']);
3588
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3588
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3589 3589
         }
3590 3590
         // set group by
3591 3591
         if (array_key_exists('group_by', $query_params)) {
@@ -3595,10 +3595,10 @@  discard block
 block discarded – undo
3595 3595
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3596 3596
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3597 3597
                 }
3598
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3599
-            } elseif (! empty($query_params['group_by'])) {
3598
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3599
+            } elseif ( ! empty($query_params['group_by'])) {
3600 3600
                 $query_object->set_group_by_sql(
3601
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3601
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3602 3602
                 );
3603 3603
             }
3604 3604
         }
@@ -3608,7 +3608,7 @@  discard block
 block discarded – undo
3608 3608
         }
3609 3609
         // now, just verify they didn't pass anything wack
3610 3610
         foreach ($query_params as $query_key => $query_value) {
3611
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3611
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3612 3612
                 throw new EE_Error(
3613 3613
                     sprintf(
3614 3614
                         __(
@@ -3716,7 +3716,7 @@  discard block
 block discarded – undo
3716 3716
         $where_query_params = array()
3717 3717
     ) {
3718 3718
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3719
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3719
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3720 3720
             throw new EE_Error(sprintf(
3721 3721
                 __(
3722 3722
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3848,19 +3848,19 @@  discard block
 block discarded – undo
3848 3848
     ) {
3849 3849
         $null_friendly_where_conditions = array();
3850 3850
         $none_overridden = true;
3851
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3851
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3852 3852
         foreach ($default_where_conditions as $key => $val) {
3853
-            if (isset($provided_where_conditions[ $key ])) {
3853
+            if (isset($provided_where_conditions[$key])) {
3854 3854
                 $none_overridden = false;
3855 3855
             } else {
3856
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3856
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3857 3857
             }
3858 3858
         }
3859 3859
         if ($none_overridden && $default_where_conditions) {
3860 3860
             if ($model->has_primary_key_field()) {
3861
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3861
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3862 3862
                                                                                 . "."
3863
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3863
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3864 3864
             }/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
@@ -3965,7 +3965,7 @@  discard block
 block discarded – undo
3965 3965
             foreach ($tables as $table_obj) {
3966 3966
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3967 3967
                                        . $table_obj->get_fully_qualified_pk_column();
3968
-                if (! in_array($qualified_pk_column, $selects)) {
3968
+                if ( ! in_array($qualified_pk_column, $selects)) {
3969 3969
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3970 3970
                 }
3971 3971
             }
@@ -4117,9 +4117,9 @@  discard block
 block discarded – undo
4117 4117
         $query_parameter_type
4118 4118
     ) {
4119 4119
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4120
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4120
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4121 4121
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4122
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4122
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4123 4123
                 if ($possible_join_string === '') {
4124 4124
                     // nothing left to $query_param
4125 4125
                     // we should actually end in a field name, not a model like this!
@@ -4250,7 +4250,7 @@  discard block
 block discarded – undo
4250 4250
     {
4251 4251
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4252 4252
         if ($SQL) {
4253
-            return " WHERE " . $SQL;
4253
+            return " WHERE ".$SQL;
4254 4254
         }
4255 4255
         return '';
4256 4256
     }
@@ -4269,7 +4269,7 @@  discard block
 block discarded – undo
4269 4269
     {
4270 4270
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4271 4271
         if ($SQL) {
4272
-            return " HAVING " . $SQL;
4272
+            return " HAVING ".$SQL;
4273 4273
         }
4274 4274
         return '';
4275 4275
     }
@@ -4288,7 +4288,7 @@  discard block
 block discarded – undo
4288 4288
     {
4289 4289
         $where_clauses = array();
4290 4290
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4291
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4291
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4292 4292
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4293 4293
                 switch ($query_param) {
4294 4294
                     case 'not':
@@ -4322,7 +4322,7 @@  discard block
 block discarded – undo
4322 4322
             } else {
4323 4323
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4324 4324
                 // if it's not a normal field, maybe it's a custom selection?
4325
-                if (! $field_obj) {
4325
+                if ( ! $field_obj) {
4326 4326
                     if ($this->_custom_selections instanceof CustomSelects) {
4327 4327
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4328 4328
                     } else {
@@ -4333,7 +4333,7 @@  discard block
 block discarded – undo
4333 4333
                     }
4334 4334
                 }
4335 4335
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4336
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4336
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4337 4337
             }
4338 4338
         }
4339 4339
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4356,7 +4356,7 @@  discard block
 block discarded – undo
4356 4356
                 $field->get_model_name(),
4357 4357
                 $query_param
4358 4358
             );
4359
-            return $table_alias_prefix . $field->get_qualified_column();
4359
+            return $table_alias_prefix.$field->get_qualified_column();
4360 4360
         }
4361 4361
         if (
4362 4362
             $this->_custom_selections instanceof CustomSelects
@@ -4416,7 +4416,7 @@  discard block
 block discarded – undo
4416 4416
     {
4417 4417
         if (is_array($op_and_value)) {
4418 4418
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4419
-            if (! $operator) {
4419
+            if ( ! $operator) {
4420 4420
                 $php_array_like_string = array();
4421 4421
                 foreach ($op_and_value as $key => $value) {
4422 4422
                     $php_array_like_string[] = "$key=>$value";
@@ -4438,14 +4438,14 @@  discard block
 block discarded – undo
4438 4438
         }
4439 4439
         // check to see if the value is actually another field
4440 4440
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4441
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4441
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4442 4442
         }
4443 4443
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4444 4444
             // in this case, the value should be an array, or at least a comma-separated list
4445 4445
             // it will need to handle a little differently
4446 4446
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4447 4447
             // note: $cleaned_value has already been run through $wpdb->prepare()
4448
-            return $operator . SP . $cleaned_value;
4448
+            return $operator.SP.$cleaned_value;
4449 4449
         }
4450 4450
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4451 4451
             // the value should be an array with count of two.
@@ -4461,7 +4461,7 @@  discard block
 block discarded – undo
4461 4461
                 );
4462 4462
             }
4463 4463
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4464
-            return $operator . SP . $cleaned_value;
4464
+            return $operator.SP.$cleaned_value;
4465 4465
         }
4466 4466
         if (in_array($operator, $this->valid_null_style_operators())) {
4467 4467
             if ($value !== null) {
@@ -4481,10 +4481,10 @@  discard block
 block discarded – undo
4481 4481
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4482 4482
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4483 4483
             // remove other junk. So just treat it as a string.
4484
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4484
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4485 4485
         }
4486
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4486
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4487
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4488 4488
         }
4489 4489
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4490 4490
             throw new EE_Error(
@@ -4498,7 +4498,7 @@  discard block
 block discarded – undo
4498 4498
                 )
4499 4499
             );
4500 4500
         }
4501
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4501
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4502 4502
             throw new EE_Error(
4503 4503
                 sprintf(
4504 4504
                     __(
@@ -4538,7 +4538,7 @@  discard block
 block discarded – undo
4538 4538
         foreach ($values as $value) {
4539 4539
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4540 4540
         }
4541
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4541
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4542 4542
     }
4543 4543
 
4544 4544
 
@@ -4579,7 +4579,7 @@  discard block
 block discarded – undo
4579 4579
                                 . $main_table->get_table_name()
4580 4580
                                 . " WHERE FALSE";
4581 4581
         }
4582
-        return "(" . implode(",", $cleaned_values) . ")";
4582
+        return "(".implode(",", $cleaned_values).")";
4583 4583
     }
4584 4584
 
4585 4585
 
@@ -4600,7 +4600,7 @@  discard block
 block discarded – undo
4600 4600
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4601 4601
             );
4602 4602
         } //$field_obj should really just be a data type
4603
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4603
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4604 4604
             throw new EE_Error(
4605 4605
                 sprintf(
4606 4606
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4633,14 +4633,14 @@  discard block
 block discarded – undo
4633 4633
             ), $query_param_name));
4634 4634
         }
4635 4635
         $number_of_parts = count($query_param_parts);
4636
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4636
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4637 4637
         if ($number_of_parts === 1) {
4638 4638
             $field_name = $last_query_param_part;
4639 4639
             $model_obj = $this;
4640 4640
         } else {// $number_of_parts >= 2
4641 4641
             // the last part is the column name, and there are only 2parts. therefore...
4642 4642
             $field_name = $last_query_param_part;
4643
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4643
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4644 4644
         }
4645 4645
         try {
4646 4646
             return $model_obj->field_settings_for($field_name);
@@ -4662,7 +4662,7 @@  discard block
 block discarded – undo
4662 4662
     public function _get_qualified_column_for_field($field_name)
4663 4663
     {
4664 4664
         $all_fields = $this->field_settings();
4665
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4665
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4666 4666
         if ($field) {
4667 4667
             return $field->get_qualified_column();
4668 4668
         }
@@ -4733,10 +4733,10 @@  discard block
 block discarded – undo
4733 4733
      */
4734 4734
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4735 4735
     {
4736
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4736
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4737 4737
         $qualified_columns = array();
4738 4738
         foreach ($this->field_settings() as $field_name => $field) {
4739
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4739
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4740 4740
         }
4741 4741
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4742 4742
     }
@@ -4760,11 +4760,11 @@  discard block
 block discarded – undo
4760 4760
             if ($table_obj instanceof EE_Primary_Table) {
4761 4761
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4762 4762
                     ? $table_obj->get_select_join_limit($limit)
4763
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4763
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4764 4764
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4765 4765
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4766 4766
                     ? $table_obj->get_select_join_limit_join($limit)
4767
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4767
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4768 4768
             }
4769 4769
         }
4770 4770
         return $SQL;
@@ -4836,7 +4836,7 @@  discard block
 block discarded – undo
4836 4836
         foreach ($this->field_settings() as $field_obj) {
4837 4837
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4838 4838
             /** @var $field_obj EE_Model_Field_Base */
4839
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4839
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4840 4840
         }
4841 4841
         return $data_types;
4842 4842
     }
@@ -4852,14 +4852,14 @@  discard block
 block discarded – undo
4852 4852
      */
4853 4853
     public function get_related_model_obj($model_name)
4854 4854
     {
4855
-        $model_classname = "EEM_" . $model_name;
4856
-        if (! class_exists($model_classname)) {
4855
+        $model_classname = "EEM_".$model_name;
4856
+        if ( ! class_exists($model_classname)) {
4857 4857
             throw new EE_Error(sprintf(__(
4858 4858
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4859 4859
                 'event_espresso'
4860 4860
             ), $model_name, $model_classname));
4861 4861
         }
4862
-        return call_user_func($model_classname . "::instance");
4862
+        return call_user_func($model_classname."::instance");
4863 4863
     }
4864 4864
 
4865 4865
 
@@ -4888,7 +4888,7 @@  discard block
 block discarded – undo
4888 4888
         $belongs_to_relations = array();
4889 4889
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4890 4890
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4891
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4891
+                $belongs_to_relations[$model_name] = $relation_obj;
4892 4892
             }
4893 4893
         }
4894 4894
         return $belongs_to_relations;
@@ -4906,7 +4906,7 @@  discard block
 block discarded – undo
4906 4906
     public function related_settings_for($relation_name)
4907 4907
     {
4908 4908
         $relatedModels = $this->relation_settings();
4909
-        if (! array_key_exists($relation_name, $relatedModels)) {
4909
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4910 4910
             throw new EE_Error(
4911 4911
                 sprintf(
4912 4912
                     __(
@@ -4919,7 +4919,7 @@  discard block
 block discarded – undo
4919 4919
                 )
4920 4920
             );
4921 4921
         }
4922
-        return $relatedModels[ $relation_name ];
4922
+        return $relatedModels[$relation_name];
4923 4923
     }
4924 4924
 
4925 4925
 
@@ -4936,14 +4936,14 @@  discard block
 block discarded – undo
4936 4936
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4937 4937
     {
4938 4938
         $fieldSettings = $this->field_settings($include_db_only_fields);
4939
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4939
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4940 4940
             throw new EE_Error(sprintf(
4941 4941
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4942 4942
                 $fieldName,
4943 4943
                 get_class($this)
4944 4944
             ));
4945 4945
         }
4946
-        return $fieldSettings[ $fieldName ];
4946
+        return $fieldSettings[$fieldName];
4947 4947
     }
4948 4948
 
4949 4949
 
@@ -4957,7 +4957,7 @@  discard block
 block discarded – undo
4957 4957
     public function has_field($fieldName)
4958 4958
     {
4959 4959
         $fieldSettings = $this->field_settings(true);
4960
-        if (isset($fieldSettings[ $fieldName ])) {
4960
+        if (isset($fieldSettings[$fieldName])) {
4961 4961
             return true;
4962 4962
         }
4963 4963
         return false;
@@ -4974,7 +4974,7 @@  discard block
 block discarded – undo
4974 4974
     public function has_relation($relation_name)
4975 4975
     {
4976 4976
         $relations = $this->relation_settings();
4977
-        if (isset($relations[ $relation_name ])) {
4977
+        if (isset($relations[$relation_name])) {
4978 4978
             return true;
4979 4979
         }
4980 4980
         return false;
@@ -5012,7 +5012,7 @@  discard block
 block discarded – undo
5012 5012
                     break;
5013 5013
                 }
5014 5014
             }
5015
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5015
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5016 5016
                 throw new EE_Error(sprintf(
5017 5017
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
5018 5018
                     get_class($this)
@@ -5073,24 +5073,24 @@  discard block
 block discarded – undo
5073 5073
      */
5074 5074
     public function get_foreign_key_to($model_name)
5075 5075
     {
5076
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5076
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5077 5077
             foreach ($this->field_settings() as $field) {
5078 5078
                 if (
5079 5079
                     $field instanceof EE_Foreign_Key_Field_Base
5080 5080
                     && in_array($model_name, $field->get_model_names_pointed_to())
5081 5081
                 ) {
5082
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5082
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5083 5083
                     break;
5084 5084
                 }
5085 5085
             }
5086
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5086
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5087 5087
                 throw new EE_Error(sprintf(__(
5088 5088
                     "There is no foreign key field pointing to model %s on model %s",
5089 5089
                     'event_espresso'
5090 5090
                 ), $model_name, get_class($this)));
5091 5091
             }
5092 5092
         }
5093
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5093
+        return $this->_cache_foreign_key_to_fields[$model_name];
5094 5094
     }
5095 5095
 
5096 5096
 
@@ -5106,7 +5106,7 @@  discard block
 block discarded – undo
5106 5106
     public function get_table_for_alias($table_alias)
5107 5107
     {
5108 5108
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5109
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5109
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5110 5110
     }
5111 5111
 
5112 5112
 
@@ -5125,7 +5125,7 @@  discard block
 block discarded – undo
5125 5125
                 $this->_cached_fields = array();
5126 5126
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5127 5127
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5128
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5128
+                        $this->_cached_fields[$field_name] = $field_obj;
5129 5129
                     }
5130 5130
                 }
5131 5131
             }
@@ -5136,8 +5136,8 @@  discard block
 block discarded – undo
5136 5136
             foreach ($this->_fields as $fields_corresponding_to_table) {
5137 5137
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5138 5138
                     /** @var $field_obj EE_Model_Field_Base */
5139
-                    if (! $field_obj->is_db_only_field()) {
5140
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5139
+                    if ( ! $field_obj->is_db_only_field()) {
5140
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5141 5141
                     }
5142 5142
                 }
5143 5143
             }
@@ -5178,12 +5178,12 @@  discard block
 block discarded – undo
5178 5178
                     $primary_key_field->get_qualified_column(),
5179 5179
                     $primary_key_field->get_table_column()
5180 5180
                 );
5181
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5181
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5182 5182
                     continue;
5183 5183
                 }
5184 5184
             }
5185 5185
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5186
-            if (! $classInstance) {
5186
+            if ( ! $classInstance) {
5187 5187
                 throw new EE_Error(
5188 5188
                     sprintf(
5189 5189
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5196,7 +5196,7 @@  discard block
 block discarded – undo
5196 5196
             $classInstance->set_timezone($this->_timezone);
5197 5197
             // make sure if there is any timezone setting present that we set the timezone for the object
5198 5198
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5199
-            $array_of_objects[ $key ] = $classInstance;
5199
+            $array_of_objects[$key] = $classInstance;
5200 5200
             // also, for all the relations of type BelongsTo, see if we can cache
5201 5201
             // those related models
5202 5202
             // (we could do this for other relations too, but if there are conditions
@@ -5240,9 +5240,9 @@  discard block
 block discarded – undo
5240 5240
         $results = array();
5241 5241
         if ($this->_custom_selections instanceof CustomSelects) {
5242 5242
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5243
-                if (isset($db_results_row[ $alias ])) {
5244
-                    $results[ $alias ] = $this->convertValueToDataType(
5245
-                        $db_results_row[ $alias ],
5243
+                if (isset($db_results_row[$alias])) {
5244
+                    $results[$alias] = $this->convertValueToDataType(
5245
+                        $db_results_row[$alias],
5246 5246
                         $this->_custom_selections->getDataTypeForAlias($alias)
5247 5247
                     );
5248 5248
                 }
@@ -5284,7 +5284,7 @@  discard block
 block discarded – undo
5284 5284
         $this_model_fields_and_values = array();
5285 5285
         // setup the row using default values;
5286 5286
         foreach ($this->field_settings() as $field_name => $field_obj) {
5287
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5287
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5288 5288
         }
5289 5289
         $className = $this->_get_class_name();
5290 5290
         $classInstance = EE_Registry::instance()
@@ -5302,20 +5302,20 @@  discard block
 block discarded – undo
5302 5302
      */
5303 5303
     public function instantiate_class_from_array_or_object($cols_n_values)
5304 5304
     {
5305
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5305
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5306 5306
             $cols_n_values = get_object_vars($cols_n_values);
5307 5307
         }
5308 5308
         $primary_key = null;
5309 5309
         // make sure the array only has keys that are fields/columns on this model
5310 5310
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5311
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5312
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5311
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5312
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5313 5313
         }
5314 5314
         $className = $this->_get_class_name();
5315 5315
         // check we actually found results that we can use to build our model object
5316 5316
         // if not, return null
5317 5317
         if ($this->has_primary_key_field()) {
5318
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5318
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5319 5319
                 return null;
5320 5320
             }
5321 5321
         } elseif ($this->unique_indexes()) {
@@ -5327,7 +5327,7 @@  discard block
 block discarded – undo
5327 5327
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5328 5328
         if ($primary_key) {
5329 5329
             $classInstance = $this->get_from_entity_map($primary_key);
5330
-            if (! $classInstance) {
5330
+            if ( ! $classInstance) {
5331 5331
                 $classInstance = EE_Registry::instance()
5332 5332
                                             ->load_class(
5333 5333
                                                 $className,
@@ -5360,8 +5360,8 @@  discard block
 block discarded – undo
5360 5360
      */
5361 5361
     public function get_from_entity_map($id)
5362 5362
     {
5363
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5364
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5363
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5364
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5365 5365
     }
5366 5366
 
5367 5367
 
@@ -5384,7 +5384,7 @@  discard block
 block discarded – undo
5384 5384
     public function add_to_entity_map(EE_Base_Class $object)
5385 5385
     {
5386 5386
         $className = $this->_get_class_name();
5387
-        if (! $object instanceof $className) {
5387
+        if ( ! $object instanceof $className) {
5388 5388
             throw new EE_Error(sprintf(
5389 5389
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5390 5390
                 is_object($object) ? get_class($object) : $object,
@@ -5392,7 +5392,7 @@  discard block
 block discarded – undo
5392 5392
             ));
5393 5393
         }
5394 5394
         /** @var $object EE_Base_Class */
5395
-        if (! $object->ID()) {
5395
+        if ( ! $object->ID()) {
5396 5396
             throw new EE_Error(sprintf(__(
5397 5397
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5398 5398
                 "event_espresso"
@@ -5403,7 +5403,7 @@  discard block
 block discarded – undo
5403 5403
         if ($classInstance) {
5404 5404
             return $classInstance;
5405 5405
         }
5406
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5406
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5407 5407
         return $object;
5408 5408
     }
5409 5409
 
@@ -5419,11 +5419,11 @@  discard block
 block discarded – undo
5419 5419
     public function clear_entity_map($id = null)
5420 5420
     {
5421 5421
         if (empty($id)) {
5422
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5422
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5423 5423
             return true;
5424 5424
         }
5425
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5426
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5425
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5426
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5427 5427
             return true;
5428 5428
         }
5429 5429
         return false;
@@ -5466,17 +5466,17 @@  discard block
 block discarded – undo
5466 5466
             // there is a primary key on this table and its not set. Use defaults for all its columns
5467 5467
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5468 5468
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5469
-                    if (! $field_obj->is_db_only_field()) {
5469
+                    if ( ! $field_obj->is_db_only_field()) {
5470 5470
                         // prepare field as if its coming from db
5471 5471
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5472
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5472
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5473 5473
                     }
5474 5474
                 }
5475 5475
             } else {
5476 5476
                 // the table's rows existed. Use their values
5477 5477
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5478
-                    if (! $field_obj->is_db_only_field()) {
5479
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5478
+                    if ( ! $field_obj->is_db_only_field()) {
5479
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5480 5480
                             $cols_n_values,
5481 5481
                             $field_obj->get_qualified_column(),
5482 5482
                             $field_obj->get_table_column()
@@ -5503,17 +5503,17 @@  discard block
 block discarded – undo
5503 5503
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5504 5504
         // does the field on the model relate to this column retrieved from the db?
5505 5505
         // or is it a db-only field? (not relating to the model)
5506
-        if (isset($cols_n_values[ $qualified_column ])) {
5507
-            $value = $cols_n_values[ $qualified_column ];
5508
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5509
-            $value = $cols_n_values[ $regular_column ];
5510
-        } elseif (! empty($this->foreign_key_aliases)) {
5506
+        if (isset($cols_n_values[$qualified_column])) {
5507
+            $value = $cols_n_values[$qualified_column];
5508
+        } elseif (isset($cols_n_values[$regular_column])) {
5509
+            $value = $cols_n_values[$regular_column];
5510
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5511 5511
             // no PK?  ok check if there is a foreign key alias set for this table
5512 5512
             // then check if that alias exists in the incoming data
5513 5513
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5514 5514
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5515
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5516
-                    $value = $cols_n_values[ $FK_alias ];
5515
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5516
+                    $value = $cols_n_values[$FK_alias];
5517 5517
                     [$pk_class] = explode('.', $PK_column);
5518 5518
                     $pk_model_name = "EEM_{$pk_class}";
5519 5519
                     /** @var EEM_Base $pk_model */
@@ -5557,7 +5557,7 @@  discard block
 block discarded – undo
5557 5557
                     $obj_in_map->clear_cache($relation_name, null, true);
5558 5558
                 }
5559 5559
             }
5560
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5560
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5561 5561
             return $obj_in_map;
5562 5562
         }
5563 5563
         return $this->get_one_by_ID($id);
@@ -5610,7 +5610,7 @@  discard block
 block discarded – undo
5610 5610
      */
5611 5611
     private function _get_class_name()
5612 5612
     {
5613
-        return "EE_" . $this->get_this_model_name();
5613
+        return "EE_".$this->get_this_model_name();
5614 5614
     }
5615 5615
 
5616 5616
 
@@ -5658,7 +5658,7 @@  discard block
 block discarded – undo
5658 5658
     {
5659 5659
         $className = get_class($this);
5660 5660
         $tagName = "FHEE__{$className}__{$methodName}";
5661
-        if (! has_filter($tagName)) {
5661
+        if ( ! has_filter($tagName)) {
5662 5662
             throw new EE_Error(
5663 5663
                 sprintf(
5664 5664
                     __(
@@ -5831,7 +5831,7 @@  discard block
 block discarded – undo
5831 5831
         $unique_indexes = array();
5832 5832
         foreach ($this->_indexes as $name => $index) {
5833 5833
             if ($index instanceof EE_Unique_Index) {
5834
-                $unique_indexes [ $name ] = $index;
5834
+                $unique_indexes [$name] = $index;
5835 5835
             }
5836 5836
         }
5837 5837
         return $unique_indexes;
@@ -5898,7 +5898,7 @@  discard block
 block discarded – undo
5898 5898
         $key_vals_in_combined_pk = array();
5899 5899
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5900 5900
         foreach ($key_fields as $key_field_name => $field_obj) {
5901
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5901
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5902 5902
                 return null;
5903 5903
             }
5904 5904
         }
@@ -5919,7 +5919,7 @@  discard block
 block discarded – undo
5919 5919
     {
5920 5920
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5921 5921
         foreach ($keys_it_should_have as $key) {
5922
-            if (! isset($key_vals[ $key ])) {
5922
+            if ( ! isset($key_vals[$key])) {
5923 5923
                 return false;
5924 5924
             }
5925 5925
         }
@@ -5952,8 +5952,8 @@  discard block
 block discarded – undo
5952 5952
         }
5953 5953
         // even copies obviously won't have the same ID, so remove the primary key
5954 5954
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
-            unset($attributes_array[ $this->primary_key_name() ]);
5955
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5956
+            unset($attributes_array[$this->primary_key_name()]);
5957 5957
         }
5958 5958
         if (isset($query_params[0])) {
5959 5959
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5975,7 +5975,7 @@  discard block
 block discarded – undo
5975 5975
      */
5976 5976
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5977 5977
     {
5978
-        if (! is_array($query_params)) {
5978
+        if ( ! is_array($query_params)) {
5979 5979
             EE_Error::doing_it_wrong(
5980 5980
                 'EEM_Base::get_one_copy',
5981 5981
                 sprintf(
@@ -6025,7 +6025,7 @@  discard block
 block discarded – undo
6025 6025
      */
6026 6026
     private function _prepare_operator_for_sql($operator_supplied)
6027 6027
     {
6028
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6028
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
6029 6029
             : null;
6030 6030
         if ($sql_operator) {
6031 6031
             return $sql_operator;
@@ -6116,7 +6116,7 @@  discard block
 block discarded – undo
6116 6116
         $objs = $this->get_all($query_params);
6117 6117
         $names = array();
6118 6118
         foreach ($objs as $obj) {
6119
-            $names[ $obj->ID() ] = $obj->name();
6119
+            $names[$obj->ID()] = $obj->name();
6120 6120
         }
6121 6121
         return $names;
6122 6122
     }
@@ -6137,7 +6137,7 @@  discard block
 block discarded – undo
6137 6137
      */
6138 6138
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6139 6139
     {
6140
-        if (! $this->has_primary_key_field()) {
6140
+        if ( ! $this->has_primary_key_field()) {
6141 6141
             if (WP_DEBUG) {
6142 6142
                 EE_Error::add_error(
6143 6143
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6150,7 +6150,7 @@  discard block
 block discarded – undo
6150 6150
         $IDs = array();
6151 6151
         foreach ($model_objects as $model_object) {
6152 6152
             $id = $model_object->ID();
6153
-            if (! $id) {
6153
+            if ( ! $id) {
6154 6154
                 if ($filter_out_empty_ids) {
6155 6155
                     continue;
6156 6156
                 }
@@ -6201,22 +6201,22 @@  discard block
 block discarded – undo
6201 6201
         EEM_Base::verify_is_valid_cap_context($context);
6202 6202
         // check if we ought to run the restriction generator first
6203 6203
         if (
6204
-            isset($this->_cap_restriction_generators[ $context ])
6205
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6206
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6204
+            isset($this->_cap_restriction_generators[$context])
6205
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6206
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6207 6207
         ) {
6208
-            $this->_cap_restrictions[ $context ] = array_merge(
6209
-                $this->_cap_restrictions[ $context ],
6210
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6208
+            $this->_cap_restrictions[$context] = array_merge(
6209
+                $this->_cap_restrictions[$context],
6210
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6211 6211
             );
6212 6212
         }
6213 6213
         // and make sure we've finalized the construction of each restriction
6214
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6214
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6215 6215
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6216 6216
                 $where_conditions_obj->_finalize_construct($this);
6217 6217
             }
6218 6218
         }
6219
-        return $this->_cap_restrictions[ $context ];
6219
+        return $this->_cap_restrictions[$context];
6220 6220
     }
6221 6221
 
6222 6222
 
@@ -6248,9 +6248,9 @@  discard block
 block discarded – undo
6248 6248
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6249 6249
             if (
6250 6250
                 ! EE_Capabilities::instance()
6251
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6251
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6252 6252
             ) {
6253
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6253
+                $missing_caps[$cap] = $restriction_if_no_cap;
6254 6254
             }
6255 6255
         }
6256 6256
         return $missing_caps;
@@ -6285,8 +6285,8 @@  discard block
 block discarded – undo
6285 6285
     public function cap_action_for_context($context)
6286 6286
     {
6287 6287
         $mapping = $this->cap_contexts_to_cap_action_map();
6288
-        if (isset($mapping[ $context ])) {
6289
-            return $mapping[ $context ];
6288
+        if (isset($mapping[$context])) {
6289
+            return $mapping[$context];
6290 6290
         }
6291 6291
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6292 6292
             return $action;
@@ -6404,7 +6404,7 @@  discard block
 block discarded – undo
6404 6404
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6405 6405
             if (
6406 6406
                 $query_param_key === $logic_query_param_key
6407
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6407
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6408 6408
             ) {
6409 6409
                 return true;
6410 6410
             }
@@ -6457,7 +6457,7 @@  discard block
 block discarded – undo
6457 6457
         if ($password_field instanceof EE_Password_Field) {
6458 6458
             $field_names = $password_field->protectedFields();
6459 6459
             foreach ($field_names as $field_name) {
6460
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6460
+                $fields[$field_name] = $this->field_settings_for($field_name);
6461 6461
             }
6462 6462
         }
6463 6463
         return $fields;
@@ -6482,7 +6482,7 @@  discard block
 block discarded – undo
6482 6482
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6483 6483
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6484 6484
         }
6485
-        if (!is_array($model_obj_or_fields_n_values)) {
6485
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6486 6486
             throw new UnexpectedEntityException(
6487 6487
                 $model_obj_or_fields_n_values,
6488 6488
                 'EE_Base_Class',
@@ -6557,7 +6557,7 @@  discard block
 block discarded – undo
6557 6557
                 )
6558 6558
             );
6559 6559
         }
6560
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6560
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6561 6561
     }
6562 6562
 
6563 6563
     /**
Please login to merge, or discard this patch.
core/services/form/meta/inputs/Button.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -4,49 +4,49 @@
 block discarded – undo
4 4
 
5 5
 class Button
6 6
 {
7
-    /**
8
-     * indicates that the HTML input type is 'button'
9
-     */
10
-    public const TYPE_BUTTON = 'button';
11
-
12
-    /**
13
-     * indicates that the HTML input type is 'reset'
14
-     */
15
-    public const TYPE_BUTTON_RESET = 'reset';
16
-
17
-    /**
18
-     * indicates that the HTML input type is 'submit'
19
-     */
20
-    public const TYPE_BUTTON_SUBMIT = 'submit';
21
-
22
-
23
-    /**
24
-     * @var array
25
-     */
26
-    private $valid_type_options;
27
-
28
-
29
-    public function __construct()
30
-    {
31
-        $this->valid_type_options = apply_filters(
32
-            'FHEE__EventEspresso_core_services_form_meta_inputs_Button__valid_type_options',
33
-            [
34
-                Button::TYPE_BUTTON        => esc_html__('Button', 'event_espresso'),
35
-                Button::TYPE_BUTTON_RESET  => esc_html__('Reset Button', 'event_espresso'),
36
-                Button::TYPE_BUTTON_SUBMIT => esc_html__('Submit Button', 'event_espresso'),
37
-            ]
38
-        );
39
-    }
40
-
41
-
42
-    /**
43
-     * @param bool $constants_only
44
-     * @return array
45
-     */
46
-    public function validTypeOptions(bool $constants_only = false): array
47
-    {
48
-        return $constants_only
49
-            ? array_keys($this->valid_type_options)
50
-            : $this->valid_type_options;
51
-    }
7
+	/**
8
+	 * indicates that the HTML input type is 'button'
9
+	 */
10
+	public const TYPE_BUTTON = 'button';
11
+
12
+	/**
13
+	 * indicates that the HTML input type is 'reset'
14
+	 */
15
+	public const TYPE_BUTTON_RESET = 'reset';
16
+
17
+	/**
18
+	 * indicates that the HTML input type is 'submit'
19
+	 */
20
+	public const TYPE_BUTTON_SUBMIT = 'submit';
21
+
22
+
23
+	/**
24
+	 * @var array
25
+	 */
26
+	private $valid_type_options;
27
+
28
+
29
+	public function __construct()
30
+	{
31
+		$this->valid_type_options = apply_filters(
32
+			'FHEE__EventEspresso_core_services_form_meta_inputs_Button__valid_type_options',
33
+			[
34
+				Button::TYPE_BUTTON        => esc_html__('Button', 'event_espresso'),
35
+				Button::TYPE_BUTTON_RESET  => esc_html__('Reset Button', 'event_espresso'),
36
+				Button::TYPE_BUTTON_SUBMIT => esc_html__('Submit Button', 'event_espresso'),
37
+			]
38
+		);
39
+	}
40
+
41
+
42
+	/**
43
+	 * @param bool $constants_only
44
+	 * @return array
45
+	 */
46
+	public function validTypeOptions(bool $constants_only = false): array
47
+	{
48
+		return $constants_only
49
+			? array_keys($this->valid_type_options)
50
+			: $this->valid_type_options;
51
+	}
52 52
 }
Please login to merge, or discard this patch.
core/services/form/meta/inputs/Input.php 1 patch
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -5,78 +5,78 @@
 block discarded – undo
5 5
 class Input
6 6
 {
7 7
 
8
-    /**
9
-     * indicates that the HTML input type is 'checkbox'
10
-     */
11
-    public const TYPE_CHECKBOX = 'checkbox';
8
+	/**
9
+	 * indicates that the HTML input type is 'checkbox'
10
+	 */
11
+	public const TYPE_CHECKBOX = 'checkbox';
12 12
 
13
-    /**
14
-     * indicates that the HTML input type is 'color'
15
-     */
16
-    public const TYPE_COLOR = 'color';
13
+	/**
14
+	 * indicates that the HTML input type is 'color'
15
+	 */
16
+	public const TYPE_COLOR = 'color';
17 17
 
18
-    /**
19
-     * indicates that the HTML input type is 'file'
20
-     */
21
-    public const TYPE_FILE = 'file';
18
+	/**
19
+	 * indicates that the HTML input type is 'file'
20
+	 */
21
+	public const TYPE_FILE = 'file';
22 22
 
23
-    /**
24
-     * indicates that the HTML input type is 'hidden'
25
-     */
26
-    public const TYPE_HIDDEN = 'hidden';
23
+	/**
24
+	 * indicates that the HTML input type is 'hidden'
25
+	 */
26
+	public const TYPE_HIDDEN = 'hidden';
27 27
 
28
-    /**
29
-     * indicates that the HTML input type is 'image'
30
-     */
31
-    public const TYPE_IMAGE = 'image';
28
+	/**
29
+	 * indicates that the HTML input type is 'image'
30
+	 */
31
+	public const TYPE_IMAGE = 'image';
32 32
 
33
-    /**
34
-     * indicates that the HTML input type is 'password'
35
-     */
36
-    public const TYPE_PASSWORD = 'password';
33
+	/**
34
+	 * indicates that the HTML input type is 'password'
35
+	 */
36
+	public const TYPE_PASSWORD = 'password';
37 37
 
38
-    /**
39
-     * indicates that the HTML input type is 'radio'
40
-     */
41
-    public const TYPE_RADIO = 'radio';
38
+	/**
39
+	 * indicates that the HTML input type is 'radio'
40
+	 */
41
+	public const TYPE_RADIO = 'radio';
42 42
 
43
-    /**
44
-     * indicates that the HTML input type is 'url'
45
-     */
46
-    public const TYPE_URL = 'url';
43
+	/**
44
+	 * indicates that the HTML input type is 'url'
45
+	 */
46
+	public const TYPE_URL = 'url';
47 47
 
48
-    /**
49
-     * @var array
50
-     */
51
-    private $valid_type_options;
48
+	/**
49
+	 * @var array
50
+	 */
51
+	private $valid_type_options;
52 52
 
53 53
 
54
-    public function __construct()
55
-    {
56
-        $this->valid_type_options = apply_filters(
57
-            'FHEE__EventEspresso_core_services_form_meta_inputs_Input__valid_type_options',
58
-            [
59
-                Input::TYPE_CHECKBOX => esc_html__('Checkbox', 'event_espresso'),
60
-                Input::TYPE_COLOR    => esc_html__('Color Picker', 'event_espresso'),
61
-                Input::TYPE_FILE     => esc_html__('File Upload', 'event_espresso'),
62
-                Input::TYPE_HIDDEN   => esc_html__('Hidden', 'event_espresso'),
63
-                Input::TYPE_IMAGE    => esc_html__('Image Upload', 'event_espresso'),
64
-                Input::TYPE_PASSWORD => esc_html__('Password', 'event_espresso'),
65
-                Input::TYPE_RADIO    => esc_html__('Radio Button', 'event_espresso'),
66
-                Input::TYPE_URL      => esc_html__('URL', 'event_espresso'),
67
-            ]
68
-        );
69
-    }
54
+	public function __construct()
55
+	{
56
+		$this->valid_type_options = apply_filters(
57
+			'FHEE__EventEspresso_core_services_form_meta_inputs_Input__valid_type_options',
58
+			[
59
+				Input::TYPE_CHECKBOX => esc_html__('Checkbox', 'event_espresso'),
60
+				Input::TYPE_COLOR    => esc_html__('Color Picker', 'event_espresso'),
61
+				Input::TYPE_FILE     => esc_html__('File Upload', 'event_espresso'),
62
+				Input::TYPE_HIDDEN   => esc_html__('Hidden', 'event_espresso'),
63
+				Input::TYPE_IMAGE    => esc_html__('Image Upload', 'event_espresso'),
64
+				Input::TYPE_PASSWORD => esc_html__('Password', 'event_espresso'),
65
+				Input::TYPE_RADIO    => esc_html__('Radio Button', 'event_espresso'),
66
+				Input::TYPE_URL      => esc_html__('URL', 'event_espresso'),
67
+			]
68
+		);
69
+	}
70 70
 
71 71
 
72
-    /**
73
-     * @param bool $constants_only
74
-     * @return array
75
-     */
76
-    public function validTypeOptions(bool $constants_only = false): array
77
-    {
78
-        return $constants_only
79
-            ? array_keys($this->valid_type_options)
80
-            : $this->valid_type_options;
81
-    }
72
+	/**
73
+	 * @param bool $constants_only
74
+	 * @return array
75
+	 */
76
+	public function validTypeOptions(bool $constants_only = false): array
77
+	{
78
+		return $constants_only
79
+			? array_keys($this->valid_type_options)
80
+			: $this->valid_type_options;
81
+	}
82 82
 }
Please login to merge, or discard this patch.
core/services/form/meta/inputs/Text.php 1 patch
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -4,61 +4,61 @@
 block discarded – undo
4 4
 
5 5
 class Text
6 6
 {
7
-    /**
8
-     * indicates that the HTML input type is 'email'
9
-     */
10
-    public const TYPE_EMAIL = 'email';
7
+	/**
8
+	 * indicates that the HTML input type is 'email'
9
+	 */
10
+	public const TYPE_EMAIL = 'email';
11 11
 
12
-    /**
13
-     * indicates that the input is used to confirm an email address
14
-     */
15
-    public const TYPE_EMAIL_CONFIRM = 'email-confirmation';
12
+	/**
13
+	 * indicates that the input is used to confirm an email address
14
+	 */
15
+	public const TYPE_EMAIL_CONFIRM = 'email-confirmation';
16 16
 
17
-    /**
18
-     * indicates that the HTML input type is 'text'
19
-     */
20
-    public const TYPE_TEXT = 'text';
17
+	/**
18
+	 * indicates that the HTML input type is 'text'
19
+	 */
20
+	public const TYPE_TEXT = 'text';
21 21
 
22
-    /**
23
-     * indicates that the input is a TEXTAREA that only allows plain text
24
-     */
25
-    public const TYPE_TEXTAREA = 'textarea';
22
+	/**
23
+	 * indicates that the input is a TEXTAREA that only allows plain text
24
+	 */
25
+	public const TYPE_TEXTAREA = 'textarea';
26 26
 
27
-    /**
28
-     * indicates that the input is a TEXTAREA that allows simple html
29
-     */
30
-    public const TYPE_TEXTAREA_HTML = 'textarea-html';
27
+	/**
28
+	 * indicates that the input is a TEXTAREA that allows simple html
29
+	 */
30
+	public const TYPE_TEXTAREA_HTML = 'textarea-html';
31 31
 
32 32
 
33
-    /**
34
-     * @var array
35
-     */
36
-    private $valid_type_options;
33
+	/**
34
+	 * @var array
35
+	 */
36
+	private $valid_type_options;
37 37
 
38 38
 
39
-    public function __construct()
40
-    {
41
-        $this->valid_type_options = apply_filters(
42
-            'FHEE__EventEspresso_core_services_form_meta_inputs_Text__valid_type_options',
43
-            [
44
-                Text::TYPE_EMAIL         => esc_html__('Email', 'event_espresso'),
45
-                Text::TYPE_EMAIL_CONFIRM => esc_html__('Email Confirmation', 'event_espresso'),
46
-                Text::TYPE_TEXT          => esc_html__('Plain Text', 'event_espresso'),
47
-                Text::TYPE_TEXTAREA      => esc_html__('Plain Textarea', 'event_espresso'),
48
-                Text::TYPE_TEXTAREA_HTML => esc_html__('Simple HTML Textarea', 'event_espresso'),
49
-            ]
50
-        );
51
-    }
39
+	public function __construct()
40
+	{
41
+		$this->valid_type_options = apply_filters(
42
+			'FHEE__EventEspresso_core_services_form_meta_inputs_Text__valid_type_options',
43
+			[
44
+				Text::TYPE_EMAIL         => esc_html__('Email', 'event_espresso'),
45
+				Text::TYPE_EMAIL_CONFIRM => esc_html__('Email Confirmation', 'event_espresso'),
46
+				Text::TYPE_TEXT          => esc_html__('Plain Text', 'event_espresso'),
47
+				Text::TYPE_TEXTAREA      => esc_html__('Plain Textarea', 'event_espresso'),
48
+				Text::TYPE_TEXTAREA_HTML => esc_html__('Simple HTML Textarea', 'event_espresso'),
49
+			]
50
+		);
51
+	}
52 52
 
53 53
 
54
-    /**
55
-     * @param bool $constants_only
56
-     * @return array
57
-     */
58
-    public function validTypeOptions(bool $constants_only = false): array
59
-    {
60
-        return $constants_only
61
-            ? array_keys($this->valid_type_options)
62
-            : $this->valid_type_options;
63
-    }
54
+	/**
55
+	 * @param bool $constants_only
56
+	 * @return array
57
+	 */
58
+	public function validTypeOptions(bool $constants_only = false): array
59
+	{
60
+		return $constants_only
61
+			? array_keys($this->valid_type_options)
62
+			: $this->valid_type_options;
63
+	}
64 64
 }
Please login to merge, or discard this patch.