Completed
Branch FET-10766-extract-activation-d... (a650cc)
by
unknown
138:26 queued 126:47
created
core/db_models/EEM_Term_Relationship.model.php 1 patch
Indentation   +220 added lines, -220 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 require_once(EE_MODELS . 'EEM_Base.model.php');
5 5
 
@@ -15,230 +15,230 @@  discard block
 block discarded – undo
15 15
 class EEM_Term_Relationship extends EEM_Base
16 16
 {
17 17
 
18
-    // private instance of the Attendee object
19
-    protected static $_instance = null;
20
-
21
-
22
-
23
-    /**
24
-     * EEM_Term_Relationship constructor.
25
-     *
26
-     * @param string $timezone
27
-     */
28
-    protected function __construct($timezone = null)
29
-    {
30
-        $this->singular_item = __('Term Relationship', 'event_espresso');
31
-        $this->plural_item = __('Term Relationships', 'event_espresso');
32
-        $this->_tables = array(
33
-            'Term_Relationship' => new EE_Primary_Table('term_relationships'),
34
-        );
35
-        $models_this_can_attach_to = array_keys(EE_Registry::instance()->cpt_models());
36
-        $this->_fields = array(
37
-            'Term_Relationship' => array(
38
-                'object_id'        => new EE_Foreign_Key_Int_Field(
39
-                    'object_id',
40
-                    __('Object(Post) ID', 'event_espresso'),
41
-                    false,
42
-                    0,
43
-                    $models_this_can_attach_to
44
-                ),
45
-                'term_taxonomy_id' => new EE_Foreign_Key_Int_Field(
46
-                    'term_taxonomy_id',
47
-                    __(
48
-                        'Term (in context of a taxonomy) ID',
49
-                        'event_espresso'
50
-                    ),
51
-                    false,
52
-                    0,
53
-                    'Term_Taxonomy'
54
-                ),
55
-                'term_order'       => new EE_Integer_Field(
56
-                    'term_order',
57
-                    __('Term Order', 'event_espresso'),
58
-                    false,
59
-                    0
60
-                ),
61
-            ),
62
-        );
63
-        $this->_model_relations = array(
64
-            'Term_Taxonomy' => new EE_Belongs_To_Relation(),
65
-        );
66
-        foreach ($models_this_can_attach_to as $model_name) {
67
-            $this->_model_relations[$model_name] = new EE_Belongs_To_Relation();
68
-        }
69
-        $this->_wp_core_model = true;
70
-        $this->_indexes = array(
71
-            'PRIMARY' => new EE_Primary_Key_Index(array('object_id', 'term_taxonomy_id')),
72
-        );
73
-        $path_to_event_model = 'Event.';
74
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Event_Related_Public(
75
-            $path_to_event_model
76
-        );
77
-        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] =
78
-            new EE_Restriction_Generator_Event_Related_Protected(
79
-                $path_to_event_model
80
-            );
81
-        $this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Event_Related_Protected(
82
-            $path_to_event_model
83
-        );
84
-        $this->_cap_restriction_generators[EEM_Base::caps_delete] =
85
-            new EE_Restriction_Generator_Event_Related_Protected(
86
-                $path_to_event_model,
87
-                EEM_Base::caps_edit
88
-            );
89
-        $path_to_tax_model = 'Term_Taxonomy.';
90
-        //add cap restrictions for editing term relations to the "ee_assign_*"
91
-        //and for deleting term relations too
92
-        $cap_contexts_affected = array(EEM_Base::caps_edit, EEM_Base::caps_delete);
93
-        foreach ($cap_contexts_affected as $cap_context_affected) {
94
-            $this->_cap_restrictions[$cap_context_affected]['ee_assign_event_category'] =
95
-                new EE_Default_Where_Conditions(
96
-                    array(
97
-                        $path_to_tax_model . 'taxonomy*ee_assign_event_category' => array(
98
-                            '!=',
99
-                            'espresso_event_categories',
100
-                        ),
101
-                    )
102
-                );
103
-            $this->_cap_restrictions[$cap_context_affected]['ee_assign_venue_category'] =
104
-                new EE_Default_Where_Conditions(
105
-                    array(
106
-                        $path_to_tax_model . 'taxonomy*ee_assign_venue_category' => array(
107
-                            '!=',
108
-                            'espresso_venue_categories',
109
-                        ),
110
-                    )
111
-                );
112
-            $this->_cap_restrictions[$cap_context_affected]['ee_assign_event_type'] = new EE_Default_Where_Conditions(
113
-                array(
114
-                    $path_to_tax_model . 'taxonomy*ee_assign_event_type' => array('!=', 'espresso_event_type'),
115
-                )
116
-            );
117
-        }
118
-        parent::__construct($timezone);
119
-        add_filter(
120
-            'FHEE__Read__create_model_query_params',
121
-            array('EEM_Term_Relationship', 'rest_api_query_params'),
122
-            10,
123
-            3
124
-        );
125
-    }
126
-
127
-
128
-
129
-    /**
130
-     * Makes sure all term-taxonomy counts are correct
131
-     *
132
-     * @param int   $term_taxonomy_id the id of the term taxonomy to update. If NULL, updates ALL
133
-     * @global wpdb $wpdb
134
-     * @return int the number of rows affected
135
-     */
136
-    public function update_term_taxonomy_counts($term_taxonomy_id = null)
137
-    {
138
-        //because this uses a subquery and sometimes assigning to column to be another column's
139
-        //value, we just write the SQL directly.
140
-        global $wpdb;
141
-        if ($term_taxonomy_id) {
142
-            $second_operand = $wpdb->prepare('%d', $term_taxonomy_id);
143
-        } else {
144
-            $second_operand = 'tr.term_taxonomy_id';
145
-        }
146
-        $rows_affected = $this->_do_wpdb_query(
147
-            'query',
148
-            array(
149
-                "
18
+	// private instance of the Attendee object
19
+	protected static $_instance = null;
20
+
21
+
22
+
23
+	/**
24
+	 * EEM_Term_Relationship constructor.
25
+	 *
26
+	 * @param string $timezone
27
+	 */
28
+	protected function __construct($timezone = null)
29
+	{
30
+		$this->singular_item = __('Term Relationship', 'event_espresso');
31
+		$this->plural_item = __('Term Relationships', 'event_espresso');
32
+		$this->_tables = array(
33
+			'Term_Relationship' => new EE_Primary_Table('term_relationships'),
34
+		);
35
+		$models_this_can_attach_to = array_keys(EE_Registry::instance()->cpt_models());
36
+		$this->_fields = array(
37
+			'Term_Relationship' => array(
38
+				'object_id'        => new EE_Foreign_Key_Int_Field(
39
+					'object_id',
40
+					__('Object(Post) ID', 'event_espresso'),
41
+					false,
42
+					0,
43
+					$models_this_can_attach_to
44
+				),
45
+				'term_taxonomy_id' => new EE_Foreign_Key_Int_Field(
46
+					'term_taxonomy_id',
47
+					__(
48
+						'Term (in context of a taxonomy) ID',
49
+						'event_espresso'
50
+					),
51
+					false,
52
+					0,
53
+					'Term_Taxonomy'
54
+				),
55
+				'term_order'       => new EE_Integer_Field(
56
+					'term_order',
57
+					__('Term Order', 'event_espresso'),
58
+					false,
59
+					0
60
+				),
61
+			),
62
+		);
63
+		$this->_model_relations = array(
64
+			'Term_Taxonomy' => new EE_Belongs_To_Relation(),
65
+		);
66
+		foreach ($models_this_can_attach_to as $model_name) {
67
+			$this->_model_relations[$model_name] = new EE_Belongs_To_Relation();
68
+		}
69
+		$this->_wp_core_model = true;
70
+		$this->_indexes = array(
71
+			'PRIMARY' => new EE_Primary_Key_Index(array('object_id', 'term_taxonomy_id')),
72
+		);
73
+		$path_to_event_model = 'Event.';
74
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Event_Related_Public(
75
+			$path_to_event_model
76
+		);
77
+		$this->_cap_restriction_generators[EEM_Base::caps_read_admin] =
78
+			new EE_Restriction_Generator_Event_Related_Protected(
79
+				$path_to_event_model
80
+			);
81
+		$this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Event_Related_Protected(
82
+			$path_to_event_model
83
+		);
84
+		$this->_cap_restriction_generators[EEM_Base::caps_delete] =
85
+			new EE_Restriction_Generator_Event_Related_Protected(
86
+				$path_to_event_model,
87
+				EEM_Base::caps_edit
88
+			);
89
+		$path_to_tax_model = 'Term_Taxonomy.';
90
+		//add cap restrictions for editing term relations to the "ee_assign_*"
91
+		//and for deleting term relations too
92
+		$cap_contexts_affected = array(EEM_Base::caps_edit, EEM_Base::caps_delete);
93
+		foreach ($cap_contexts_affected as $cap_context_affected) {
94
+			$this->_cap_restrictions[$cap_context_affected]['ee_assign_event_category'] =
95
+				new EE_Default_Where_Conditions(
96
+					array(
97
+						$path_to_tax_model . 'taxonomy*ee_assign_event_category' => array(
98
+							'!=',
99
+							'espresso_event_categories',
100
+						),
101
+					)
102
+				);
103
+			$this->_cap_restrictions[$cap_context_affected]['ee_assign_venue_category'] =
104
+				new EE_Default_Where_Conditions(
105
+					array(
106
+						$path_to_tax_model . 'taxonomy*ee_assign_venue_category' => array(
107
+							'!=',
108
+							'espresso_venue_categories',
109
+						),
110
+					)
111
+				);
112
+			$this->_cap_restrictions[$cap_context_affected]['ee_assign_event_type'] = new EE_Default_Where_Conditions(
113
+				array(
114
+					$path_to_tax_model . 'taxonomy*ee_assign_event_type' => array('!=', 'espresso_event_type'),
115
+				)
116
+			);
117
+		}
118
+		parent::__construct($timezone);
119
+		add_filter(
120
+			'FHEE__Read__create_model_query_params',
121
+			array('EEM_Term_Relationship', 'rest_api_query_params'),
122
+			10,
123
+			3
124
+		);
125
+	}
126
+
127
+
128
+
129
+	/**
130
+	 * Makes sure all term-taxonomy counts are correct
131
+	 *
132
+	 * @param int   $term_taxonomy_id the id of the term taxonomy to update. If NULL, updates ALL
133
+	 * @global wpdb $wpdb
134
+	 * @return int the number of rows affected
135
+	 */
136
+	public function update_term_taxonomy_counts($term_taxonomy_id = null)
137
+	{
138
+		//because this uses a subquery and sometimes assigning to column to be another column's
139
+		//value, we just write the SQL directly.
140
+		global $wpdb;
141
+		if ($term_taxonomy_id) {
142
+			$second_operand = $wpdb->prepare('%d', $term_taxonomy_id);
143
+		} else {
144
+			$second_operand = 'tr.term_taxonomy_id';
145
+		}
146
+		$rows_affected = $this->_do_wpdb_query(
147
+			'query',
148
+			array(
149
+				"
150 150
                 UPDATE {$wpdb->term_taxonomy} AS tt 
151 151
                 SET count = (
152 152
                     select count(*) as proper_count from {$wpdb->term_relationships} AS tr 
153 153
                     WHERE tt.term_taxonomy_id = $second_operand
154 154
                 )",
155
-            )
156
-        );
157
-        return $rows_affected;
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     * Overrides the parent to also make sure term-taxonomy counts are up-to-date after
164
-     * inserting
165
-     *
166
-     * @param array $field_n_values @see EEM_Base::insert
167
-     * @return boolean
168
-     */
169
-    public function insert($field_n_values)
170
-    {
171
-        $return = parent::insert($field_n_values);
172
-        if (isset($field_n_values['term_taxonomy_id'])) {
173
-            $this->update_term_taxonomy_counts($field_n_values['term_taxonomy_id']);
174
-        }
175
-        return $return;
176
-    }
177
-
178
-
179
-
180
-    /**
181
-     * Overrides parent so that after an update, we also check the term_taxonomy_counts are
182
-     * all ok
183
-     *
184
-     * @param array   $fields_n_values         see EEM_Base::update
185
-     * @param array   $query_params            @see EEM_Base::get_all
186
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
187
-     *                                         in this model's entity map according to $fields_n_values that match
188
-     *                                         $query_params. This obviously has some overhead, so you can disable it
189
-     *                                         by setting this to FALSE, but be aware that model objects being used
190
-     *                                         could get out-of-sync with the database
191
-     * @return int
192
-     */
193
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
194
-    {
195
-        $count = parent::update($fields_n_values, $query_params, $keep_model_objs_in_sync);
196
-        if ($count) {
197
-            $this->update_term_taxonomy_counts();
198
-        }
199
-        return $count;
200
-    }
201
-
202
-
203
-
204
-    /**
205
-     * Overrides parent so that after running this, we also double-check
206
-     * the term taxonomy counts are up-to-date
207
-     *
208
-     * @param array   $query_params @see EEM_Base::get_all
209
-     * @param boolean $allow_blocking
210
-     * @return int @see EEM_Base::delete
211
-     */
212
-    public function delete($query_params, $allow_blocking = true)
213
-    {
214
-        $count = parent::delete($query_params, $allow_blocking);
215
-        if ($count) {
216
-            $this->update_term_taxonomy_counts();
217
-        }
218
-        return $count;
219
-    }
220
-
221
-
222
-
223
-    /**
224
-     * Makes sure that during REST API queries, we only return term relationships
225
-     * for term taxonomies which should be shown in the rest api
226
-     *
227
-     * @param array    $model_query_params
228
-     * @param array    $querystring_query_params
229
-     * @param EEM_Base $model
230
-     * @return array
231
-     */
232
-    public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
233
-    {
234
-        if ($model === EEM_Term_Relationship::instance()) {
235
-            $taxonomies = get_taxonomies(array('show_in_rest' => true));
236
-            if (! empty($taxonomies)) {
237
-                $model_query_params[0]['Term_Taxonomy.taxonomy'] = array('IN', $taxonomies);
238
-            }
239
-        }
240
-        return $model_query_params;
241
-    }
155
+			)
156
+		);
157
+		return $rows_affected;
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 * Overrides the parent to also make sure term-taxonomy counts are up-to-date after
164
+	 * inserting
165
+	 *
166
+	 * @param array $field_n_values @see EEM_Base::insert
167
+	 * @return boolean
168
+	 */
169
+	public function insert($field_n_values)
170
+	{
171
+		$return = parent::insert($field_n_values);
172
+		if (isset($field_n_values['term_taxonomy_id'])) {
173
+			$this->update_term_taxonomy_counts($field_n_values['term_taxonomy_id']);
174
+		}
175
+		return $return;
176
+	}
177
+
178
+
179
+
180
+	/**
181
+	 * Overrides parent so that after an update, we also check the term_taxonomy_counts are
182
+	 * all ok
183
+	 *
184
+	 * @param array   $fields_n_values         see EEM_Base::update
185
+	 * @param array   $query_params            @see EEM_Base::get_all
186
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
187
+	 *                                         in this model's entity map according to $fields_n_values that match
188
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
189
+	 *                                         by setting this to FALSE, but be aware that model objects being used
190
+	 *                                         could get out-of-sync with the database
191
+	 * @return int
192
+	 */
193
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
194
+	{
195
+		$count = parent::update($fields_n_values, $query_params, $keep_model_objs_in_sync);
196
+		if ($count) {
197
+			$this->update_term_taxonomy_counts();
198
+		}
199
+		return $count;
200
+	}
201
+
202
+
203
+
204
+	/**
205
+	 * Overrides parent so that after running this, we also double-check
206
+	 * the term taxonomy counts are up-to-date
207
+	 *
208
+	 * @param array   $query_params @see EEM_Base::get_all
209
+	 * @param boolean $allow_blocking
210
+	 * @return int @see EEM_Base::delete
211
+	 */
212
+	public function delete($query_params, $allow_blocking = true)
213
+	{
214
+		$count = parent::delete($query_params, $allow_blocking);
215
+		if ($count) {
216
+			$this->update_term_taxonomy_counts();
217
+		}
218
+		return $count;
219
+	}
220
+
221
+
222
+
223
+	/**
224
+	 * Makes sure that during REST API queries, we only return term relationships
225
+	 * for term taxonomies which should be shown in the rest api
226
+	 *
227
+	 * @param array    $model_query_params
228
+	 * @param array    $querystring_query_params
229
+	 * @param EEM_Base $model
230
+	 * @return array
231
+	 */
232
+	public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
233
+	{
234
+		if ($model === EEM_Term_Relationship::instance()) {
235
+			$taxonomies = get_taxonomies(array('show_in_rest' => true));
236
+			if (! empty($taxonomies)) {
237
+				$model_query_params[0]['Term_Taxonomy.taxonomy'] = array('IN', $taxonomies);
238
+			}
239
+		}
240
+		return $model_query_params;
241
+	}
242 242
 
243 243
 
244 244
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Term.model.php 1 patch
Indentation   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -15,207 +15,207 @@  discard block
 block discarded – undo
15 15
 class EEM_Term extends EEM_Base
16 16
 {
17 17
 
18
-    // private instance of the Attendee object
19
-    protected static $_instance = null;
20
-
21
-
22
-
23
-    /**
24
-     *__construct
25
-     *
26
-     * @param string $timezone
27
-     */
28
-    protected function __construct($timezone = null)
29
-    {
30
-        $this->singular_item = __('Term', 'event_espresso');
31
-        $this->plural_item = __('Terms', 'event_espresso');
32
-        $this->_tables = array(
33
-            'Term' => new EE_Primary_Table('terms', 'term_id'),
34
-        );
35
-        $this->_fields = array(
36
-            'Term' => array(
37
-                'term_id'    => new EE_Primary_Key_Int_Field('term_id', __('Term ID', 'event_espresso')),
38
-                'name'       => new EE_Plain_Text_Field('name', __('Term Name', 'event_espresso'), false, ''),
39
-                'slug'       => new EE_Slug_Field('slug', __('Term Slug', 'event_espresso'), false),
40
-                'term_group' => new EE_Integer_Field('term_group', __("Term Group", "event_espresso"), false, 0),
41
-            ),
42
-        );
43
-        $this->_model_relations = array(
44
-            'Term_Taxonomy' => new EE_Has_Many_Relation(),
45
-        );
46
-        $this->_wp_core_model = true;
47
-        $path_to_tax_model = 'Term_Taxonomy';
48
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
49
-        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Taxonomy_Protected(
50
-            $path_to_tax_model
51
-        );
52
-        $this->_cap_restriction_generators[EEM_Base::caps_edit] = false;
53
-        $this->_cap_restriction_generators[EEM_Base::caps_delete] = false;
54
-        $path_to_tax_model = $path_to_tax_model . '.';
55
-        //add cap restrictions for editing relating to the "ee_edit_*"
56
-        $this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
57
-            array(
58
-                $path_to_tax_model . 'taxonomy*ee_edit_event_category' => array('!=', 'espresso_event_categories'),
59
-            )
60
-        );
61
-        $this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
62
-            array(
63
-                $path_to_tax_model . 'taxonomy*ee_edit_venue_category' => array('!=', 'espresso_venue_categories'),
64
-            )
65
-        );
66
-        $this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_event_type'] = new EE_Default_Where_Conditions(
67
-            array(
68
-                $path_to_tax_model . 'taxonomy*ee_edit_event_type' => array('!=', 'espresso_event_type'),
69
-            )
70
-        );
71
-        //add cap restrictions for deleting relating to the "ee_deleting_*"
72
-        $this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
73
-            array(
74
-                $path_to_tax_model . 'taxonomy*ee_delete_event_category' => array('!=', 'espresso_event_categories'),
75
-            )
76
-        );
77
-        $this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
78
-            array(
79
-                $path_to_tax_model . 'taxonomy*ee_delete_venue_category' => array('!=', 'espresso_venue_categories'),
80
-            )
81
-        );
82
-        $this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_event_type'] = new EE_Default_Where_Conditions(
83
-            array(
84
-                $path_to_tax_model . 'taxonomy*ee_delete_event_type' => array('!=', 'espresso_event_type'),
85
-            )
86
-        );
87
-        parent::__construct($timezone);
88
-        add_filter('FHEE__Read__create_model_query_params', array('EEM_Term', 'rest_api_query_params'), 10, 3);
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     * retrieves a list of all EE event categories
95
-     *
96
-     * @access public
97
-     * @param bool $show_uncategorized
98
-     * @return \EE_Base_Class[]
99
-     */
100
-    public function get_all_ee_categories($show_uncategorized = false)
101
-    {
102
-        $where_params = array(
103
-            'Term_Taxonomy.taxonomy' => 'espresso_event_categories',
104
-            'NOT'                    => array('name' => __('Uncategorized', 'event_espresso')),
105
-        );
106
-        if ($show_uncategorized) {
107
-            unset($where_params['NOT']);
108
-        }
109
-        return EEM_Term::instance()->get_all(
110
-            array(
111
-                $where_params,
112
-                'order_by' => array('name' => 'ASC'),
113
-            )
114
-        );
115
-    }
116
-
117
-
118
-
119
-    /**
120
-     * retrieves a list of all post_tags associated with an EE CPT
121
-     *
122
-     * @access public
123
-     * @param string $post_type
124
-     * @return array
125
-     */
126
-    public function get_all_CPT_post_tags($post_type = '')
127
-    {
128
-        switch ($post_type) {
129
-            case 'espresso_events':
130
-                return $this->get_all_event_post_tags();
131
-                break;
132
-            case 'espresso_venues':
133
-                return $this->get_all_venue_post_tags();
134
-                break;
135
-            default:
136
-                $event_tags = $this->get_all_event_post_tags();
137
-                $venue_tags = $this->get_all_venue_post_tags();
138
-                return array_merge($event_tags, $venue_tags);
139
-        }
140
-    }
141
-
142
-
143
-
144
-    /**
145
-     * get_all_event_post_tags
146
-     *
147
-     * @return EE_Base_Class[]
148
-     */
149
-    public function get_all_event_post_tags()
150
-    {
151
-        $post_tags = EEM_Term::instance()->get_all(
152
-            array(
153
-                array(
154
-                    'Term_Taxonomy.taxonomy'        => 'post_tag',
155
-                    'Term_Taxonomy.Event.post_type' => 'espresso_events',
156
-                ),
157
-                'order_by'   => array('name' => 'ASC'),
158
-                'force_join' => array('Term_Taxonomy.Event'),
159
-            )
160
-        );
161
-        foreach ($post_tags as $key => $post_tag) {
162
-            if (! isset($post_tags[$key]->post_type)) {
163
-                $post_tags[$key]->post_type = array();
164
-            }
165
-            $post_tags[$key]->post_type[] = 'espresso_events';
166
-        }
167
-        return $post_tags;
168
-    }
169
-
170
-
171
-
172
-    /**
173
-     * get_all_venue_post_tags
174
-     *
175
-     * @return EE_Base_Class[]
176
-     */
177
-    public function get_all_venue_post_tags()
178
-    {
179
-        $post_tags = EEM_Term::instance()->get_all(
180
-            array(
181
-                array(
182
-                    'Term_Taxonomy.taxonomy'        => 'post_tag',
183
-                    'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
184
-                ),
185
-                'order_by'   => array('name' => 'ASC'),
186
-                'force_join' => array('Term_Taxonomy'),
187
-            )
188
-        );
189
-        foreach ($post_tags as $key => $post_tag) {
190
-            if (! isset($post_tags[$key]->post_type)) {
191
-                $post_tags[$key]->post_type = array();
192
-            }
193
-            $post_tags[$key]->post_type[] = 'espresso_venues';
194
-        }
195
-        return $post_tags;
196
-    }
197
-
198
-
199
-
200
-    /**
201
-     * Makes sure that during REST API queries, we only return terms
202
-     * for term taxonomies which should be shown in the rest api
203
-     *
204
-     * @param array    $model_query_params
205
-     * @param array    $querystring_query_params
206
-     * @param EEM_Base $model
207
-     * @return array
208
-     */
209
-    public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
210
-    {
211
-        if ($model === EEM_Term::instance()) {
212
-            $taxonomies = get_taxonomies(array('show_in_rest' => true));
213
-            if (! empty($taxonomies)) {
214
-                $model_query_params[0]['Term_Taxonomy.taxonomy'] = array('IN', $taxonomies);
215
-            }
216
-        }
217
-        return $model_query_params;
218
-    }
18
+	// private instance of the Attendee object
19
+	protected static $_instance = null;
20
+
21
+
22
+
23
+	/**
24
+	 *__construct
25
+	 *
26
+	 * @param string $timezone
27
+	 */
28
+	protected function __construct($timezone = null)
29
+	{
30
+		$this->singular_item = __('Term', 'event_espresso');
31
+		$this->plural_item = __('Terms', 'event_espresso');
32
+		$this->_tables = array(
33
+			'Term' => new EE_Primary_Table('terms', 'term_id'),
34
+		);
35
+		$this->_fields = array(
36
+			'Term' => array(
37
+				'term_id'    => new EE_Primary_Key_Int_Field('term_id', __('Term ID', 'event_espresso')),
38
+				'name'       => new EE_Plain_Text_Field('name', __('Term Name', 'event_espresso'), false, ''),
39
+				'slug'       => new EE_Slug_Field('slug', __('Term Slug', 'event_espresso'), false),
40
+				'term_group' => new EE_Integer_Field('term_group', __("Term Group", "event_espresso"), false, 0),
41
+			),
42
+		);
43
+		$this->_model_relations = array(
44
+			'Term_Taxonomy' => new EE_Has_Many_Relation(),
45
+		);
46
+		$this->_wp_core_model = true;
47
+		$path_to_tax_model = 'Term_Taxonomy';
48
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
49
+		$this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Taxonomy_Protected(
50
+			$path_to_tax_model
51
+		);
52
+		$this->_cap_restriction_generators[EEM_Base::caps_edit] = false;
53
+		$this->_cap_restriction_generators[EEM_Base::caps_delete] = false;
54
+		$path_to_tax_model = $path_to_tax_model . '.';
55
+		//add cap restrictions for editing relating to the "ee_edit_*"
56
+		$this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_event_category'] = new EE_Default_Where_Conditions(
57
+			array(
58
+				$path_to_tax_model . 'taxonomy*ee_edit_event_category' => array('!=', 'espresso_event_categories'),
59
+			)
60
+		);
61
+		$this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_venue_category'] = new EE_Default_Where_Conditions(
62
+			array(
63
+				$path_to_tax_model . 'taxonomy*ee_edit_venue_category' => array('!=', 'espresso_venue_categories'),
64
+			)
65
+		);
66
+		$this->_cap_restrictions[EEM_Base::caps_edit]['ee_edit_event_type'] = new EE_Default_Where_Conditions(
67
+			array(
68
+				$path_to_tax_model . 'taxonomy*ee_edit_event_type' => array('!=', 'espresso_event_type'),
69
+			)
70
+		);
71
+		//add cap restrictions for deleting relating to the "ee_deleting_*"
72
+		$this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_event_category'] = new EE_Default_Where_Conditions(
73
+			array(
74
+				$path_to_tax_model . 'taxonomy*ee_delete_event_category' => array('!=', 'espresso_event_categories'),
75
+			)
76
+		);
77
+		$this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_venue_category'] = new EE_Default_Where_Conditions(
78
+			array(
79
+				$path_to_tax_model . 'taxonomy*ee_delete_venue_category' => array('!=', 'espresso_venue_categories'),
80
+			)
81
+		);
82
+		$this->_cap_restrictions[EEM_Base::caps_delete]['ee_delete_event_type'] = new EE_Default_Where_Conditions(
83
+			array(
84
+				$path_to_tax_model . 'taxonomy*ee_delete_event_type' => array('!=', 'espresso_event_type'),
85
+			)
86
+		);
87
+		parent::__construct($timezone);
88
+		add_filter('FHEE__Read__create_model_query_params', array('EEM_Term', 'rest_api_query_params'), 10, 3);
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 * retrieves a list of all EE event categories
95
+	 *
96
+	 * @access public
97
+	 * @param bool $show_uncategorized
98
+	 * @return \EE_Base_Class[]
99
+	 */
100
+	public function get_all_ee_categories($show_uncategorized = false)
101
+	{
102
+		$where_params = array(
103
+			'Term_Taxonomy.taxonomy' => 'espresso_event_categories',
104
+			'NOT'                    => array('name' => __('Uncategorized', 'event_espresso')),
105
+		);
106
+		if ($show_uncategorized) {
107
+			unset($where_params['NOT']);
108
+		}
109
+		return EEM_Term::instance()->get_all(
110
+			array(
111
+				$where_params,
112
+				'order_by' => array('name' => 'ASC'),
113
+			)
114
+		);
115
+	}
116
+
117
+
118
+
119
+	/**
120
+	 * retrieves a list of all post_tags associated with an EE CPT
121
+	 *
122
+	 * @access public
123
+	 * @param string $post_type
124
+	 * @return array
125
+	 */
126
+	public function get_all_CPT_post_tags($post_type = '')
127
+	{
128
+		switch ($post_type) {
129
+			case 'espresso_events':
130
+				return $this->get_all_event_post_tags();
131
+				break;
132
+			case 'espresso_venues':
133
+				return $this->get_all_venue_post_tags();
134
+				break;
135
+			default:
136
+				$event_tags = $this->get_all_event_post_tags();
137
+				$venue_tags = $this->get_all_venue_post_tags();
138
+				return array_merge($event_tags, $venue_tags);
139
+		}
140
+	}
141
+
142
+
143
+
144
+	/**
145
+	 * get_all_event_post_tags
146
+	 *
147
+	 * @return EE_Base_Class[]
148
+	 */
149
+	public function get_all_event_post_tags()
150
+	{
151
+		$post_tags = EEM_Term::instance()->get_all(
152
+			array(
153
+				array(
154
+					'Term_Taxonomy.taxonomy'        => 'post_tag',
155
+					'Term_Taxonomy.Event.post_type' => 'espresso_events',
156
+				),
157
+				'order_by'   => array('name' => 'ASC'),
158
+				'force_join' => array('Term_Taxonomy.Event'),
159
+			)
160
+		);
161
+		foreach ($post_tags as $key => $post_tag) {
162
+			if (! isset($post_tags[$key]->post_type)) {
163
+				$post_tags[$key]->post_type = array();
164
+			}
165
+			$post_tags[$key]->post_type[] = 'espresso_events';
166
+		}
167
+		return $post_tags;
168
+	}
169
+
170
+
171
+
172
+	/**
173
+	 * get_all_venue_post_tags
174
+	 *
175
+	 * @return EE_Base_Class[]
176
+	 */
177
+	public function get_all_venue_post_tags()
178
+	{
179
+		$post_tags = EEM_Term::instance()->get_all(
180
+			array(
181
+				array(
182
+					'Term_Taxonomy.taxonomy'        => 'post_tag',
183
+					'Term_Taxonomy.Venue.post_type' => 'espresso_venues',
184
+				),
185
+				'order_by'   => array('name' => 'ASC'),
186
+				'force_join' => array('Term_Taxonomy'),
187
+			)
188
+		);
189
+		foreach ($post_tags as $key => $post_tag) {
190
+			if (! isset($post_tags[$key]->post_type)) {
191
+				$post_tags[$key]->post_type = array();
192
+			}
193
+			$post_tags[$key]->post_type[] = 'espresso_venues';
194
+		}
195
+		return $post_tags;
196
+	}
197
+
198
+
199
+
200
+	/**
201
+	 * Makes sure that during REST API queries, we only return terms
202
+	 * for term taxonomies which should be shown in the rest api
203
+	 *
204
+	 * @param array    $model_query_params
205
+	 * @param array    $querystring_query_params
206
+	 * @param EEM_Base $model
207
+	 * @return array
208
+	 */
209
+	public static function rest_api_query_params($model_query_params, $querystring_query_params, $model)
210
+	{
211
+		if ($model === EEM_Term::instance()) {
212
+			$taxonomies = get_taxonomies(array('show_in_rest' => true));
213
+			if (! empty($taxonomies)) {
214
+				$model_query_params[0]['Term_Taxonomy.taxonomy'] = array('IN', $taxonomies);
215
+			}
216
+		}
217
+		return $model_query_params;
218
+	}
219 219
 
220 220
 
221 221
 
Please login to merge, or discard this patch.
core/db_models/EEM_Post_Meta.model.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -33,58 +33,58 @@  discard block
 block discarded – undo
33 33
 class EEM_Post_Meta extends EEM_Base
34 34
 {
35 35
 
36
-    // private instance of the EE_Post_Meta object
37
-    protected static $_instance = null;
36
+	// private instance of the EE_Post_Meta object
37
+	protected static $_instance = null;
38 38
 
39 39
 
40 40
 
41
-    protected function __construct($timezone = null)
42
-    {
43
-        $this->singular_item = __('Post Meta', 'event_espresso');
44
-        $this->plural_item = __('Post Metas', 'event_espresso');
45
-        $this->_tables = array(
46
-            'Post_Meta' => new EE_Primary_Table('postmeta', 'meta_id'),
47
-        );
48
-        $models_this_can_attach_to = array_keys(EE_Registry::instance()->cpt_models());
49
-        $this->_fields = array(
50
-            'Post_Meta' => array(
51
-                'meta_id'    => new EE_Primary_Key_Int_Field(
52
-                    'meta_id',
53
-                    __("Meta ID", "event_espresso")
54
-                ),
55
-                'post_id'    => new EE_Foreign_Key_Int_Field(
56
-                    'post_id',
57
-                    __("Primary Key of Post", "event_espresso"),
58
-                    false,
59
-                    0,
60
-                    $models_this_can_attach_to
61
-                ),
62
-                'meta_key'   => new EE_Plain_Text_Field(
63
-                    'meta_key',
64
-                    __("Meta Key", "event_espresso"),
65
-                    false,
66
-                    ''
67
-                ),
68
-                'meta_value' => new EE_Maybe_Serialized_Text_Field(
69
-                    'meta_value',
70
-                    __("Meta Value", "event_espresso"),
71
-                    true
72
-                ),
73
-            ),
74
-        );
75
-        $this->_model_relations = array();
76
-        foreach ($models_this_can_attach_to as $model) {
77
-            $this->_model_relations[$model] = new EE_Belongs_To_Relation();
78
-        }
79
-        $this->_wp_core_model = true;
80
-        foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
81
-            $this->_cap_restriction_generators[$cap_context] = new EE_Restriction_Generator_Meta(
82
-                'meta_key',
83
-                'meta_value'
84
-            );
85
-        }
86
-        parent::__construct($timezone);
87
-    }
41
+	protected function __construct($timezone = null)
42
+	{
43
+		$this->singular_item = __('Post Meta', 'event_espresso');
44
+		$this->plural_item = __('Post Metas', 'event_espresso');
45
+		$this->_tables = array(
46
+			'Post_Meta' => new EE_Primary_Table('postmeta', 'meta_id'),
47
+		);
48
+		$models_this_can_attach_to = array_keys(EE_Registry::instance()->cpt_models());
49
+		$this->_fields = array(
50
+			'Post_Meta' => array(
51
+				'meta_id'    => new EE_Primary_Key_Int_Field(
52
+					'meta_id',
53
+					__("Meta ID", "event_espresso")
54
+				),
55
+				'post_id'    => new EE_Foreign_Key_Int_Field(
56
+					'post_id',
57
+					__("Primary Key of Post", "event_espresso"),
58
+					false,
59
+					0,
60
+					$models_this_can_attach_to
61
+				),
62
+				'meta_key'   => new EE_Plain_Text_Field(
63
+					'meta_key',
64
+					__("Meta Key", "event_espresso"),
65
+					false,
66
+					''
67
+				),
68
+				'meta_value' => new EE_Maybe_Serialized_Text_Field(
69
+					'meta_value',
70
+					__("Meta Value", "event_espresso"),
71
+					true
72
+				),
73
+			),
74
+		);
75
+		$this->_model_relations = array();
76
+		foreach ($models_this_can_attach_to as $model) {
77
+			$this->_model_relations[$model] = new EE_Belongs_To_Relation();
78
+		}
79
+		$this->_wp_core_model = true;
80
+		foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
81
+			$this->_cap_restriction_generators[$cap_context] = new EE_Restriction_Generator_Meta(
82
+				'meta_key',
83
+				'meta_value'
84
+			);
85
+		}
86
+		parent::__construct($timezone);
87
+	}
88 88
 
89 89
 
90 90
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Currency_Payment_Method.model.php 1 patch
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (!defined('EVENT_ESPRESSO_VERSION'))
3
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
4 4
 	exit('No direct script access allowed');
5 5
 
6 6
 /**
@@ -25,22 +25,22 @@  discard block
 block discarded – undo
25 25
  *
26 26
  * ------------------------------------------------------------------------
27 27
  */
28
-class EEM_Currency_Payment_Method extends EEM_Base{
28
+class EEM_Currency_Payment_Method extends EEM_Base {
29 29
 	// private instance of the Attendee object
30 30
 	protected static $_instance = NULL;
31 31
 
32 32
 
33
-	protected function __construct( $timezone = NULL ) {
34
-		$this->singular_item = __('Currency Usable by Payment Method','event_espresso');
35
-		$this->plural_item = __('Currencies Usable by Payment Methods','event_espresso');
33
+	protected function __construct($timezone = NULL) {
34
+		$this->singular_item = __('Currency Usable by Payment Method', 'event_espresso');
35
+		$this->plural_item = __('Currencies Usable by Payment Methods', 'event_espresso');
36 36
 		$this->_tables = array(
37
-			'Currency_Payment_Method'=>new EE_Primary_Table('esp_currency_payment_method','CPM_ID')
37
+			'Currency_Payment_Method'=>new EE_Primary_Table('esp_currency_payment_method', 'CPM_ID')
38 38
 		);
39 39
 		$this->_fields = array(
40 40
 			'Currency_Payment_Method'=>array(
41
-				'CPM_ID'=>new EE_Primary_Key_Int_Field('CPM_ID', __('Currency to Payment Method LInk ID','event_espresso')),
42
-				'CUR_code'=>new EE_Foreign_Key_String_Field('CUR_code', __('Currency Code','event_espresso'), false, '', 'Currency'),
43
-				'PMD_ID'=>new EE_Foreign_Key_Int_Field('PMD_ID', __('Paymetn Method ID','event_espresso'), false, 0, 'Payment_Method')
41
+				'CPM_ID'=>new EE_Primary_Key_Int_Field('CPM_ID', __('Currency to Payment Method LInk ID', 'event_espresso')),
42
+				'CUR_code'=>new EE_Foreign_Key_String_Field('CUR_code', __('Currency Code', 'event_espresso'), false, '', 'Currency'),
43
+				'PMD_ID'=>new EE_Foreign_Key_Int_Field('PMD_ID', __('Paymetn Method ID', 'event_espresso'), false, 0, 'Payment_Method')
44 44
 			)
45 45
 		);
46 46
 		$this->_model_relations = array(
@@ -48,9 +48,9 @@  discard block
 block discarded – undo
48 48
 			'Payment_Method'=>new EE_Belongs_To_Relation()
49 49
 		);
50 50
 		//this model is generally available for reading
51
-		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
51
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
52 52
 		$this->_caps_slug = 'payment_methods';
53
-		parent::__construct( $timezone );
53
+		parent::__construct($timezone);
54 54
 	}
55 55
 }
56 56
 
Please login to merge, or discard this patch.
core/db_models/EEM_Status.model.php 1 patch
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -25,291 +25,291 @@  discard block
 block discarded – undo
25 25
 class EEM_Status extends EEM_Base
26 26
 {
27 27
 
28
-    // private instance of the Attendee object
29
-    protected static $_instance = null;
28
+	// private instance of the Attendee object
29
+	protected static $_instance = null;
30 30
 
31 31
 
32
-    /**
33
-     * @return EEM_Status
34
-     */
35
-    protected function __construct($timezone = null)
36
-    {
37
-        $this->singular_item    = __('Status', 'event_espresso');
38
-        $this->plural_item      = __('Stati', 'event_espresso');
39
-        $this->_tables          = array(
40
-            'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
-        );
42
-        $this->_fields          = array(
43
-            'StatusTable' => array(
44
-                'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
-                'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
-                'STS_type'     => new EE_Enum_Text_Field(
47
-                    'STS_type',
48
-                    __("Type", "event_espresso"),
49
-                    false,
50
-                    'event',
51
-                    array(
52
-                        'event'        => __("Event", "event_espresso"),//deprecated
53
-                        'registration' => __("Registration", "event_espresso"),
54
-                        'transaction'  => __("Transaction", "event_espresso"),
55
-                        'payment'      => __("Payment", "event_espresso"),
56
-                        'email'        => __("Email", "event_espresso"),
57
-                        'message'      => __("Message", "event_espresso"),
58
-                    )),
59
-                'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false, false),
60
-                'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
-                'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
-            ),
63
-        );
64
-        $this->_model_relations = array(
65
-            'Registration' => new EE_Has_Many_Relation(),
66
-            'Transaction'  => new EE_Has_Many_Relation(),
67
-            'Payment'      => new EE_Has_Many_Relation(),
68
-        );
69
-        //this model is generally available for reading
70
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
32
+	/**
33
+	 * @return EEM_Status
34
+	 */
35
+	protected function __construct($timezone = null)
36
+	{
37
+		$this->singular_item    = __('Status', 'event_espresso');
38
+		$this->plural_item      = __('Stati', 'event_espresso');
39
+		$this->_tables          = array(
40
+			'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
+		);
42
+		$this->_fields          = array(
43
+			'StatusTable' => array(
44
+				'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
+				'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
+				'STS_type'     => new EE_Enum_Text_Field(
47
+					'STS_type',
48
+					__("Type", "event_espresso"),
49
+					false,
50
+					'event',
51
+					array(
52
+						'event'        => __("Event", "event_espresso"),//deprecated
53
+						'registration' => __("Registration", "event_espresso"),
54
+						'transaction'  => __("Transaction", "event_espresso"),
55
+						'payment'      => __("Payment", "event_espresso"),
56
+						'email'        => __("Email", "event_espresso"),
57
+						'message'      => __("Message", "event_espresso"),
58
+					)),
59
+				'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false, false),
60
+				'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
+				'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
+			),
63
+		);
64
+		$this->_model_relations = array(
65
+			'Registration' => new EE_Has_Many_Relation(),
66
+			'Transaction'  => new EE_Has_Many_Relation(),
67
+			'Payment'      => new EE_Has_Many_Relation(),
68
+		);
69
+		//this model is generally available for reading
70
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
71 71
 
72
-        parent::__construct($timezone);
73
-    }
72
+		parent::__construct($timezone);
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * This method provides the localized singular or plural string for a given status id
78
-     *
79
-     * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
-     *                           That way if there isn't a translation in the index we'll return the default code.
81
-     * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
-     *                           same as the singular (in English), however, this may NOT be the case with other
83
-     *                           languages
84
-     * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
-     *                           the status string returned ( UPPER, lower, Sentence)
86
-     * @throws EE_Error
87
-     * @return array             an array of translated strings for the incoming status id.
88
-     */
89
-    public function localized_status($statuses, $plural = false, $schema = 'upper')
90
-    {
91
-        //note these are all in lower case because ucwords() on upper case will NOT convert.
92
-        $translation_array = array(
93
-            EEM_Registration::status_id_pending_payment => array(
94
-                __('pending payment', 'event_espresso'), //singular
95
-                __('pending payments', 'event_espresso') //plural
96
-            ),
97
-            EEM_Registration::status_id_approved        => array(
98
-                __('approved', 'event_espresso'), //singular
99
-                __('approved', 'event_espresso') //plural
100
-            ),
101
-            EEM_Registration::status_id_not_approved    => array(
102
-                __('not approved', 'event_espresso'),
103
-                __('not approved', 'event_espresso'),
104
-            ),
105
-            EEM_Registration::status_id_cancelled       => array(
106
-                __('cancelled', 'event_espresso'),
107
-                __('cancelled', 'event_espresso'),
108
-            ),
109
-            EEM_Registration::status_id_incomplete      => array(
110
-                __('incomplete', 'event_espresso'),
111
-                __('incomplete', 'event_espresso'),
112
-            ),
113
-            EEM_Registration::status_id_declined        => array(
114
-                __('declined', 'event_espresso'),
115
-                __('declined', 'event_espresso'),
116
-            ),
117
-            EEM_Registration::status_id_wait_list       => array(
118
-                __('wait list', 'event_espresso'),
119
-                __('wait list', 'event_espresso'),
120
-            ),
121
-            EEM_Transaction::overpaid_status_code       => array(
122
-                __('overpaid', 'event_espresso'),
123
-                __('overpaid', 'event_espresso'),
124
-            ),
125
-            EEM_Transaction::complete_status_code       => array(
126
-                __('complete', 'event_espresso'),
127
-                __('complete', 'event_espresso'),
128
-            ),
129
-            EEM_Transaction::incomplete_status_code     => array(
130
-                __('incomplete', 'event_espresso'),
131
-                __('incomplete', 'event_espresso'),
132
-            ),
133
-            EEM_Transaction::failed_status_code         => array(
134
-                __('failed', 'event_espresso'),
135
-                __('failed', 'event_espresso'),
136
-            ),
137
-            EEM_Transaction::abandoned_status_code      => array(
138
-                __('abandoned', 'event_espresso'),
139
-                __('abandoned', 'event_espresso'),
140
-            ),
141
-            EEM_Payment::status_id_approved             => array(
142
-                __('accepted', 'event_espresso'),
143
-                __('accepted', 'event_espresso'),
144
-            ),
145
-            EEM_Payment::status_id_pending              => array(
146
-                __('pending', 'event_espresso'),
147
-                __('pending', 'event_espresso'),
148
-            ),
149
-            EEM_Payment::status_id_cancelled            => array(
150
-                __('cancelled', 'event_espresso'),
151
-                __('cancelled', 'event_espresso'),
152
-            ),
153
-            EEM_Payment::status_id_declined             => array(
154
-                __('declined', 'event_espresso'),
155
-                __('declined', 'event_espresso'),
156
-            ),
157
-            EEM_Payment::status_id_failed               => array(
158
-                __('failed', 'event_espresso'),
159
-                __('failed', 'event_espresso'),
160
-            ),
161
-            //following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
-            EEM_Event::sold_out                         => array(
163
-                __('sold out', 'event_espresso'),
164
-                __('sold out', 'event_espresso'),
165
-            ),
166
-            EEM_Event::postponed                        => array(
167
-                __('postponed', 'event_espresso'),
168
-                __('Postponed', 'event_espresso'),
169
-            ),
170
-            EEM_Event::cancelled                        => array(
171
-                __('cancelled', 'event_espresso'),
172
-                __('cancelled', 'event_espresso'),
173
-            ),
174
-            EE_Ticket::archived                         => array(
175
-                __('archived', 'event_espresso'),
176
-                __('archived', 'event_espresso'),
177
-            ),
178
-            EE_Ticket::expired                          => array(
179
-                __('expired', 'event_espresso'),
180
-                __('expired', 'event_espresso'),
181
-            ),
182
-            EE_Ticket::sold_out                         => array(
183
-                __('sold out', 'event_espresso'),
184
-                __('sold out', 'event_espresso'),
185
-            ),
186
-            EE_Ticket::pending                          => array(
187
-                __('upcoming', 'event_espresso'),
188
-                __('upcoming', 'event_espresso'),
189
-            ),
190
-            EE_Ticket::onsale                           => array(
191
-                __('on sale', 'event_espresso'),
192
-                __('on sale', 'event_espresso'),
193
-            ),
194
-            EE_Datetime::cancelled                      => array(
195
-                __('cancelled', 'event_espresso'),
196
-                __('cancelled', 'event_espresso'),
197
-            ),
198
-            EE_Datetime::sold_out                       => array(
199
-                __('sold out', 'event_espresso'),
200
-                __('sold out', 'event_espresso'),
201
-            ),
202
-            EE_Datetime::expired                        => array(
203
-                __('expired', 'event_espresso'),
204
-                __('expired', 'event_espresso'),
205
-            ),
206
-            EE_Datetime::inactive                       => array(
207
-                __('inactive', 'event_espresso'),
208
-                __('inactive', 'event_espresso'),
209
-            ),
210
-            EE_Datetime::upcoming                       => array(
211
-                __('upcoming', 'event_espresso'),
212
-                __('upcoming', 'event_espresso'),
213
-            ),
214
-            EE_Datetime::active                         => array(
215
-                __('active', 'event_espresso'),
216
-                __('active', 'event_espresso'),
217
-            ),
218
-            EE_Datetime::postponed                      => array(
219
-                __('postponed', 'event_espresso'),
220
-                __('postponed', 'event_espresso'),
221
-            ),
222
-            //messages related
223
-            EEM_Message::status_sent                    => array(
224
-                __('sent', 'event_espresso'),
225
-                __('sent', 'event_espresso'),
226
-            ),
227
-            EEM_Message::status_idle                    => array(
228
-                __('queued for sending', 'event_espresso'),
229
-                __('queued for sending', 'event_espresso'),
230
-            ),
231
-            EEM_Message::status_failed                  => array(
232
-                __('failed', 'event_espresso'),
233
-                __('failed', 'event_espresso'),
234
-            ),
235
-            EEM_Message::status_debug_only              => array(
236
-                __('debug only', 'event_espresso'),
237
-                __('debug only', 'event_espresso'),
238
-            ),
239
-            EEM_Message::status_messenger_executing     => array(
240
-                __('messenger is executing', 'event_espresso'),
241
-                __('messenger is executing', 'event_espresso'),
242
-            ),
243
-            EEM_Message::status_resend                  => array(
244
-                __('queued for resending', 'event_espresso'),
245
-                __('queued for resending', 'event_espresso'),
246
-            ),
247
-            EEM_Message::status_incomplete              => array(
248
-                __('queued for generating', 'event_espresso'),
249
-                __('queued for generating', 'event_espresso'),
250
-            ),
251
-            EEM_Message::status_retry                   => array(
252
-                __('failed sending, can be retried', 'event_espresso'),
253
-                __('failed sending, can be retried', 'event_espresso'),
254
-            ),
255
-            EEM_CPT_Base::post_status_publish           => array(
256
-                __('published', 'event_espresso'),
257
-                __('published', 'event_espresso'),
258
-            ),
259
-            EEM_CPT_Base::post_status_future            => array(
260
-                __('scheduled', 'event_espresso'),
261
-                __('scheduled', 'event_espresso'),
262
-            ),
263
-            EEM_CPT_Base::post_status_draft             => array(
264
-                __('draft', 'event_espresso'),
265
-                __('draft', 'event_espresso'),
266
-            ),
267
-            EEM_CPT_Base::post_status_pending           => array(
268
-                __('pending', 'event_espresso'),
269
-                __('pending', 'event_espresso'),
270
-            ),
271
-            EEM_CPT_Base::post_status_private           => array(
272
-                __('private', 'event_espresso'),
273
-                __('private', 'event_espresso'),
274
-            ),
275
-            EEM_CPT_Base::post_status_trashed           => array(
276
-                __('trashed', 'event_espresso'),
277
-                __('trashed', 'event_espresso'),
278
-            ),
279
-        );
76
+	/**
77
+	 * This method provides the localized singular or plural string for a given status id
78
+	 *
79
+	 * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
+	 *                           That way if there isn't a translation in the index we'll return the default code.
81
+	 * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
+	 *                           same as the singular (in English), however, this may NOT be the case with other
83
+	 *                           languages
84
+	 * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
+	 *                           the status string returned ( UPPER, lower, Sentence)
86
+	 * @throws EE_Error
87
+	 * @return array             an array of translated strings for the incoming status id.
88
+	 */
89
+	public function localized_status($statuses, $plural = false, $schema = 'upper')
90
+	{
91
+		//note these are all in lower case because ucwords() on upper case will NOT convert.
92
+		$translation_array = array(
93
+			EEM_Registration::status_id_pending_payment => array(
94
+				__('pending payment', 'event_espresso'), //singular
95
+				__('pending payments', 'event_espresso') //plural
96
+			),
97
+			EEM_Registration::status_id_approved        => array(
98
+				__('approved', 'event_espresso'), //singular
99
+				__('approved', 'event_espresso') //plural
100
+			),
101
+			EEM_Registration::status_id_not_approved    => array(
102
+				__('not approved', 'event_espresso'),
103
+				__('not approved', 'event_espresso'),
104
+			),
105
+			EEM_Registration::status_id_cancelled       => array(
106
+				__('cancelled', 'event_espresso'),
107
+				__('cancelled', 'event_espresso'),
108
+			),
109
+			EEM_Registration::status_id_incomplete      => array(
110
+				__('incomplete', 'event_espresso'),
111
+				__('incomplete', 'event_espresso'),
112
+			),
113
+			EEM_Registration::status_id_declined        => array(
114
+				__('declined', 'event_espresso'),
115
+				__('declined', 'event_espresso'),
116
+			),
117
+			EEM_Registration::status_id_wait_list       => array(
118
+				__('wait list', 'event_espresso'),
119
+				__('wait list', 'event_espresso'),
120
+			),
121
+			EEM_Transaction::overpaid_status_code       => array(
122
+				__('overpaid', 'event_espresso'),
123
+				__('overpaid', 'event_espresso'),
124
+			),
125
+			EEM_Transaction::complete_status_code       => array(
126
+				__('complete', 'event_espresso'),
127
+				__('complete', 'event_espresso'),
128
+			),
129
+			EEM_Transaction::incomplete_status_code     => array(
130
+				__('incomplete', 'event_espresso'),
131
+				__('incomplete', 'event_espresso'),
132
+			),
133
+			EEM_Transaction::failed_status_code         => array(
134
+				__('failed', 'event_espresso'),
135
+				__('failed', 'event_espresso'),
136
+			),
137
+			EEM_Transaction::abandoned_status_code      => array(
138
+				__('abandoned', 'event_espresso'),
139
+				__('abandoned', 'event_espresso'),
140
+			),
141
+			EEM_Payment::status_id_approved             => array(
142
+				__('accepted', 'event_espresso'),
143
+				__('accepted', 'event_espresso'),
144
+			),
145
+			EEM_Payment::status_id_pending              => array(
146
+				__('pending', 'event_espresso'),
147
+				__('pending', 'event_espresso'),
148
+			),
149
+			EEM_Payment::status_id_cancelled            => array(
150
+				__('cancelled', 'event_espresso'),
151
+				__('cancelled', 'event_espresso'),
152
+			),
153
+			EEM_Payment::status_id_declined             => array(
154
+				__('declined', 'event_espresso'),
155
+				__('declined', 'event_espresso'),
156
+			),
157
+			EEM_Payment::status_id_failed               => array(
158
+				__('failed', 'event_espresso'),
159
+				__('failed', 'event_espresso'),
160
+			),
161
+			//following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
+			EEM_Event::sold_out                         => array(
163
+				__('sold out', 'event_espresso'),
164
+				__('sold out', 'event_espresso'),
165
+			),
166
+			EEM_Event::postponed                        => array(
167
+				__('postponed', 'event_espresso'),
168
+				__('Postponed', 'event_espresso'),
169
+			),
170
+			EEM_Event::cancelled                        => array(
171
+				__('cancelled', 'event_espresso'),
172
+				__('cancelled', 'event_espresso'),
173
+			),
174
+			EE_Ticket::archived                         => array(
175
+				__('archived', 'event_espresso'),
176
+				__('archived', 'event_espresso'),
177
+			),
178
+			EE_Ticket::expired                          => array(
179
+				__('expired', 'event_espresso'),
180
+				__('expired', 'event_espresso'),
181
+			),
182
+			EE_Ticket::sold_out                         => array(
183
+				__('sold out', 'event_espresso'),
184
+				__('sold out', 'event_espresso'),
185
+			),
186
+			EE_Ticket::pending                          => array(
187
+				__('upcoming', 'event_espresso'),
188
+				__('upcoming', 'event_espresso'),
189
+			),
190
+			EE_Ticket::onsale                           => array(
191
+				__('on sale', 'event_espresso'),
192
+				__('on sale', 'event_espresso'),
193
+			),
194
+			EE_Datetime::cancelled                      => array(
195
+				__('cancelled', 'event_espresso'),
196
+				__('cancelled', 'event_espresso'),
197
+			),
198
+			EE_Datetime::sold_out                       => array(
199
+				__('sold out', 'event_espresso'),
200
+				__('sold out', 'event_espresso'),
201
+			),
202
+			EE_Datetime::expired                        => array(
203
+				__('expired', 'event_espresso'),
204
+				__('expired', 'event_espresso'),
205
+			),
206
+			EE_Datetime::inactive                       => array(
207
+				__('inactive', 'event_espresso'),
208
+				__('inactive', 'event_espresso'),
209
+			),
210
+			EE_Datetime::upcoming                       => array(
211
+				__('upcoming', 'event_espresso'),
212
+				__('upcoming', 'event_espresso'),
213
+			),
214
+			EE_Datetime::active                         => array(
215
+				__('active', 'event_espresso'),
216
+				__('active', 'event_espresso'),
217
+			),
218
+			EE_Datetime::postponed                      => array(
219
+				__('postponed', 'event_espresso'),
220
+				__('postponed', 'event_espresso'),
221
+			),
222
+			//messages related
223
+			EEM_Message::status_sent                    => array(
224
+				__('sent', 'event_espresso'),
225
+				__('sent', 'event_espresso'),
226
+			),
227
+			EEM_Message::status_idle                    => array(
228
+				__('queued for sending', 'event_espresso'),
229
+				__('queued for sending', 'event_espresso'),
230
+			),
231
+			EEM_Message::status_failed                  => array(
232
+				__('failed', 'event_espresso'),
233
+				__('failed', 'event_espresso'),
234
+			),
235
+			EEM_Message::status_debug_only              => array(
236
+				__('debug only', 'event_espresso'),
237
+				__('debug only', 'event_espresso'),
238
+			),
239
+			EEM_Message::status_messenger_executing     => array(
240
+				__('messenger is executing', 'event_espresso'),
241
+				__('messenger is executing', 'event_espresso'),
242
+			),
243
+			EEM_Message::status_resend                  => array(
244
+				__('queued for resending', 'event_espresso'),
245
+				__('queued for resending', 'event_espresso'),
246
+			),
247
+			EEM_Message::status_incomplete              => array(
248
+				__('queued for generating', 'event_espresso'),
249
+				__('queued for generating', 'event_espresso'),
250
+			),
251
+			EEM_Message::status_retry                   => array(
252
+				__('failed sending, can be retried', 'event_espresso'),
253
+				__('failed sending, can be retried', 'event_espresso'),
254
+			),
255
+			EEM_CPT_Base::post_status_publish           => array(
256
+				__('published', 'event_espresso'),
257
+				__('published', 'event_espresso'),
258
+			),
259
+			EEM_CPT_Base::post_status_future            => array(
260
+				__('scheduled', 'event_espresso'),
261
+				__('scheduled', 'event_espresso'),
262
+			),
263
+			EEM_CPT_Base::post_status_draft             => array(
264
+				__('draft', 'event_espresso'),
265
+				__('draft', 'event_espresso'),
266
+			),
267
+			EEM_CPT_Base::post_status_pending           => array(
268
+				__('pending', 'event_espresso'),
269
+				__('pending', 'event_espresso'),
270
+			),
271
+			EEM_CPT_Base::post_status_private           => array(
272
+				__('private', 'event_espresso'),
273
+				__('private', 'event_espresso'),
274
+			),
275
+			EEM_CPT_Base::post_status_trashed           => array(
276
+				__('trashed', 'event_espresso'),
277
+				__('trashed', 'event_espresso'),
278
+			),
279
+		);
280 280
 
281
-        $translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
281
+		$translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
282 282
 
283
-        if ( ! is_array($statuses)) {
284
-            throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
-                'event_espresso'));
286
-        }
283
+		if ( ! is_array($statuses)) {
284
+			throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
+				'event_espresso'));
286
+		}
287 287
 
288
-        $translation = array();
288
+		$translation = array();
289 289
 
290
-        foreach ($statuses as $id => $code) {
291
-            if (isset($translation_array[$id])) {
292
-                $translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
-            } else {
294
-                $translation[$id] = $code;
295
-            }
290
+		foreach ($statuses as $id => $code) {
291
+			if (isset($translation_array[$id])) {
292
+				$translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
+			} else {
294
+				$translation[$id] = $code;
295
+			}
296 296
 
297
-            //schema
298
-            switch ($schema) {
299
-                case 'lower' :
300
-                    $translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
-                    break;
302
-                case 'sentence' :
303
-                    $translation[$id] = ucwords($translation[$id]);
304
-                    break;
305
-                case 'upper' :
306
-                    $translation[$id] = strtoupper($translation[$id]);
307
-                    break;
308
-            }
309
-        }
297
+			//schema
298
+			switch ($schema) {
299
+				case 'lower' :
300
+					$translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
+					break;
302
+				case 'sentence' :
303
+					$translation[$id] = ucwords($translation[$id]);
304
+					break;
305
+				case 'upper' :
306
+					$translation[$id] = strtoupper($translation[$id]);
307
+					break;
308
+			}
309
+		}
310 310
 
311
-        return $translation;
312
-    }
311
+		return $translation;
312
+	}
313 313
 
314 314
 
315 315
 }
Please login to merge, or discard this patch.
core/libraries/rest_api/controllers/model/Read.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1317,7 +1317,7 @@
 block discarded – undo
1317 1317
      *
1318 1318
 *@param EEM_Base        $model
1319 1319
      * @param WP_REST_Request $request
1320
-     * @param null             $context
1320
+     * @param string             $context
1321 1321
      * @return array|WP_Error
1322 1322
      */
1323 1323
     public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null)
Please login to merge, or discard this patch.
Indentation   +1341 added lines, -1347 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
 use EEM_CPT_Base;
22 22
 
23 23
 if (! defined('EVENT_ESPRESSO_VERSION')) {
24
-    exit('No direct script access allowed');
24
+	exit('No direct script access allowed');
25 25
 }
26 26
 
27 27
 
@@ -39,1364 +39,1358 @@  discard block
 block discarded – undo
39 39
 
40 40
 
41 41
 
42
-    /**
43
-     * @var CalculatedModelFields
44
-     */
45
-    protected $fields_calculator;
42
+	/**
43
+	 * @var CalculatedModelFields
44
+	 */
45
+	protected $fields_calculator;
46 46
 
47 47
 
48 48
 
49
-    /**
50
-     * Read constructor.
51
-     */
52
-    public function __construct()
53
-    {
54
-        parent::__construct();
55
-        $this->fields_calculator = new CalculatedModelFields();
56
-    }
49
+	/**
50
+	 * Read constructor.
51
+	 */
52
+	public function __construct()
53
+	{
54
+		parent::__construct();
55
+		$this->fields_calculator = new CalculatedModelFields();
56
+	}
57 57
 
58 58
 
59 59
 
60
-    /**
61
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
62
-
63
-     *
60
+	/**
61
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
62
+	 *
64 63
 *@param WP_REST_Request $request
65
-     * @param string           $version
66
-     * @param string           $model_name
67
-     * @return \WP_REST_Response|WP_Error
68
-     */
69
-    public static function handleRequestGetAll(WP_REST_Request $request, $version, $model_name)
70
-    {
71
-        $controller = new Read();
72
-        try {
73
-            $controller->setRequestedVersion($version);
74
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
75
-                return $controller->sendResponse(
76
-                    new WP_Error(
77
-                        'endpoint_parsing_error',
78
-                        sprintf(
79
-                            __(
80
-                                'There is no model for endpoint %s. Please contact event espresso support',
81
-                                'event_espresso'
82
-                            ),
83
-                            $model_name
84
-                        )
85
-                    )
86
-                );
87
-            }
88
-            return $controller->sendResponse(
89
-                $controller->getEntitiesFromModel(
90
-                    $controller->getModelVersionInfo()->loadModel($model_name),
91
-                    $request
92
-                )
93
-            );
94
-        } catch (Exception $e) {
95
-            return $controller->sendResponse($e);
96
-        }
97
-    }
98
-
99
-
100
-
101
-    /**
102
-     * Prepares and returns schema for any OPTIONS request.
103
-     *
104
-     * @param string $version    The API endpoint version being used.
105
-     * @param string $model_name Something like `Event` or `Registration`
106
-     * @return array
107
-     */
108
-    public static function handleSchemaRequest($version, $model_name)
109
-    {
110
-        $controller = new Read();
111
-        try {
112
-            $controller->setRequestedVersion($version);
113
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
114
-                return array();
115
-            }
116
-            //get the model for this version
117
-            $model = $controller->getModelVersionInfo()->loadModel($model_name);
118
-            $model_schema = new JsonModelSchema($model);
119
-            return $model_schema->getModelSchemaForRelations(
120
-                $controller->getModelVersionInfo()->relationSettings($model),
121
-                $controller->customizeSchemaForRestResponse(
122
-                    $model,
123
-                    $model_schema->getModelSchemaForFields(
124
-                        $controller->getModelVersionInfo()->fieldsOnModelInThisVersion($model),
125
-                        $model_schema->getInitialSchemaStructure()
126
-                    )
127
-                )
128
-            );
129
-        } catch (Exception $e) {
130
-            return array();
131
-        }
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * This loops through each field in the given schema for the model and does the following:
138
-     * - add any extra fields that are REST API specific and related to existing fields.
139
-     * - transform default values into the correct format for a REST API response.
140
-     *
141
-     * @param EEM_Base $model
142
-     * @param array     $schema
143
-     * @return array  The final schema.
144
-     */
145
-    protected function customizeSchemaForRestResponse(EEM_Base $model, array $schema)
146
-    {
147
-        foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field) {
148
-            $schema = $this->translateDefaultsForRestResponse(
149
-                $field_name,
150
-                $field,
151
-                $this->maybeAddExtraFieldsToSchema($field_name, $field, $schema)
152
-            );
153
-        }
154
-        return $schema;
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
161
-     * response.
162
-     *
163
-     * @param                      $field_name
164
-     * @param EE_Model_Field_Base $field
165
-     * @param array                $schema
166
-     * @return array
167
-     * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
168
-     * did, let's know about it ASAP, so let the exception bubble up)
169
-     */
170
-    protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema)
171
-    {
172
-        if (isset($schema['properties'][$field_name]['default'])) {
173
-            if (is_array($schema['properties'][$field_name]['default'])) {
174
-                foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) {
175
-                    if ($default_key === 'raw') {
176
-                        $schema['properties'][$field_name]['default'][$default_key] =
177
-                            ModelDataTranslator::prepareFieldValueForJson(
178
-                                $field,
179
-                                $default_value,
180
-                                $this->getModelVersionInfo()->requestedVersion()
181
-                            );
182
-                    }
183
-                }
184
-            } else {
185
-                $schema['properties'][$field_name]['default'] = ModelDataTranslator::prepareFieldValueForJson(
186
-                    $field,
187
-                    $schema['properties'][$field_name]['default'],
188
-                    $this->getModelVersionInfo()->requestedVersion()
189
-                );
190
-            }
191
-        }
192
-        return $schema;
193
-    }
194
-
195
-
196
-
197
-    /**
198
-     * Adds additional fields to the schema
199
-     * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
200
-     * needs to be added to the schema.
201
-     *
202
-     * @param                      $field_name
203
-     * @param EE_Model_Field_Base $field
204
-     * @param array                $schema
205
-     * @return array
206
-     */
207
-    protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema)
208
-    {
209
-        if ($field instanceof EE_Datetime_Field) {
210
-            $schema['properties'][$field_name . '_gmt'] = $field->getSchema();
211
-            //modify the description
212
-            $schema['properties'][$field_name . '_gmt']['description'] = sprintf(
213
-                esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
214
-                $field->get_nicename()
215
-            );
216
-        }
217
-        return $schema;
218
-    }
219
-
220
-
221
-
222
-    /**
223
-     * Used to figure out the route from the request when a `WP_REST_Request` object is not available
224
-     *
225
-     * @return string
226
-     */
227
-    protected function getRouteFromRequest()
228
-    {
229
-        if (isset($GLOBALS['wp'])
230
-            && $GLOBALS['wp'] instanceof \WP
231
-            && isset($GLOBALS['wp']->query_vars['rest_route'])
232
-        ) {
233
-            return $GLOBALS['wp']->query_vars['rest_route'];
234
-        } else {
235
-            return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
236
-        }
237
-    }
238
-
239
-
240
-
241
-    /**
242
-     * Gets a single entity related to the model indicated in the path and its id
243
-
244
-     *
64
+	 * @param string           $version
65
+	 * @param string           $model_name
66
+	 * @return \WP_REST_Response|WP_Error
67
+	 */
68
+	public static function handleRequestGetAll(WP_REST_Request $request, $version, $model_name)
69
+	{
70
+		$controller = new Read();
71
+		try {
72
+			$controller->setRequestedVersion($version);
73
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
74
+				return $controller->sendResponse(
75
+					new WP_Error(
76
+						'endpoint_parsing_error',
77
+						sprintf(
78
+							__(
79
+								'There is no model for endpoint %s. Please contact event espresso support',
80
+								'event_espresso'
81
+							),
82
+							$model_name
83
+						)
84
+					)
85
+				);
86
+			}
87
+			return $controller->sendResponse(
88
+				$controller->getEntitiesFromModel(
89
+					$controller->getModelVersionInfo()->loadModel($model_name),
90
+					$request
91
+				)
92
+			);
93
+		} catch (Exception $e) {
94
+			return $controller->sendResponse($e);
95
+		}
96
+	}
97
+
98
+
99
+
100
+	/**
101
+	 * Prepares and returns schema for any OPTIONS request.
102
+	 *
103
+	 * @param string $version    The API endpoint version being used.
104
+	 * @param string $model_name Something like `Event` or `Registration`
105
+	 * @return array
106
+	 */
107
+	public static function handleSchemaRequest($version, $model_name)
108
+	{
109
+		$controller = new Read();
110
+		try {
111
+			$controller->setRequestedVersion($version);
112
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
113
+				return array();
114
+			}
115
+			//get the model for this version
116
+			$model = $controller->getModelVersionInfo()->loadModel($model_name);
117
+			$model_schema = new JsonModelSchema($model);
118
+			return $model_schema->getModelSchemaForRelations(
119
+				$controller->getModelVersionInfo()->relationSettings($model),
120
+				$controller->customizeSchemaForRestResponse(
121
+					$model,
122
+					$model_schema->getModelSchemaForFields(
123
+						$controller->getModelVersionInfo()->fieldsOnModelInThisVersion($model),
124
+						$model_schema->getInitialSchemaStructure()
125
+					)
126
+				)
127
+			);
128
+		} catch (Exception $e) {
129
+			return array();
130
+		}
131
+	}
132
+
133
+
134
+
135
+	/**
136
+	 * This loops through each field in the given schema for the model and does the following:
137
+	 * - add any extra fields that are REST API specific and related to existing fields.
138
+	 * - transform default values into the correct format for a REST API response.
139
+	 *
140
+	 * @param EEM_Base $model
141
+	 * @param array     $schema
142
+	 * @return array  The final schema.
143
+	 */
144
+	protected function customizeSchemaForRestResponse(EEM_Base $model, array $schema)
145
+	{
146
+		foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field) {
147
+			$schema = $this->translateDefaultsForRestResponse(
148
+				$field_name,
149
+				$field,
150
+				$this->maybeAddExtraFieldsToSchema($field_name, $field, $schema)
151
+			);
152
+		}
153
+		return $schema;
154
+	}
155
+
156
+
157
+
158
+	/**
159
+	 * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
160
+	 * response.
161
+	 *
162
+	 * @param                      $field_name
163
+	 * @param EE_Model_Field_Base $field
164
+	 * @param array                $schema
165
+	 * @return array
166
+	 * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
167
+	 * did, let's know about it ASAP, so let the exception bubble up)
168
+	 */
169
+	protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema)
170
+	{
171
+		if (isset($schema['properties'][$field_name]['default'])) {
172
+			if (is_array($schema['properties'][$field_name]['default'])) {
173
+				foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) {
174
+					if ($default_key === 'raw') {
175
+						$schema['properties'][$field_name]['default'][$default_key] =
176
+							ModelDataTranslator::prepareFieldValueForJson(
177
+								$field,
178
+								$default_value,
179
+								$this->getModelVersionInfo()->requestedVersion()
180
+							);
181
+					}
182
+				}
183
+			} else {
184
+				$schema['properties'][$field_name]['default'] = ModelDataTranslator::prepareFieldValueForJson(
185
+					$field,
186
+					$schema['properties'][$field_name]['default'],
187
+					$this->getModelVersionInfo()->requestedVersion()
188
+				);
189
+			}
190
+		}
191
+		return $schema;
192
+	}
193
+
194
+
195
+
196
+	/**
197
+	 * Adds additional fields to the schema
198
+	 * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
199
+	 * needs to be added to the schema.
200
+	 *
201
+	 * @param                      $field_name
202
+	 * @param EE_Model_Field_Base $field
203
+	 * @param array                $schema
204
+	 * @return array
205
+	 */
206
+	protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema)
207
+	{
208
+		if ($field instanceof EE_Datetime_Field) {
209
+			$schema['properties'][$field_name . '_gmt'] = $field->getSchema();
210
+			//modify the description
211
+			$schema['properties'][$field_name . '_gmt']['description'] = sprintf(
212
+				esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
213
+				$field->get_nicename()
214
+			);
215
+		}
216
+		return $schema;
217
+	}
218
+
219
+
220
+
221
+	/**
222
+	 * Used to figure out the route from the request when a `WP_REST_Request` object is not available
223
+	 *
224
+	 * @return string
225
+	 */
226
+	protected function getRouteFromRequest()
227
+	{
228
+		if (isset($GLOBALS['wp'])
229
+			&& $GLOBALS['wp'] instanceof \WP
230
+			&& isset($GLOBALS['wp']->query_vars['rest_route'])
231
+		) {
232
+			return $GLOBALS['wp']->query_vars['rest_route'];
233
+		} else {
234
+			return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
235
+		}
236
+	}
237
+
238
+
239
+
240
+	/**
241
+	 * Gets a single entity related to the model indicated in the path and its id
242
+	 *
245 243
 *@param WP_REST_Request $request
246
-     * @param string           $version
247
-     * @param string           $model_name
248
-     * @return \WP_REST_Response|WP_Error
249
-     */
250
-    public static function handleRequestGetOne(WP_REST_Request $request, $version, $model_name)
251
-    {
252
-        $controller = new Read();
253
-        try {
254
-            $controller->setRequestedVersion($version);
255
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
256
-                return $controller->sendResponse(
257
-                    new WP_Error(
258
-                        'endpoint_parsing_error',
259
-                        sprintf(
260
-                            __(
261
-                                'There is no model for endpoint %s. Please contact event espresso support',
262
-                                'event_espresso'
263
-                            ),
264
-                            $model_name
265
-                        )
266
-                    )
267
-                );
268
-            }
269
-            return $controller->sendResponse(
270
-                $controller->getEntityFromModel(
271
-                    $controller->getModelVersionInfo()->loadModel($model_name),
272
-                    $request
273
-                )
274
-            );
275
-        } catch (Exception $e) {
276
-            return $controller->sendResponse($e);
277
-        }
278
-    }
279
-
280
-
281
-
282
-    /**
283
-     * Gets all the related entities (or if its a belongs-to relation just the one)
284
-     * to the item with the given id
285
-
286
-     *
244
+	 * @param string           $version
245
+	 * @param string           $model_name
246
+	 * @return \WP_REST_Response|WP_Error
247
+	 */
248
+	public static function handleRequestGetOne(WP_REST_Request $request, $version, $model_name)
249
+	{
250
+		$controller = new Read();
251
+		try {
252
+			$controller->setRequestedVersion($version);
253
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
254
+				return $controller->sendResponse(
255
+					new WP_Error(
256
+						'endpoint_parsing_error',
257
+						sprintf(
258
+							__(
259
+								'There is no model for endpoint %s. Please contact event espresso support',
260
+								'event_espresso'
261
+							),
262
+							$model_name
263
+						)
264
+					)
265
+				);
266
+			}
267
+			return $controller->sendResponse(
268
+				$controller->getEntityFromModel(
269
+					$controller->getModelVersionInfo()->loadModel($model_name),
270
+					$request
271
+				)
272
+			);
273
+		} catch (Exception $e) {
274
+			return $controller->sendResponse($e);
275
+		}
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * Gets all the related entities (or if its a belongs-to relation just the one)
282
+	 * to the item with the given id
283
+	 *
287 284
 *@param WP_REST_Request $request
288
-     * @param string           $version
289
-     * @param string           $model_name
290
-     * @param string           $related_model_name
291
-     * @return \WP_REST_Response|WP_Error
292
-     */
293
-    public static function handleRequestGetRelated(
294
-        WP_REST_Request $request,
295
-        $version,
296
-        $model_name,
297
-        $related_model_name
298
-    ) {
299
-        $controller = new Read();
300
-        try {
301
-            $controller->setRequestedVersion($version);
302
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
303
-                return $controller->sendResponse(
304
-                    new WP_Error(
305
-                        'endpoint_parsing_error',
306
-                        sprintf(
307
-                            __(
308
-                                'There is no model for endpoint %s. Please contact event espresso support',
309
-                                'event_espresso'
310
-                            ),
311
-                            $model_name
312
-                        )
313
-                    )
314
-                );
315
-            }
316
-            $main_model = $controller->getModelVersionInfo()->loadModel($model_name);
317
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
318
-                return $controller->sendResponse(
319
-                    new WP_Error(
320
-                        'endpoint_parsing_error',
321
-                        sprintf(
322
-                            __(
323
-                                'There is no model for endpoint %s. Please contact event espresso support',
324
-                                'event_espresso'
325
-                            ),
326
-                            $related_model_name
327
-                        )
328
-                    )
329
-                );
330
-            }
331
-            return $controller->sendResponse(
332
-                $controller->getEntitiesFromRelation(
333
-                    $request->get_param('id'),
334
-                    $main_model->related_settings_for($related_model_name),
335
-                    $request
336
-                )
337
-            );
338
-        } catch (Exception $e) {
339
-            return $controller->sendResponse($e);
340
-        }
341
-    }
342
-
343
-
344
-
345
-    /**
346
-     * Gets a collection for the given model and filters
347
-
348
-     *
285
+	 * @param string           $version
286
+	 * @param string           $model_name
287
+	 * @param string           $related_model_name
288
+	 * @return \WP_REST_Response|WP_Error
289
+	 */
290
+	public static function handleRequestGetRelated(
291
+		WP_REST_Request $request,
292
+		$version,
293
+		$model_name,
294
+		$related_model_name
295
+	) {
296
+		$controller = new Read();
297
+		try {
298
+			$controller->setRequestedVersion($version);
299
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
300
+				return $controller->sendResponse(
301
+					new WP_Error(
302
+						'endpoint_parsing_error',
303
+						sprintf(
304
+							__(
305
+								'There is no model for endpoint %s. Please contact event espresso support',
306
+								'event_espresso'
307
+							),
308
+							$model_name
309
+						)
310
+					)
311
+				);
312
+			}
313
+			$main_model = $controller->getModelVersionInfo()->loadModel($model_name);
314
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
315
+				return $controller->sendResponse(
316
+					new WP_Error(
317
+						'endpoint_parsing_error',
318
+						sprintf(
319
+							__(
320
+								'There is no model for endpoint %s. Please contact event espresso support',
321
+								'event_espresso'
322
+							),
323
+							$related_model_name
324
+						)
325
+					)
326
+				);
327
+			}
328
+			return $controller->sendResponse(
329
+				$controller->getEntitiesFromRelation(
330
+					$request->get_param('id'),
331
+					$main_model->related_settings_for($related_model_name),
332
+					$request
333
+				)
334
+			);
335
+		} catch (Exception $e) {
336
+			return $controller->sendResponse($e);
337
+		}
338
+	}
339
+
340
+
341
+
342
+	/**
343
+	 * Gets a collection for the given model and filters
344
+	 *
349 345
 *@param EEM_Base        $model
350
-     * @param WP_REST_Request $request
351
-     * @return array|WP_Error
352
-     */
353
-    public function getEntitiesFromModel($model, $request)
354
-    {
355
-        $query_params = $this->createModelQueryParams($model, $request->get_params());
356
-        if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
357
-            $model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
358
-            return new WP_Error(
359
-                sprintf('rest_%s_cannot_list', $model_name_plural),
360
-                sprintf(
361
-                    __('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
362
-                    $model_name_plural,
363
-                    Capabilities::getMissingPermissionsString($model, $query_params['caps'])
364
-                ),
365
-                array('status' => 403)
366
-            );
367
-        }
368
-        if (! $request->get_header('no_rest_headers')) {
369
-            $this->setHeadersFromQueryParams($model, $query_params);
370
-        }
371
-        /** @type array $results */
372
-        $results = $model->get_all_wpdb_results($query_params);
373
-        $nice_results = array();
374
-        foreach ($results as $result) {
375
-            $nice_results[] = $this->createEntityFromWpdbResult(
376
-                $model,
377
-                $result,
378
-                $request
379
-            );
380
-        }
381
-        return $nice_results;
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * Gets the collection for given relation object
388
-     * The same as Read::get_entities_from_model(), except if the relation
389
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
390
-     * the join-model-object into the results
391
-     *
392
-     * @param array                   $primary_model_query_params query params for finding the item from which
393
-     *                                                            relations will be based
394
-     * @param \EE_Model_Relation_Base $relation
395
-     * @param WP_REST_Request        $request
396
-     * @return WP_Error|array
397
-     * @throws RestException
398
-     */
399
-    protected function getEntitiesFromRelationUsingModelQueryParams($primary_model_query_params, $relation, $request)
400
-    {
401
-        $context = $this->validateContext($request->get_param('caps'));
402
-        $model = $relation->get_this_model();
403
-        $related_model = $relation->get_other_model();
404
-        if (! isset($primary_model_query_params[0])) {
405
-            $primary_model_query_params[0] = array();
406
-        }
407
-        //check if they can access the 1st model object
408
-        $primary_model_query_params = array(
409
-            0       => $primary_model_query_params[0],
410
-            'limit' => 1,
411
-        );
412
-        if ($model instanceof \EEM_Soft_Delete_Base) {
413
-            $primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included(
414
-                $primary_model_query_params
415
-            );
416
-        }
417
-        $restricted_query_params = $primary_model_query_params;
418
-        $restricted_query_params['caps'] = $context;
419
-        $this->setDebugInfo('main model query params', $restricted_query_params);
420
-        $this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context));
421
-        if (! (
422
-            Capabilities::currentUserHasPartialAccessTo($related_model, $context)
423
-            && $model->exists($restricted_query_params)
424
-        )
425
-        ) {
426
-            if ($relation instanceof EE_Belongs_To_Relation) {
427
-                $related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
428
-            } else {
429
-                $related_model_name_maybe_plural = EEH_Inflector::pluralize_and_lower(
430
-                    $related_model->get_this_model_name()
431
-                );
432
-            }
433
-            return new WP_Error(
434
-                sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
435
-                sprintf(
436
-                    __(
437
-                        'Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
438
-                        'event_espresso'
439
-                    ),
440
-                    $related_model_name_maybe_plural,
441
-                    $relation->get_this_model()->get_this_model_name(),
442
-                    implode(
443
-                        ',',
444
-                        array_keys(
445
-                            Capabilities::getMissingPermissions($related_model, $context)
446
-                        )
447
-                    )
448
-                ),
449
-                array('status' => 403)
450
-            );
451
-        }
452
-        $query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params());
453
-        foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
454
-            $query_params[0][$relation->get_this_model()->get_this_model_name()
455
-                             . '.'
456
-                             . $where_condition_key] = $where_condition_value;
457
-        }
458
-        $query_params['default_where_conditions'] = 'none';
459
-        $query_params['caps'] = $context;
460
-        if (! $request->get_header('no_rest_headers')) {
461
-            $this->setHeadersFromQueryParams($relation->get_other_model(), $query_params);
462
-        }
463
-        /** @type array $results */
464
-        $results = $relation->get_other_model()->get_all_wpdb_results($query_params);
465
-        $nice_results = array();
466
-        foreach ($results as $result) {
467
-            $nice_result = $this->createEntityFromWpdbResult(
468
-                $relation->get_other_model(),
469
-                $result,
470
-                $request
471
-            );
472
-            if ($relation instanceof \EE_HABTM_Relation) {
473
-                //put the unusual stuff (properties from the HABTM relation) first, and make sure
474
-                //if there are conflicts we prefer the properties from the main model
475
-                $join_model_result = $this->createEntityFromWpdbResult(
476
-                    $relation->get_join_model(),
477
-                    $result,
478
-                    $request
479
-                );
480
-                $joined_result = array_merge($nice_result, $join_model_result);
481
-                //but keep the meta stuff from the main model
482
-                if (isset($nice_result['meta'])) {
483
-                    $joined_result['meta'] = $nice_result['meta'];
484
-                }
485
-                $nice_result = $joined_result;
486
-            }
487
-            $nice_results[] = $nice_result;
488
-        }
489
-        if ($relation instanceof EE_Belongs_To_Relation) {
490
-            return array_shift($nice_results);
491
-        } else {
492
-            return $nice_results;
493
-        }
494
-    }
495
-
496
-
497
-
498
-    /**
499
-     * Gets the collection for given relation object
500
-     * The same as Read::get_entities_from_model(), except if the relation
501
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
502
-     * the join-model-object into the results
503
-
504
-     *
346
+	 * @param WP_REST_Request $request
347
+	 * @return array|WP_Error
348
+	 */
349
+	public function getEntitiesFromModel($model, $request)
350
+	{
351
+		$query_params = $this->createModelQueryParams($model, $request->get_params());
352
+		if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
353
+			$model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
354
+			return new WP_Error(
355
+				sprintf('rest_%s_cannot_list', $model_name_plural),
356
+				sprintf(
357
+					__('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
358
+					$model_name_plural,
359
+					Capabilities::getMissingPermissionsString($model, $query_params['caps'])
360
+				),
361
+				array('status' => 403)
362
+			);
363
+		}
364
+		if (! $request->get_header('no_rest_headers')) {
365
+			$this->setHeadersFromQueryParams($model, $query_params);
366
+		}
367
+		/** @type array $results */
368
+		$results = $model->get_all_wpdb_results($query_params);
369
+		$nice_results = array();
370
+		foreach ($results as $result) {
371
+			$nice_results[] = $this->createEntityFromWpdbResult(
372
+				$model,
373
+				$result,
374
+				$request
375
+			);
376
+		}
377
+		return $nice_results;
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * Gets the collection for given relation object
384
+	 * The same as Read::get_entities_from_model(), except if the relation
385
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
386
+	 * the join-model-object into the results
387
+	 *
388
+	 * @param array                   $primary_model_query_params query params for finding the item from which
389
+	 *                                                            relations will be based
390
+	 * @param \EE_Model_Relation_Base $relation
391
+	 * @param WP_REST_Request        $request
392
+	 * @return WP_Error|array
393
+	 * @throws RestException
394
+	 */
395
+	protected function getEntitiesFromRelationUsingModelQueryParams($primary_model_query_params, $relation, $request)
396
+	{
397
+		$context = $this->validateContext($request->get_param('caps'));
398
+		$model = $relation->get_this_model();
399
+		$related_model = $relation->get_other_model();
400
+		if (! isset($primary_model_query_params[0])) {
401
+			$primary_model_query_params[0] = array();
402
+		}
403
+		//check if they can access the 1st model object
404
+		$primary_model_query_params = array(
405
+			0       => $primary_model_query_params[0],
406
+			'limit' => 1,
407
+		);
408
+		if ($model instanceof \EEM_Soft_Delete_Base) {
409
+			$primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included(
410
+				$primary_model_query_params
411
+			);
412
+		}
413
+		$restricted_query_params = $primary_model_query_params;
414
+		$restricted_query_params['caps'] = $context;
415
+		$this->setDebugInfo('main model query params', $restricted_query_params);
416
+		$this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context));
417
+		if (! (
418
+			Capabilities::currentUserHasPartialAccessTo($related_model, $context)
419
+			&& $model->exists($restricted_query_params)
420
+		)
421
+		) {
422
+			if ($relation instanceof EE_Belongs_To_Relation) {
423
+				$related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
424
+			} else {
425
+				$related_model_name_maybe_plural = EEH_Inflector::pluralize_and_lower(
426
+					$related_model->get_this_model_name()
427
+				);
428
+			}
429
+			return new WP_Error(
430
+				sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
431
+				sprintf(
432
+					__(
433
+						'Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
434
+						'event_espresso'
435
+					),
436
+					$related_model_name_maybe_plural,
437
+					$relation->get_this_model()->get_this_model_name(),
438
+					implode(
439
+						',',
440
+						array_keys(
441
+							Capabilities::getMissingPermissions($related_model, $context)
442
+						)
443
+					)
444
+				),
445
+				array('status' => 403)
446
+			);
447
+		}
448
+		$query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params());
449
+		foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
450
+			$query_params[0][$relation->get_this_model()->get_this_model_name()
451
+							 . '.'
452
+							 . $where_condition_key] = $where_condition_value;
453
+		}
454
+		$query_params['default_where_conditions'] = 'none';
455
+		$query_params['caps'] = $context;
456
+		if (! $request->get_header('no_rest_headers')) {
457
+			$this->setHeadersFromQueryParams($relation->get_other_model(), $query_params);
458
+		}
459
+		/** @type array $results */
460
+		$results = $relation->get_other_model()->get_all_wpdb_results($query_params);
461
+		$nice_results = array();
462
+		foreach ($results as $result) {
463
+			$nice_result = $this->createEntityFromWpdbResult(
464
+				$relation->get_other_model(),
465
+				$result,
466
+				$request
467
+			);
468
+			if ($relation instanceof \EE_HABTM_Relation) {
469
+				//put the unusual stuff (properties from the HABTM relation) first, and make sure
470
+				//if there are conflicts we prefer the properties from the main model
471
+				$join_model_result = $this->createEntityFromWpdbResult(
472
+					$relation->get_join_model(),
473
+					$result,
474
+					$request
475
+				);
476
+				$joined_result = array_merge($nice_result, $join_model_result);
477
+				//but keep the meta stuff from the main model
478
+				if (isset($nice_result['meta'])) {
479
+					$joined_result['meta'] = $nice_result['meta'];
480
+				}
481
+				$nice_result = $joined_result;
482
+			}
483
+			$nice_results[] = $nice_result;
484
+		}
485
+		if ($relation instanceof EE_Belongs_To_Relation) {
486
+			return array_shift($nice_results);
487
+		} else {
488
+			return $nice_results;
489
+		}
490
+	}
491
+
492
+
493
+
494
+	/**
495
+	 * Gets the collection for given relation object
496
+	 * The same as Read::get_entities_from_model(), except if the relation
497
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
498
+	 * the join-model-object into the results
499
+	 *
505 500
 *@param string                  $id the ID of the thing we are fetching related stuff from
506
-     * @param \EE_Model_Relation_Base $relation
507
-     * @param WP_REST_Request        $request
508
-     * @return array|WP_Error
509
-     * @throws EE_Error
510
-     */
511
-    public function getEntitiesFromRelation($id, $relation, $request)
512
-    {
513
-        if (! $relation->get_this_model()->has_primary_key_field()) {
514
-            throw new EE_Error(
515
-                sprintf(
516
-                    __(
517
-                        // @codingStandardsIgnoreStart
518
-                        'Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
519
-                        // @codingStandardsIgnoreEnd
520
-                        'event_espresso'
521
-                    ),
522
-                    $relation->get_this_model()->get_this_model_name()
523
-                )
524
-            );
525
-        }
526
-        return $this->getEntitiesFromRelationUsingModelQueryParams(
527
-            array(
528
-                array(
529
-                    $relation->get_this_model()->primary_key_name() => $id,
530
-                ),
531
-            ),
532
-            $relation,
533
-            $request
534
-        );
535
-    }
536
-
537
-
538
-
539
-    /**
540
-     * Sets the headers that are based on the model and query params,
541
-     * like the total records. This should only be called on the original request
542
-     * from the client, not on subsequent internal
543
-     *
544
-     * @param EEM_Base $model
545
-     * @param array     $query_params
546
-     * @return void
547
-     */
548
-    protected function setHeadersFromQueryParams($model, $query_params)
549
-    {
550
-        $this->setDebugInfo('model query params', $query_params);
551
-        $this->setDebugInfo(
552
-            'missing caps',
553
-            Capabilities::getMissingPermissionsString($model, $query_params['caps'])
554
-        );
555
-        //normally the limit to a 2-part array, where the 2nd item is the limit
556
-        if (! isset($query_params['limit'])) {
557
-            $query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
558
-        }
559
-        if (is_array($query_params['limit'])) {
560
-            $limit_parts = $query_params['limit'];
561
-        } else {
562
-            $limit_parts = explode(',', $query_params['limit']);
563
-            if (count($limit_parts) == 1) {
564
-                $limit_parts = array(0, $limit_parts[0]);
565
-            }
566
-        }
567
-        //remove the group by and having parts of the query, as those will
568
-        //make the sql query return an array of values, instead of just a single value
569
-        unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
570
-        $count = $model->count($query_params, null, true);
571
-        $pages = $count / $limit_parts[1];
572
-        $this->setResponseHeader('Total', $count, false);
573
-        $this->setResponseHeader('PageSize', $limit_parts[1], false);
574
-        $this->setResponseHeader('TotalPages', ceil($pages), false);
575
-    }
576
-
577
-
578
-
579
-    /**
580
-     * Changes database results into REST API entities
581
-     *
582
-     * @param EEM_Base        $model
583
-     * @param array            $db_row     like results from $wpdb->get_results()
584
-     * @param WP_REST_Request $rest_request
585
-     * @param string           $deprecated no longer used
586
-     * @return array ready for being converted into json for sending to client
587
-     */
588
-    public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null)
589
-    {
590
-        if (! $rest_request instanceof WP_REST_Request) {
591
-            //ok so this was called in the old style, where the 3rd arg was
592
-            //$include, and the 4th arg was $context
593
-            //now setup the request just to avoid fatal errors, although we won't be able
594
-            //to truly make use of it because it's kinda devoid of info
595
-            $rest_request = new WP_REST_Request();
596
-            $rest_request->set_param('include', $rest_request);
597
-            $rest_request->set_param('caps', $deprecated);
598
-        }
599
-        if ($rest_request->get_param('caps') == null) {
600
-            $rest_request->set_param('caps', EEM_Base::caps_read);
601
-        }
602
-        $entity_array = $this->createBareEntityFromWpdbResults($model, $db_row);
603
-        $entity_array = $this->addExtraFields($model, $db_row, $entity_array);
604
-        $entity_array['_links'] = $this->getEntityLinks($model, $db_row, $entity_array);
605
-        $entity_array['_calculated_fields'] = $this->getEntityCalculations($model, $db_row, $rest_request);
606
-        $entity_array = apply_filters(
607
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
608
-            $entity_array,
609
-            $model,
610
-            $rest_request->get_param('caps'),
611
-            $rest_request,
612
-            $this
613
-        );
614
-        $entity_array = $this->includeRequestedModels($model, $rest_request, $entity_array, $db_row);
615
-        $entity_array = apply_filters(
616
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
617
-            $entity_array,
618
-            $model,
619
-            $rest_request->get_param('caps'),
620
-            $rest_request,
621
-            $this
622
-        );
623
-        $result_without_inaccessible_fields = Capabilities::filterOutInaccessibleEntityFields(
624
-            $entity_array,
625
-            $model,
626
-            $rest_request->get_param('caps'),
627
-            $this->getModelVersionInfo(),
628
-            $model->get_index_primary_key_string(
629
-                $model->deduce_fields_n_values_from_cols_n_values($db_row)
630
-            )
631
-        );
632
-        $this->setDebugInfo(
633
-            'inaccessible fields',
634
-            array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
635
-        );
636
-        return apply_filters(
637
-            'FHEE__Read__create_entity_from_wpdb_results__entity_return',
638
-            $result_without_inaccessible_fields,
639
-            $model,
640
-            $rest_request->get_param('caps')
641
-        );
642
-    }
643
-
644
-
645
-
646
-    /**
647
-     * Creates a REST entity array (JSON object we're going to return in the response, but
648
-     * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
649
-     * from $wpdb->get_row( $sql, ARRAY_A)
650
-     *
651
-     * @param EEM_Base $model
652
-     * @param array     $db_row
653
-     * @return array entity mostly ready for converting to JSON and sending in the response
654
-     *
655
-     */
656
-    protected function createBareEntityFromWpdbResults(EEM_Base $model, $db_row)
657
-    {
658
-        $result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
659
-        $result = array_intersect_key(
660
-            $result,
661
-            $this->getModelVersionInfo()->fieldsOnModelInThisVersion($model)
662
-        );
663
-        //if this is a CPT, we need to set the global $post to it,
664
-        //otherwise shortcodes etc won't work properly while rendering it
665
-        if ($model instanceof \EEM_CPT_Base) {
666
-            $do_chevy_shuffle = true;
667
-        } else {
668
-            $do_chevy_shuffle = false;
669
-        }
670
-        if ($do_chevy_shuffle) {
671
-            global $post;
672
-            $old_post = $post;
673
-            $post = get_post($result[$model->primary_key_name()]);
674
-            if (! $post instanceof \WP_Post) {
675
-                //well that's weird, because $result is what we JUST fetched from the database
676
-                throw new RestException(
677
-                    'error_fetching_post_from_database_results',
678
-                    esc_html__(
679
-                        'An item was retrieved from the database but it\'s not a WP_Post like it should be.',
680
-                        'event_espresso'
681
-                    )
682
-                );
683
-            }
684
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
685
-            $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
686
-                $model_object_classname,
687
-                $result,
688
-                false,
689
-                false
690
-            );
691
-        }
692
-        foreach ($result as $field_name => $field_value) {
693
-            $field_obj = $model->field_settings_for($field_name);
694
-            if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) {
695
-                unset($result[$field_name]);
696
-            } elseif ($this->isSubclassOfOne(
697
-                $field_obj,
698
-                $this->getModelVersionInfo()->fieldsThatHaveRenderedFormat()
699
-            )
700
-            ) {
701
-                $result[$field_name] = array(
702
-                    'raw'      => $this->prepareFieldObjValueForJson($field_obj, $field_value),
703
-                    'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
704
-                );
705
-            } elseif ($this->isSubclassOfOne(
706
-                $field_obj,
707
-                $this->getModelVersionInfo()->fieldsThatHavePrettyFormat()
708
-            )
709
-            ) {
710
-                $result[$field_name] = array(
711
-                    'raw'    => $this->prepareFieldObjValueForJson($field_obj, $field_value),
712
-                    'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
713
-                );
714
-            } elseif ($field_obj instanceof \EE_Datetime_Field) {
715
-                $field_value = $field_obj->prepare_for_set_from_db($field_value);
716
-                $timezone = $field_value->getTimezone();
717
-                $field_value->setTimezone(new \DateTimeZone('UTC'));
718
-                $result[$field_name . '_gmt'] = ModelDataTranslator::prepareFieldValuesForJson(
719
-                    $field_obj,
720
-                    $field_value,
721
-                    $this->getModelVersionInfo()->requestedVersion()
722
-                );
723
-                $field_value->setTimezone($timezone);
724
-                $result[$field_name] = ModelDataTranslator::prepareFieldValuesForJson(
725
-                    $field_obj,
726
-                    $field_value,
727
-                    $this->getModelVersionInfo()->requestedVersion()
728
-                );
729
-            } else {
730
-                $result[$field_name] = $this->prepareFieldObjValueForJson($field_obj, $field_value);
731
-            }
732
-        }
733
-        if ($do_chevy_shuffle) {
734
-            $post = $old_post;
735
-        }
736
-        return $result;
737
-    }
738
-
739
-
740
-
741
-    /**
742
-     * Takes a value all the way from the DB representation, to the model object's representation, to the
743
-     * user-facing PHP representation, to the REST API representation. (Assumes you've already taken from the DB
744
-     * representation using $field_obj->prepare_for_set_from_db())
745
-     *
746
-     * @param EE_Model_Field_Base $field_obj
747
-     * @param mixed $value as it's stored on a model object
748
-     * @param string $format valid values are 'normal' (default), 'pretty', 'datetime_obj'
749
-     * @return mixed
750
-     * @throws ObjectDetectedException if $value contains a PHP object
751
-     */
752
-    protected function prepareFieldObjValueForJson(EE_Model_Field_Base $field_obj, $value, $format = 'normal')
753
-    {
754
-        $value = $field_obj->prepare_for_set_from_db($value);
755
-        switch ($format) {
756
-            case 'pretty':
757
-                $value = $field_obj->prepare_for_pretty_echoing($value);
758
-                break;
759
-            case 'normal':
760
-            default:
761
-                $value = $field_obj->prepare_for_get($value);
762
-                break;
763
-        }
764
-        return ModelDataTranslator::prepareFieldValuesForJson(
765
-            $field_obj,
766
-            $value,
767
-            $this->getModelVersionInfo()->requestedVersion()
768
-        );
769
-    }
770
-
771
-
772
-
773
-    /**
774
-     * Adds a few extra fields to the entity response
775
-     *
776
-     * @param EEM_Base $model
777
-     * @param array     $db_row
778
-     * @param array     $entity_array
779
-     * @return array modified entity
780
-     */
781
-    protected function addExtraFields(EEM_Base $model, $db_row, $entity_array)
782
-    {
783
-        if ($model instanceof EEM_CPT_Base) {
784
-            $entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
785
-        }
786
-        return $entity_array;
787
-    }
788
-
789
-
790
-
791
-    /**
792
-     * Gets links we want to add to the response
793
-     *
794
-     * @global \WP_REST_Server $wp_rest_server
795
-     * @param EEM_Base        $model
796
-     * @param array            $db_row
797
-     * @param array            $entity_array
798
-     * @return array the _links item in the entity
799
-     */
800
-    protected function getEntityLinks($model, $db_row, $entity_array)
801
-    {
802
-        //add basic links
803
-        $links = array();
804
-        if ($model->has_primary_key_field()) {
805
-            $links['self'] = array(
806
-                array(
807
-                    'href' => $this->getVersionedLinkTo(
808
-                        EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
809
-                        . '/'
810
-                        . $entity_array[$model->primary_key_name()]
811
-                    ),
812
-                ),
813
-            );
814
-        }
815
-        $links['collection'] = array(
816
-            array(
817
-                'href' => $this->getVersionedLinkTo(
818
-                    EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
819
-                ),
820
-            ),
821
-        );
822
-        //add links to related models
823
-        if ($model->has_primary_key_field()) {
824
-            foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) {
825
-                $related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj);
826
-                $links[EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
827
-                    array(
828
-                        'href'   => $this->getVersionedLinkTo(
829
-                            EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
830
-                            . '/'
831
-                            . $entity_array[$model->primary_key_name()]
832
-                            . '/'
833
-                            . $related_model_part
834
-                        ),
835
-                        'single' => $relation_obj instanceof EE_Belongs_To_Relation ? true : false,
836
-                    ),
837
-                );
838
-            }
839
-        }
840
-        return $links;
841
-    }
842
-
843
-
844
-
845
-    /**
846
-     * Adds the included models indicated in the request to the entity provided
847
-     *
848
-     * @param EEM_Base        $model
849
-     * @param WP_REST_Request $rest_request
850
-     * @param array            $entity_array
851
-     * @param array            $db_row
852
-     * @return array the modified entity
853
-     */
854
-    protected function includeRequestedModels(
855
-        EEM_Base $model,
856
-        WP_REST_Request $rest_request,
857
-        $entity_array,
858
-        $db_row = array()
859
-    ) {
860
-        //if $db_row not included, hope the entity array has what we need
861
-        if (! $db_row) {
862
-            $db_row = $entity_array;
863
-        }
864
-        $includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), '');
865
-        $includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model);
866
-        //if they passed in * or didn't specify any includes, return everything
867
-        if (! in_array('*', $includes_for_this_model)
868
-            && ! empty($includes_for_this_model)
869
-        ) {
870
-            if ($model->has_primary_key_field()) {
871
-                //always include the primary key. ya just gotta know that at least
872
-                $includes_for_this_model[] = $model->primary_key_name();
873
-            }
874
-            if ($this->explodeAndGetItemsPrefixedWith($rest_request->get_param('calculate'), '')) {
875
-                $includes_for_this_model[] = '_calculated_fields';
876
-            }
877
-            $entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
878
-        }
879
-        $relation_settings = $this->getModelVersionInfo()->relationSettings($model);
880
-        foreach ($relation_settings as $relation_name => $relation_obj) {
881
-            $related_fields_to_include = $this->explodeAndGetItemsPrefixedWith(
882
-                $rest_request->get_param('include'),
883
-                $relation_name
884
-            );
885
-            $related_fields_to_calculate = $this->explodeAndGetItemsPrefixedWith(
886
-                $rest_request->get_param('calculate'),
887
-                $relation_name
888
-            );
889
-            //did they specify they wanted to include a related model, or
890
-            //specific fields from a related model?
891
-            //or did they specify to calculate a field from a related model?
892
-            if ($related_fields_to_include || $related_fields_to_calculate) {
893
-                //if so, we should include at least some part of the related model
894
-                $pretend_related_request = new WP_REST_Request();
895
-                $pretend_related_request->set_query_params(
896
-                    array(
897
-                        'caps'      => $rest_request->get_param('caps'),
898
-                        'include'   => $related_fields_to_include,
899
-                        'calculate' => $related_fields_to_calculate,
900
-                    )
901
-                );
902
-                $pretend_related_request->add_header('no_rest_headers', true);
903
-                $primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
904
-                    $model->get_index_primary_key_string(
905
-                        $model->deduce_fields_n_values_from_cols_n_values($db_row)
906
-                    )
907
-                );
908
-                $related_results = $this->getEntitiesFromRelationUsingModelQueryParams(
909
-                    $primary_model_query_params,
910
-                    $relation_obj,
911
-                    $pretend_related_request
912
-                );
913
-                $entity_array[Read::getRelatedEntityName($relation_name, $relation_obj)] = $related_results
914
-                                                                                           instanceof
915
-                                                                                           WP_Error
916
-                    ? null
917
-                    : $related_results;
918
-            }
919
-        }
920
-        return $entity_array;
921
-    }
922
-
923
-
924
-
925
-    /**
926
-     * Returns a new array with all the names of models removed. Eg
927
-     * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
928
-     *
929
-     * @param array $arr
930
-     * @return array
931
-     */
932
-    private function removeModelNamesFromArray($arr)
933
-    {
934
-        return array_diff($arr, array_keys(EE_Registry::instance()->non_abstract_db_models));
935
-    }
936
-
937
-
938
-
939
-    /**
940
-     * Gets the calculated fields for the response
941
-     *
942
-     * @param EEM_Base        $model
943
-     * @param array            $wpdb_row
944
-     * @param WP_REST_Request $rest_request
945
-     * @return \stdClass the _calculations item in the entity
946
-     * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
947
-     * did, let's know about it ASAP, so let the exception bubble up)
948
-     */
949
-    protected function getEntityCalculations($model, $wpdb_row, $rest_request)
950
-    {
951
-        $calculated_fields = $this->explodeAndGetItemsPrefixedWith(
952
-            $rest_request->get_param('calculate'),
953
-            ''
954
-        );
955
-        //note: setting calculate=* doesn't do anything
956
-        $calculated_fields_to_return = new \stdClass();
957
-        foreach ($calculated_fields as $field_to_calculate) {
958
-            try {
959
-                $calculated_fields_to_return->$field_to_calculate = ModelDataTranslator::prepareFieldValueForJson(
960
-                    null,
961
-                    $this->fields_calculator->retrieveCalculatedFieldValue(
962
-                        $model,
963
-                        $field_to_calculate,
964
-                        $wpdb_row,
965
-                        $rest_request,
966
-                        $this
967
-                    ),
968
-                    $this->getModelVersionInfo()->requestedVersion()
969
-                );
970
-            } catch (RestException $e) {
971
-                //if we don't have permission to read it, just leave it out. but let devs know about the problem
972
-                $this->setResponseHeader(
973
-                    'Notices-Field-Calculation-Errors['
974
-                    . $e->getStringCode()
975
-                    . ']['
976
-                    . $model->get_this_model_name()
977
-                    . ']['
978
-                    . $field_to_calculate
979
-                    . ']',
980
-                    $e->getMessage(),
981
-                    true
982
-                );
983
-            }
984
-        }
985
-        return $calculated_fields_to_return;
986
-    }
987
-
988
-
989
-
990
-    /**
991
-     * Gets the full URL to the resource, taking the requested version into account
992
-     *
993
-     * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
994
-     * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
995
-     */
996
-    public function getVersionedLinkTo($link_part_after_version_and_slash)
997
-    {
998
-        return rest_url(
999
-            EED_Core_Rest_Api::get_versioned_route_to(
1000
-                $link_part_after_version_and_slash,
1001
-                $this->getModelVersionInfo()->requestedVersion()
1002
-            )
1003
-        );
1004
-    }
1005
-
1006
-
1007
-
1008
-    /**
1009
-     * Gets the correct lowercase name for the relation in the API according
1010
-     * to the relation's type
1011
-     *
1012
-     * @param string                  $relation_name
1013
-     * @param \EE_Model_Relation_Base $relation_obj
1014
-     * @return string
1015
-     */
1016
-    public static function getRelatedEntityName($relation_name, $relation_obj)
1017
-    {
1018
-        if ($relation_obj instanceof EE_Belongs_To_Relation) {
1019
-            return strtolower($relation_name);
1020
-        } else {
1021
-            return EEH_Inflector::pluralize_and_lower($relation_name);
1022
-        }
1023
-    }
1024
-
1025
-
1026
-
1027
-    /**
1028
-     * Gets the one model object with the specified id for the specified model
1029
-     *
1030
-     * @param EEM_Base        $model
1031
-     * @param WP_REST_Request $request
1032
-     * @return array|WP_Error
1033
-     */
1034
-    public function getEntityFromModel($model, $request)
1035
-    {
1036
-        $context = $this->validateContext($request->get_param('caps'));
1037
-        return $this->getOneOrReportPermissionError($model, $request, $context);
1038
-    }
1039
-
1040
-
1041
-
1042
-    /**
1043
-     * If a context is provided which isn't valid, maybe it was added in a future
1044
-     * version so just treat it as a default read
1045
-     *
1046
-     * @param string $context
1047
-     * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1048
-     */
1049
-    public function validateContext($context)
1050
-    {
1051
-        if (! $context) {
1052
-            $context = EEM_Base::caps_read;
1053
-        }
1054
-        $valid_contexts = EEM_Base::valid_cap_contexts();
1055
-        if (in_array($context, $valid_contexts)) {
1056
-            return $context;
1057
-        } else {
1058
-            return EEM_Base::caps_read;
1059
-        }
1060
-    }
1061
-
1062
-
1063
-
1064
-    /**
1065
-     * Verifies the passed in value is an allowable default where conditions value.
1066
-     *
1067
-     * @param $default_query_params
1068
-     * @return string
1069
-     */
1070
-    public function validateDefaultQueryParams($default_query_params)
1071
-    {
1072
-        $valid_default_where_conditions_for_api_calls = array(
1073
-            EEM_Base::default_where_conditions_all,
1074
-            EEM_Base::default_where_conditions_minimum_all,
1075
-            EEM_Base::default_where_conditions_minimum_others,
1076
-        );
1077
-        if (! $default_query_params) {
1078
-            $default_query_params = EEM_Base::default_where_conditions_all;
1079
-        }
1080
-        if (in_array(
1081
-            $default_query_params,
1082
-            $valid_default_where_conditions_for_api_calls,
1083
-            true
1084
-        )) {
1085
-            return $default_query_params;
1086
-        } else {
1087
-            return EEM_Base::default_where_conditions_all;
1088
-        }
1089
-    }
1090
-
1091
-
1092
-
1093
-    /**
1094
-     * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1095
-     * Note: right now the query parameter keys for fields (and related fields)
1096
-     * can be left as-is, but it's quite possible this will change someday.
1097
-     * Also, this method's contents might be candidate for moving to Model_Data_Translator
1098
-     *
1099
-     * @param EEM_Base $model
1100
-     * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
1101
-     * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1102
-     *                                    that absolutely no results should be returned
1103
-     * @throws EE_Error
1104
-     * @throws RestException
1105
-     */
1106
-    public function createModelQueryParams($model, $query_parameters)
1107
-    {
1108
-        $model_query_params = array();
1109
-        if (isset($query_parameters['where'])) {
1110
-            $model_query_params[0] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1111
-                $query_parameters['where'],
1112
-                $model,
1113
-                $this->getModelVersionInfo()->requestedVersion()
1114
-            );
1115
-        }
1116
-        if (isset($query_parameters['order_by'])) {
1117
-            $order_by = $query_parameters['order_by'];
1118
-        } elseif (isset($query_parameters['orderby'])) {
1119
-            $order_by = $query_parameters['orderby'];
1120
-        } else {
1121
-            $order_by = null;
1122
-        }
1123
-        if ($order_by !== null) {
1124
-            if (is_array($order_by)) {
1125
-                $order_by = ModelDataTranslator::prepareFieldNamesInArrayKeysFromJson($order_by);
1126
-            } else {
1127
-                //it's a single item
1128
-                $order_by = ModelDataTranslator::prepareFieldNameFromJson($order_by);
1129
-            }
1130
-            $model_query_params['order_by'] = $order_by;
1131
-        }
1132
-        if (isset($query_parameters['group_by'])) {
1133
-            $group_by = $query_parameters['group_by'];
1134
-        } elseif (isset($query_parameters['groupby'])) {
1135
-            $group_by = $query_parameters['groupby'];
1136
-        } else {
1137
-            $group_by = array_keys($model->get_combined_primary_key_fields());
1138
-        }
1139
-        //make sure they're all real names
1140
-        if (is_array($group_by)) {
1141
-            $group_by = ModelDataTranslator::prepareFieldNamesFromJson($group_by);
1142
-        }
1143
-        if ($group_by !== null) {
1144
-            $model_query_params['group_by'] = $group_by;
1145
-        }
1146
-        if (isset($query_parameters['having'])) {
1147
-            $model_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1148
-                $query_parameters['having'],
1149
-                $model,
1150
-                $this->getModelVersionInfo()->requestedVersion()
1151
-            );
1152
-        }
1153
-        if (isset($query_parameters['order'])) {
1154
-            $model_query_params['order'] = $query_parameters['order'];
1155
-        }
1156
-        if (isset($query_parameters['mine'])) {
1157
-            $model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1158
-        }
1159
-        if (isset($query_parameters['limit'])) {
1160
-            //limit should be either a string like '23' or '23,43', or an array with two items in it
1161
-            if (! is_array($query_parameters['limit'])) {
1162
-                $limit_array = explode(',', (string)$query_parameters['limit']);
1163
-            } else {
1164
-                $limit_array = $query_parameters['limit'];
1165
-            }
1166
-            $sanitized_limit = array();
1167
-            foreach ($limit_array as $key => $limit_part) {
1168
-                if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1169
-                    throw new EE_Error(
1170
-                        sprintf(
1171
-                            __(
1172
-                                // @codingStandardsIgnoreStart
1173
-                                'An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
1174
-                                // @codingStandardsIgnoreEnd
1175
-                                'event_espresso'
1176
-                            ),
1177
-                            wp_json_encode($query_parameters['limit'])
1178
-                        )
1179
-                    );
1180
-                }
1181
-                $sanitized_limit[] = (int)$limit_part;
1182
-            }
1183
-            $model_query_params['limit'] = implode(',', $sanitized_limit);
1184
-        } else {
1185
-            $model_query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
1186
-        }
1187
-        if (isset($query_parameters['caps'])) {
1188
-            $model_query_params['caps'] = $this->validateContext($query_parameters['caps']);
1189
-        } else {
1190
-            $model_query_params['caps'] = EEM_Base::caps_read;
1191
-        }
1192
-        if (isset($query_parameters['default_where_conditions'])) {
1193
-            $model_query_params['default_where_conditions'] = $this->validateDefaultQueryParams(
1194
-                $query_parameters['default_where_conditions']
1195
-            );
1196
-        }
1197
-        return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1198
-    }
1199
-
1200
-
1201
-
1202
-    /**
1203
-     * Changes the REST-style query params for use in the models
1204
-     *
1205
-     * @deprecated
1206
-     * @param EEM_Base $model
1207
-     * @param array     $query_params sub-array from @see EEM_Base::get_all()
1208
-     * @return array
1209
-     */
1210
-    public function prepareRestQueryParamsKeyForModels($model, $query_params)
1211
-    {
1212
-        $model_ready_query_params = array();
1213
-        foreach ($query_params as $key => $value) {
1214
-            if (is_array($value)) {
1215
-                $model_ready_query_params[$key] = $this->prepareRestQueryParamsKeyForModels($model, $value);
1216
-            } else {
1217
-                $model_ready_query_params[$key] = $value;
1218
-            }
1219
-        }
1220
-        return $model_ready_query_params;
1221
-    }
1222
-
1223
-
1224
-
1225
-    /**
1226
-     * @deprecated instead use ModelDataTranslator::prepareFieldValuesFromJson()
1227
-     * @param $model
1228
-     * @param $query_params
1229
-     * @return array
1230
-     */
1231
-    public function prepareRestQueryParamsValuesForModels($model, $query_params)
1232
-    {
1233
-        $model_ready_query_params = array();
1234
-        foreach ($query_params as $key => $value) {
1235
-            if (is_array($value)) {
1236
-                $model_ready_query_params[$key] = $this->prepareRestQueryParamsValuesForModels($model, $value);
1237
-            } else {
1238
-                $model_ready_query_params[$key] = $value;
1239
-            }
1240
-        }
1241
-        return $model_ready_query_params;
1242
-    }
1243
-
1244
-
1245
-
1246
-    /**
1247
-     * Explodes the string on commas, and only returns items with $prefix followed by a period.
1248
-     * If no prefix is specified, returns items with no period.
1249
-     *
1250
-     * @param string|array $string_to_explode eg "jibba,jabba, blah, blah, blah" or array('jibba', 'jabba' )
1251
-     * @param string       $prefix            "Event" or "foobar"
1252
-     * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1253
-     *                                        we only return strings starting with that and a period; if no prefix was
1254
-     *                                        specified we return all items containing NO periods
1255
-     */
1256
-    public function explodeAndGetItemsPrefixedWith($string_to_explode, $prefix)
1257
-    {
1258
-        if (is_string($string_to_explode)) {
1259
-            $exploded_contents = explode(',', $string_to_explode);
1260
-        } elseif (is_array($string_to_explode)) {
1261
-            $exploded_contents = $string_to_explode;
1262
-        } else {
1263
-            $exploded_contents = array();
1264
-        }
1265
-        //if the string was empty, we want an empty array
1266
-        $exploded_contents = array_filter($exploded_contents);
1267
-        $contents_with_prefix = array();
1268
-        foreach ($exploded_contents as $item) {
1269
-            $item = trim($item);
1270
-            //if no prefix was provided, so we look for items with no "." in them
1271
-            if (! $prefix) {
1272
-                //does this item have a period?
1273
-                if (strpos($item, '.') === false) {
1274
-                    //if not, then its what we're looking for
1275
-                    $contents_with_prefix[] = $item;
1276
-                }
1277
-            } elseif (strpos($item, $prefix . '.') === 0) {
1278
-                //this item has the prefix and a period, grab it
1279
-                $contents_with_prefix[] = substr(
1280
-                    $item,
1281
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1282
-                );
1283
-            } elseif ($item === $prefix) {
1284
-                //this item is JUST the prefix
1285
-                //so let's grab everything after, which is a blank string
1286
-                $contents_with_prefix[] = '';
1287
-            }
1288
-        }
1289
-        return $contents_with_prefix;
1290
-    }
1291
-
1292
-
1293
-
1294
-    /**
1295
-     * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1296
-     * Deprecated because its return values were really quite confusing- sometimes it returned
1297
-     * an empty array (when the include string was blank or '*') or sometimes it returned
1298
-     * array('*') (when you provided a model and a model of that kind was found).
1299
-     * Parses the $include_string so we fetch all the field names relating to THIS model
1300
-     * (ie have NO period in them), or for the provided model (ie start with the model
1301
-     * name and then a period).
1302
-     * @param string $include_string @see Read:handle_request_get_all
1303
-     * @param string $model_name
1304
-     * @return array of fields for this model. If $model_name is provided, then
1305
-     *                               the fields for that model, with the model's name removed from each.
1306
-     *                               If $include_string was blank or '*' returns an empty array
1307
-     */
1308
-    public function extractIncludesForThisModel($include_string, $model_name = null)
1309
-    {
1310
-        if (is_array($include_string)) {
1311
-            $include_string = implode(',', $include_string);
1312
-        }
1313
-        if ($include_string === '*' || $include_string === '') {
1314
-            return array();
1315
-        }
1316
-        $includes = explode(',', $include_string);
1317
-        $extracted_fields_to_include = array();
1318
-        if ($model_name) {
1319
-            foreach ($includes as $field_to_include) {
1320
-                $field_to_include = trim($field_to_include);
1321
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1322
-                    //found the model name at the exact start
1323
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1324
-                    $extracted_fields_to_include[] = $field_sans_model_name;
1325
-                } elseif ($field_to_include == $model_name) {
1326
-                    $extracted_fields_to_include[] = '*';
1327
-                }
1328
-            }
1329
-        } else {
1330
-            //look for ones with no period
1331
-            foreach ($includes as $field_to_include) {
1332
-                $field_to_include = trim($field_to_include);
1333
-                if (strpos($field_to_include, '.') === false
1334
-                    && ! $this->getModelVersionInfo()->isModelNameInThisVersion($field_to_include)
1335
-                ) {
1336
-                    $extracted_fields_to_include[] = $field_to_include;
1337
-                }
1338
-            }
1339
-        }
1340
-        return $extracted_fields_to_include;
1341
-    }
1342
-
1343
-
1344
-
1345
-    /**
1346
-     * Gets the single item using the model according to the request in the context given, otherwise
1347
-     * returns that it's inaccessible to the current user
1348
-
1349
-     *
501
+	 * @param \EE_Model_Relation_Base $relation
502
+	 * @param WP_REST_Request        $request
503
+	 * @return array|WP_Error
504
+	 * @throws EE_Error
505
+	 */
506
+	public function getEntitiesFromRelation($id, $relation, $request)
507
+	{
508
+		if (! $relation->get_this_model()->has_primary_key_field()) {
509
+			throw new EE_Error(
510
+				sprintf(
511
+					__(
512
+						// @codingStandardsIgnoreStart
513
+						'Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
514
+						// @codingStandardsIgnoreEnd
515
+						'event_espresso'
516
+					),
517
+					$relation->get_this_model()->get_this_model_name()
518
+				)
519
+			);
520
+		}
521
+		return $this->getEntitiesFromRelationUsingModelQueryParams(
522
+			array(
523
+				array(
524
+					$relation->get_this_model()->primary_key_name() => $id,
525
+				),
526
+			),
527
+			$relation,
528
+			$request
529
+		);
530
+	}
531
+
532
+
533
+
534
+	/**
535
+	 * Sets the headers that are based on the model and query params,
536
+	 * like the total records. This should only be called on the original request
537
+	 * from the client, not on subsequent internal
538
+	 *
539
+	 * @param EEM_Base $model
540
+	 * @param array     $query_params
541
+	 * @return void
542
+	 */
543
+	protected function setHeadersFromQueryParams($model, $query_params)
544
+	{
545
+		$this->setDebugInfo('model query params', $query_params);
546
+		$this->setDebugInfo(
547
+			'missing caps',
548
+			Capabilities::getMissingPermissionsString($model, $query_params['caps'])
549
+		);
550
+		//normally the limit to a 2-part array, where the 2nd item is the limit
551
+		if (! isset($query_params['limit'])) {
552
+			$query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
553
+		}
554
+		if (is_array($query_params['limit'])) {
555
+			$limit_parts = $query_params['limit'];
556
+		} else {
557
+			$limit_parts = explode(',', $query_params['limit']);
558
+			if (count($limit_parts) == 1) {
559
+				$limit_parts = array(0, $limit_parts[0]);
560
+			}
561
+		}
562
+		//remove the group by and having parts of the query, as those will
563
+		//make the sql query return an array of values, instead of just a single value
564
+		unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
565
+		$count = $model->count($query_params, null, true);
566
+		$pages = $count / $limit_parts[1];
567
+		$this->setResponseHeader('Total', $count, false);
568
+		$this->setResponseHeader('PageSize', $limit_parts[1], false);
569
+		$this->setResponseHeader('TotalPages', ceil($pages), false);
570
+	}
571
+
572
+
573
+
574
+	/**
575
+	 * Changes database results into REST API entities
576
+	 *
577
+	 * @param EEM_Base        $model
578
+	 * @param array            $db_row     like results from $wpdb->get_results()
579
+	 * @param WP_REST_Request $rest_request
580
+	 * @param string           $deprecated no longer used
581
+	 * @return array ready for being converted into json for sending to client
582
+	 */
583
+	public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null)
584
+	{
585
+		if (! $rest_request instanceof WP_REST_Request) {
586
+			//ok so this was called in the old style, where the 3rd arg was
587
+			//$include, and the 4th arg was $context
588
+			//now setup the request just to avoid fatal errors, although we won't be able
589
+			//to truly make use of it because it's kinda devoid of info
590
+			$rest_request = new WP_REST_Request();
591
+			$rest_request->set_param('include', $rest_request);
592
+			$rest_request->set_param('caps', $deprecated);
593
+		}
594
+		if ($rest_request->get_param('caps') == null) {
595
+			$rest_request->set_param('caps', EEM_Base::caps_read);
596
+		}
597
+		$entity_array = $this->createBareEntityFromWpdbResults($model, $db_row);
598
+		$entity_array = $this->addExtraFields($model, $db_row, $entity_array);
599
+		$entity_array['_links'] = $this->getEntityLinks($model, $db_row, $entity_array);
600
+		$entity_array['_calculated_fields'] = $this->getEntityCalculations($model, $db_row, $rest_request);
601
+		$entity_array = apply_filters(
602
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
603
+			$entity_array,
604
+			$model,
605
+			$rest_request->get_param('caps'),
606
+			$rest_request,
607
+			$this
608
+		);
609
+		$entity_array = $this->includeRequestedModels($model, $rest_request, $entity_array, $db_row);
610
+		$entity_array = apply_filters(
611
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
612
+			$entity_array,
613
+			$model,
614
+			$rest_request->get_param('caps'),
615
+			$rest_request,
616
+			$this
617
+		);
618
+		$result_without_inaccessible_fields = Capabilities::filterOutInaccessibleEntityFields(
619
+			$entity_array,
620
+			$model,
621
+			$rest_request->get_param('caps'),
622
+			$this->getModelVersionInfo(),
623
+			$model->get_index_primary_key_string(
624
+				$model->deduce_fields_n_values_from_cols_n_values($db_row)
625
+			)
626
+		);
627
+		$this->setDebugInfo(
628
+			'inaccessible fields',
629
+			array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
630
+		);
631
+		return apply_filters(
632
+			'FHEE__Read__create_entity_from_wpdb_results__entity_return',
633
+			$result_without_inaccessible_fields,
634
+			$model,
635
+			$rest_request->get_param('caps')
636
+		);
637
+	}
638
+
639
+
640
+
641
+	/**
642
+	 * Creates a REST entity array (JSON object we're going to return in the response, but
643
+	 * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
644
+	 * from $wpdb->get_row( $sql, ARRAY_A)
645
+	 *
646
+	 * @param EEM_Base $model
647
+	 * @param array     $db_row
648
+	 * @return array entity mostly ready for converting to JSON and sending in the response
649
+	 *
650
+	 */
651
+	protected function createBareEntityFromWpdbResults(EEM_Base $model, $db_row)
652
+	{
653
+		$result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
654
+		$result = array_intersect_key(
655
+			$result,
656
+			$this->getModelVersionInfo()->fieldsOnModelInThisVersion($model)
657
+		);
658
+		//if this is a CPT, we need to set the global $post to it,
659
+		//otherwise shortcodes etc won't work properly while rendering it
660
+		if ($model instanceof \EEM_CPT_Base) {
661
+			$do_chevy_shuffle = true;
662
+		} else {
663
+			$do_chevy_shuffle = false;
664
+		}
665
+		if ($do_chevy_shuffle) {
666
+			global $post;
667
+			$old_post = $post;
668
+			$post = get_post($result[$model->primary_key_name()]);
669
+			if (! $post instanceof \WP_Post) {
670
+				//well that's weird, because $result is what we JUST fetched from the database
671
+				throw new RestException(
672
+					'error_fetching_post_from_database_results',
673
+					esc_html__(
674
+						'An item was retrieved from the database but it\'s not a WP_Post like it should be.',
675
+						'event_espresso'
676
+					)
677
+				);
678
+			}
679
+			$model_object_classname = 'EE_' . $model->get_this_model_name();
680
+			$post->{$model_object_classname} = \EE_Registry::instance()->load_class(
681
+				$model_object_classname,
682
+				$result,
683
+				false,
684
+				false
685
+			);
686
+		}
687
+		foreach ($result as $field_name => $field_value) {
688
+			$field_obj = $model->field_settings_for($field_name);
689
+			if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) {
690
+				unset($result[$field_name]);
691
+			} elseif ($this->isSubclassOfOne(
692
+				$field_obj,
693
+				$this->getModelVersionInfo()->fieldsThatHaveRenderedFormat()
694
+			)
695
+			) {
696
+				$result[$field_name] = array(
697
+					'raw'      => $this->prepareFieldObjValueForJson($field_obj, $field_value),
698
+					'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
699
+				);
700
+			} elseif ($this->isSubclassOfOne(
701
+				$field_obj,
702
+				$this->getModelVersionInfo()->fieldsThatHavePrettyFormat()
703
+			)
704
+			) {
705
+				$result[$field_name] = array(
706
+					'raw'    => $this->prepareFieldObjValueForJson($field_obj, $field_value),
707
+					'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
708
+				);
709
+			} elseif ($field_obj instanceof \EE_Datetime_Field) {
710
+				$field_value = $field_obj->prepare_for_set_from_db($field_value);
711
+				$timezone = $field_value->getTimezone();
712
+				$field_value->setTimezone(new \DateTimeZone('UTC'));
713
+				$result[$field_name . '_gmt'] = ModelDataTranslator::prepareFieldValuesForJson(
714
+					$field_obj,
715
+					$field_value,
716
+					$this->getModelVersionInfo()->requestedVersion()
717
+				);
718
+				$field_value->setTimezone($timezone);
719
+				$result[$field_name] = ModelDataTranslator::prepareFieldValuesForJson(
720
+					$field_obj,
721
+					$field_value,
722
+					$this->getModelVersionInfo()->requestedVersion()
723
+				);
724
+			} else {
725
+				$result[$field_name] = $this->prepareFieldObjValueForJson($field_obj, $field_value);
726
+			}
727
+		}
728
+		if ($do_chevy_shuffle) {
729
+			$post = $old_post;
730
+		}
731
+		return $result;
732
+	}
733
+
734
+
735
+
736
+	/**
737
+	 * Takes a value all the way from the DB representation, to the model object's representation, to the
738
+	 * user-facing PHP representation, to the REST API representation. (Assumes you've already taken from the DB
739
+	 * representation using $field_obj->prepare_for_set_from_db())
740
+	 *
741
+	 * @param EE_Model_Field_Base $field_obj
742
+	 * @param mixed $value as it's stored on a model object
743
+	 * @param string $format valid values are 'normal' (default), 'pretty', 'datetime_obj'
744
+	 * @return mixed
745
+	 * @throws ObjectDetectedException if $value contains a PHP object
746
+	 */
747
+	protected function prepareFieldObjValueForJson(EE_Model_Field_Base $field_obj, $value, $format = 'normal')
748
+	{
749
+		$value = $field_obj->prepare_for_set_from_db($value);
750
+		switch ($format) {
751
+			case 'pretty':
752
+				$value = $field_obj->prepare_for_pretty_echoing($value);
753
+				break;
754
+			case 'normal':
755
+			default:
756
+				$value = $field_obj->prepare_for_get($value);
757
+				break;
758
+		}
759
+		return ModelDataTranslator::prepareFieldValuesForJson(
760
+			$field_obj,
761
+			$value,
762
+			$this->getModelVersionInfo()->requestedVersion()
763
+		);
764
+	}
765
+
766
+
767
+
768
+	/**
769
+	 * Adds a few extra fields to the entity response
770
+	 *
771
+	 * @param EEM_Base $model
772
+	 * @param array     $db_row
773
+	 * @param array     $entity_array
774
+	 * @return array modified entity
775
+	 */
776
+	protected function addExtraFields(EEM_Base $model, $db_row, $entity_array)
777
+	{
778
+		if ($model instanceof EEM_CPT_Base) {
779
+			$entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
780
+		}
781
+		return $entity_array;
782
+	}
783
+
784
+
785
+
786
+	/**
787
+	 * Gets links we want to add to the response
788
+	 *
789
+	 * @global \WP_REST_Server $wp_rest_server
790
+	 * @param EEM_Base        $model
791
+	 * @param array            $db_row
792
+	 * @param array            $entity_array
793
+	 * @return array the _links item in the entity
794
+	 */
795
+	protected function getEntityLinks($model, $db_row, $entity_array)
796
+	{
797
+		//add basic links
798
+		$links = array();
799
+		if ($model->has_primary_key_field()) {
800
+			$links['self'] = array(
801
+				array(
802
+					'href' => $this->getVersionedLinkTo(
803
+						EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
804
+						. '/'
805
+						. $entity_array[$model->primary_key_name()]
806
+					),
807
+				),
808
+			);
809
+		}
810
+		$links['collection'] = array(
811
+			array(
812
+				'href' => $this->getVersionedLinkTo(
813
+					EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
814
+				),
815
+			),
816
+		);
817
+		//add links to related models
818
+		if ($model->has_primary_key_field()) {
819
+			foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) {
820
+				$related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj);
821
+				$links[EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
822
+					array(
823
+						'href'   => $this->getVersionedLinkTo(
824
+							EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
825
+							. '/'
826
+							. $entity_array[$model->primary_key_name()]
827
+							. '/'
828
+							. $related_model_part
829
+						),
830
+						'single' => $relation_obj instanceof EE_Belongs_To_Relation ? true : false,
831
+					),
832
+				);
833
+			}
834
+		}
835
+		return $links;
836
+	}
837
+
838
+
839
+
840
+	/**
841
+	 * Adds the included models indicated in the request to the entity provided
842
+	 *
843
+	 * @param EEM_Base        $model
844
+	 * @param WP_REST_Request $rest_request
845
+	 * @param array            $entity_array
846
+	 * @param array            $db_row
847
+	 * @return array the modified entity
848
+	 */
849
+	protected function includeRequestedModels(
850
+		EEM_Base $model,
851
+		WP_REST_Request $rest_request,
852
+		$entity_array,
853
+		$db_row = array()
854
+	) {
855
+		//if $db_row not included, hope the entity array has what we need
856
+		if (! $db_row) {
857
+			$db_row = $entity_array;
858
+		}
859
+		$includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), '');
860
+		$includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model);
861
+		//if they passed in * or didn't specify any includes, return everything
862
+		if (! in_array('*', $includes_for_this_model)
863
+			&& ! empty($includes_for_this_model)
864
+		) {
865
+			if ($model->has_primary_key_field()) {
866
+				//always include the primary key. ya just gotta know that at least
867
+				$includes_for_this_model[] = $model->primary_key_name();
868
+			}
869
+			if ($this->explodeAndGetItemsPrefixedWith($rest_request->get_param('calculate'), '')) {
870
+				$includes_for_this_model[] = '_calculated_fields';
871
+			}
872
+			$entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
873
+		}
874
+		$relation_settings = $this->getModelVersionInfo()->relationSettings($model);
875
+		foreach ($relation_settings as $relation_name => $relation_obj) {
876
+			$related_fields_to_include = $this->explodeAndGetItemsPrefixedWith(
877
+				$rest_request->get_param('include'),
878
+				$relation_name
879
+			);
880
+			$related_fields_to_calculate = $this->explodeAndGetItemsPrefixedWith(
881
+				$rest_request->get_param('calculate'),
882
+				$relation_name
883
+			);
884
+			//did they specify they wanted to include a related model, or
885
+			//specific fields from a related model?
886
+			//or did they specify to calculate a field from a related model?
887
+			if ($related_fields_to_include || $related_fields_to_calculate) {
888
+				//if so, we should include at least some part of the related model
889
+				$pretend_related_request = new WP_REST_Request();
890
+				$pretend_related_request->set_query_params(
891
+					array(
892
+						'caps'      => $rest_request->get_param('caps'),
893
+						'include'   => $related_fields_to_include,
894
+						'calculate' => $related_fields_to_calculate,
895
+					)
896
+				);
897
+				$pretend_related_request->add_header('no_rest_headers', true);
898
+				$primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
899
+					$model->get_index_primary_key_string(
900
+						$model->deduce_fields_n_values_from_cols_n_values($db_row)
901
+					)
902
+				);
903
+				$related_results = $this->getEntitiesFromRelationUsingModelQueryParams(
904
+					$primary_model_query_params,
905
+					$relation_obj,
906
+					$pretend_related_request
907
+				);
908
+				$entity_array[Read::getRelatedEntityName($relation_name, $relation_obj)] = $related_results
909
+																						   instanceof
910
+																						   WP_Error
911
+					? null
912
+					: $related_results;
913
+			}
914
+		}
915
+		return $entity_array;
916
+	}
917
+
918
+
919
+
920
+	/**
921
+	 * Returns a new array with all the names of models removed. Eg
922
+	 * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
923
+	 *
924
+	 * @param array $arr
925
+	 * @return array
926
+	 */
927
+	private function removeModelNamesFromArray($arr)
928
+	{
929
+		return array_diff($arr, array_keys(EE_Registry::instance()->non_abstract_db_models));
930
+	}
931
+
932
+
933
+
934
+	/**
935
+	 * Gets the calculated fields for the response
936
+	 *
937
+	 * @param EEM_Base        $model
938
+	 * @param array            $wpdb_row
939
+	 * @param WP_REST_Request $rest_request
940
+	 * @return \stdClass the _calculations item in the entity
941
+	 * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
942
+	 * did, let's know about it ASAP, so let the exception bubble up)
943
+	 */
944
+	protected function getEntityCalculations($model, $wpdb_row, $rest_request)
945
+	{
946
+		$calculated_fields = $this->explodeAndGetItemsPrefixedWith(
947
+			$rest_request->get_param('calculate'),
948
+			''
949
+		);
950
+		//note: setting calculate=* doesn't do anything
951
+		$calculated_fields_to_return = new \stdClass();
952
+		foreach ($calculated_fields as $field_to_calculate) {
953
+			try {
954
+				$calculated_fields_to_return->$field_to_calculate = ModelDataTranslator::prepareFieldValueForJson(
955
+					null,
956
+					$this->fields_calculator->retrieveCalculatedFieldValue(
957
+						$model,
958
+						$field_to_calculate,
959
+						$wpdb_row,
960
+						$rest_request,
961
+						$this
962
+					),
963
+					$this->getModelVersionInfo()->requestedVersion()
964
+				);
965
+			} catch (RestException $e) {
966
+				//if we don't have permission to read it, just leave it out. but let devs know about the problem
967
+				$this->setResponseHeader(
968
+					'Notices-Field-Calculation-Errors['
969
+					. $e->getStringCode()
970
+					. ']['
971
+					. $model->get_this_model_name()
972
+					. ']['
973
+					. $field_to_calculate
974
+					. ']',
975
+					$e->getMessage(),
976
+					true
977
+				);
978
+			}
979
+		}
980
+		return $calculated_fields_to_return;
981
+	}
982
+
983
+
984
+
985
+	/**
986
+	 * Gets the full URL to the resource, taking the requested version into account
987
+	 *
988
+	 * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
989
+	 * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
990
+	 */
991
+	public function getVersionedLinkTo($link_part_after_version_and_slash)
992
+	{
993
+		return rest_url(
994
+			EED_Core_Rest_Api::get_versioned_route_to(
995
+				$link_part_after_version_and_slash,
996
+				$this->getModelVersionInfo()->requestedVersion()
997
+			)
998
+		);
999
+	}
1000
+
1001
+
1002
+
1003
+	/**
1004
+	 * Gets the correct lowercase name for the relation in the API according
1005
+	 * to the relation's type
1006
+	 *
1007
+	 * @param string                  $relation_name
1008
+	 * @param \EE_Model_Relation_Base $relation_obj
1009
+	 * @return string
1010
+	 */
1011
+	public static function getRelatedEntityName($relation_name, $relation_obj)
1012
+	{
1013
+		if ($relation_obj instanceof EE_Belongs_To_Relation) {
1014
+			return strtolower($relation_name);
1015
+		} else {
1016
+			return EEH_Inflector::pluralize_and_lower($relation_name);
1017
+		}
1018
+	}
1019
+
1020
+
1021
+
1022
+	/**
1023
+	 * Gets the one model object with the specified id for the specified model
1024
+	 *
1025
+	 * @param EEM_Base        $model
1026
+	 * @param WP_REST_Request $request
1027
+	 * @return array|WP_Error
1028
+	 */
1029
+	public function getEntityFromModel($model, $request)
1030
+	{
1031
+		$context = $this->validateContext($request->get_param('caps'));
1032
+		return $this->getOneOrReportPermissionError($model, $request, $context);
1033
+	}
1034
+
1035
+
1036
+
1037
+	/**
1038
+	 * If a context is provided which isn't valid, maybe it was added in a future
1039
+	 * version so just treat it as a default read
1040
+	 *
1041
+	 * @param string $context
1042
+	 * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1043
+	 */
1044
+	public function validateContext($context)
1045
+	{
1046
+		if (! $context) {
1047
+			$context = EEM_Base::caps_read;
1048
+		}
1049
+		$valid_contexts = EEM_Base::valid_cap_contexts();
1050
+		if (in_array($context, $valid_contexts)) {
1051
+			return $context;
1052
+		} else {
1053
+			return EEM_Base::caps_read;
1054
+		}
1055
+	}
1056
+
1057
+
1058
+
1059
+	/**
1060
+	 * Verifies the passed in value is an allowable default where conditions value.
1061
+	 *
1062
+	 * @param $default_query_params
1063
+	 * @return string
1064
+	 */
1065
+	public function validateDefaultQueryParams($default_query_params)
1066
+	{
1067
+		$valid_default_where_conditions_for_api_calls = array(
1068
+			EEM_Base::default_where_conditions_all,
1069
+			EEM_Base::default_where_conditions_minimum_all,
1070
+			EEM_Base::default_where_conditions_minimum_others,
1071
+		);
1072
+		if (! $default_query_params) {
1073
+			$default_query_params = EEM_Base::default_where_conditions_all;
1074
+		}
1075
+		if (in_array(
1076
+			$default_query_params,
1077
+			$valid_default_where_conditions_for_api_calls,
1078
+			true
1079
+		)) {
1080
+			return $default_query_params;
1081
+		} else {
1082
+			return EEM_Base::default_where_conditions_all;
1083
+		}
1084
+	}
1085
+
1086
+
1087
+
1088
+	/**
1089
+	 * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1090
+	 * Note: right now the query parameter keys for fields (and related fields)
1091
+	 * can be left as-is, but it's quite possible this will change someday.
1092
+	 * Also, this method's contents might be candidate for moving to Model_Data_Translator
1093
+	 *
1094
+	 * @param EEM_Base $model
1095
+	 * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
1096
+	 * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1097
+	 *                                    that absolutely no results should be returned
1098
+	 * @throws EE_Error
1099
+	 * @throws RestException
1100
+	 */
1101
+	public function createModelQueryParams($model, $query_parameters)
1102
+	{
1103
+		$model_query_params = array();
1104
+		if (isset($query_parameters['where'])) {
1105
+			$model_query_params[0] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1106
+				$query_parameters['where'],
1107
+				$model,
1108
+				$this->getModelVersionInfo()->requestedVersion()
1109
+			);
1110
+		}
1111
+		if (isset($query_parameters['order_by'])) {
1112
+			$order_by = $query_parameters['order_by'];
1113
+		} elseif (isset($query_parameters['orderby'])) {
1114
+			$order_by = $query_parameters['orderby'];
1115
+		} else {
1116
+			$order_by = null;
1117
+		}
1118
+		if ($order_by !== null) {
1119
+			if (is_array($order_by)) {
1120
+				$order_by = ModelDataTranslator::prepareFieldNamesInArrayKeysFromJson($order_by);
1121
+			} else {
1122
+				//it's a single item
1123
+				$order_by = ModelDataTranslator::prepareFieldNameFromJson($order_by);
1124
+			}
1125
+			$model_query_params['order_by'] = $order_by;
1126
+		}
1127
+		if (isset($query_parameters['group_by'])) {
1128
+			$group_by = $query_parameters['group_by'];
1129
+		} elseif (isset($query_parameters['groupby'])) {
1130
+			$group_by = $query_parameters['groupby'];
1131
+		} else {
1132
+			$group_by = array_keys($model->get_combined_primary_key_fields());
1133
+		}
1134
+		//make sure they're all real names
1135
+		if (is_array($group_by)) {
1136
+			$group_by = ModelDataTranslator::prepareFieldNamesFromJson($group_by);
1137
+		}
1138
+		if ($group_by !== null) {
1139
+			$model_query_params['group_by'] = $group_by;
1140
+		}
1141
+		if (isset($query_parameters['having'])) {
1142
+			$model_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1143
+				$query_parameters['having'],
1144
+				$model,
1145
+				$this->getModelVersionInfo()->requestedVersion()
1146
+			);
1147
+		}
1148
+		if (isset($query_parameters['order'])) {
1149
+			$model_query_params['order'] = $query_parameters['order'];
1150
+		}
1151
+		if (isset($query_parameters['mine'])) {
1152
+			$model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1153
+		}
1154
+		if (isset($query_parameters['limit'])) {
1155
+			//limit should be either a string like '23' or '23,43', or an array with two items in it
1156
+			if (! is_array($query_parameters['limit'])) {
1157
+				$limit_array = explode(',', (string)$query_parameters['limit']);
1158
+			} else {
1159
+				$limit_array = $query_parameters['limit'];
1160
+			}
1161
+			$sanitized_limit = array();
1162
+			foreach ($limit_array as $key => $limit_part) {
1163
+				if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1164
+					throw new EE_Error(
1165
+						sprintf(
1166
+							__(
1167
+								// @codingStandardsIgnoreStart
1168
+								'An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
1169
+								// @codingStandardsIgnoreEnd
1170
+								'event_espresso'
1171
+							),
1172
+							wp_json_encode($query_parameters['limit'])
1173
+						)
1174
+					);
1175
+				}
1176
+				$sanitized_limit[] = (int)$limit_part;
1177
+			}
1178
+			$model_query_params['limit'] = implode(',', $sanitized_limit);
1179
+		} else {
1180
+			$model_query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
1181
+		}
1182
+		if (isset($query_parameters['caps'])) {
1183
+			$model_query_params['caps'] = $this->validateContext($query_parameters['caps']);
1184
+		} else {
1185
+			$model_query_params['caps'] = EEM_Base::caps_read;
1186
+		}
1187
+		if (isset($query_parameters['default_where_conditions'])) {
1188
+			$model_query_params['default_where_conditions'] = $this->validateDefaultQueryParams(
1189
+				$query_parameters['default_where_conditions']
1190
+			);
1191
+		}
1192
+		return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1193
+	}
1194
+
1195
+
1196
+
1197
+	/**
1198
+	 * Changes the REST-style query params for use in the models
1199
+	 *
1200
+	 * @deprecated
1201
+	 * @param EEM_Base $model
1202
+	 * @param array     $query_params sub-array from @see EEM_Base::get_all()
1203
+	 * @return array
1204
+	 */
1205
+	public function prepareRestQueryParamsKeyForModels($model, $query_params)
1206
+	{
1207
+		$model_ready_query_params = array();
1208
+		foreach ($query_params as $key => $value) {
1209
+			if (is_array($value)) {
1210
+				$model_ready_query_params[$key] = $this->prepareRestQueryParamsKeyForModels($model, $value);
1211
+			} else {
1212
+				$model_ready_query_params[$key] = $value;
1213
+			}
1214
+		}
1215
+		return $model_ready_query_params;
1216
+	}
1217
+
1218
+
1219
+
1220
+	/**
1221
+	 * @deprecated instead use ModelDataTranslator::prepareFieldValuesFromJson()
1222
+	 * @param $model
1223
+	 * @param $query_params
1224
+	 * @return array
1225
+	 */
1226
+	public function prepareRestQueryParamsValuesForModels($model, $query_params)
1227
+	{
1228
+		$model_ready_query_params = array();
1229
+		foreach ($query_params as $key => $value) {
1230
+			if (is_array($value)) {
1231
+				$model_ready_query_params[$key] = $this->prepareRestQueryParamsValuesForModels($model, $value);
1232
+			} else {
1233
+				$model_ready_query_params[$key] = $value;
1234
+			}
1235
+		}
1236
+		return $model_ready_query_params;
1237
+	}
1238
+
1239
+
1240
+
1241
+	/**
1242
+	 * Explodes the string on commas, and only returns items with $prefix followed by a period.
1243
+	 * If no prefix is specified, returns items with no period.
1244
+	 *
1245
+	 * @param string|array $string_to_explode eg "jibba,jabba, blah, blah, blah" or array('jibba', 'jabba' )
1246
+	 * @param string       $prefix            "Event" or "foobar"
1247
+	 * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1248
+	 *                                        we only return strings starting with that and a period; if no prefix was
1249
+	 *                                        specified we return all items containing NO periods
1250
+	 */
1251
+	public function explodeAndGetItemsPrefixedWith($string_to_explode, $prefix)
1252
+	{
1253
+		if (is_string($string_to_explode)) {
1254
+			$exploded_contents = explode(',', $string_to_explode);
1255
+		} elseif (is_array($string_to_explode)) {
1256
+			$exploded_contents = $string_to_explode;
1257
+		} else {
1258
+			$exploded_contents = array();
1259
+		}
1260
+		//if the string was empty, we want an empty array
1261
+		$exploded_contents = array_filter($exploded_contents);
1262
+		$contents_with_prefix = array();
1263
+		foreach ($exploded_contents as $item) {
1264
+			$item = trim($item);
1265
+			//if no prefix was provided, so we look for items with no "." in them
1266
+			if (! $prefix) {
1267
+				//does this item have a period?
1268
+				if (strpos($item, '.') === false) {
1269
+					//if not, then its what we're looking for
1270
+					$contents_with_prefix[] = $item;
1271
+				}
1272
+			} elseif (strpos($item, $prefix . '.') === 0) {
1273
+				//this item has the prefix and a period, grab it
1274
+				$contents_with_prefix[] = substr(
1275
+					$item,
1276
+					strpos($item, $prefix . '.') + strlen($prefix . '.')
1277
+				);
1278
+			} elseif ($item === $prefix) {
1279
+				//this item is JUST the prefix
1280
+				//so let's grab everything after, which is a blank string
1281
+				$contents_with_prefix[] = '';
1282
+			}
1283
+		}
1284
+		return $contents_with_prefix;
1285
+	}
1286
+
1287
+
1288
+
1289
+	/**
1290
+	 * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1291
+	 * Deprecated because its return values were really quite confusing- sometimes it returned
1292
+	 * an empty array (when the include string was blank or '*') or sometimes it returned
1293
+	 * array('*') (when you provided a model and a model of that kind was found).
1294
+	 * Parses the $include_string so we fetch all the field names relating to THIS model
1295
+	 * (ie have NO period in them), or for the provided model (ie start with the model
1296
+	 * name and then a period).
1297
+	 * @param string $include_string @see Read:handle_request_get_all
1298
+	 * @param string $model_name
1299
+	 * @return array of fields for this model. If $model_name is provided, then
1300
+	 *                               the fields for that model, with the model's name removed from each.
1301
+	 *                               If $include_string was blank or '*' returns an empty array
1302
+	 */
1303
+	public function extractIncludesForThisModel($include_string, $model_name = null)
1304
+	{
1305
+		if (is_array($include_string)) {
1306
+			$include_string = implode(',', $include_string);
1307
+		}
1308
+		if ($include_string === '*' || $include_string === '') {
1309
+			return array();
1310
+		}
1311
+		$includes = explode(',', $include_string);
1312
+		$extracted_fields_to_include = array();
1313
+		if ($model_name) {
1314
+			foreach ($includes as $field_to_include) {
1315
+				$field_to_include = trim($field_to_include);
1316
+				if (strpos($field_to_include, $model_name . '.') === 0) {
1317
+					//found the model name at the exact start
1318
+					$field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1319
+					$extracted_fields_to_include[] = $field_sans_model_name;
1320
+				} elseif ($field_to_include == $model_name) {
1321
+					$extracted_fields_to_include[] = '*';
1322
+				}
1323
+			}
1324
+		} else {
1325
+			//look for ones with no period
1326
+			foreach ($includes as $field_to_include) {
1327
+				$field_to_include = trim($field_to_include);
1328
+				if (strpos($field_to_include, '.') === false
1329
+					&& ! $this->getModelVersionInfo()->isModelNameInThisVersion($field_to_include)
1330
+				) {
1331
+					$extracted_fields_to_include[] = $field_to_include;
1332
+				}
1333
+			}
1334
+		}
1335
+		return $extracted_fields_to_include;
1336
+	}
1337
+
1338
+
1339
+
1340
+	/**
1341
+	 * Gets the single item using the model according to the request in the context given, otherwise
1342
+	 * returns that it's inaccessible to the current user
1343
+	 *
1350 1344
 *@param EEM_Base        $model
1351
-     * @param WP_REST_Request $request
1352
-     * @param null             $context
1353
-     * @return array|WP_Error
1354
-     */
1355
-    public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null)
1356
-    {
1357
-        $query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
1358
-        if ($model instanceof \EEM_Soft_Delete_Base) {
1359
-            $query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
1360
-        }
1361
-        $restricted_query_params = $query_params;
1362
-        $restricted_query_params['caps'] = $context;
1363
-        $this->setDebugInfo('model query params', $restricted_query_params);
1364
-        $model_rows = $model->get_all_wpdb_results($restricted_query_params);
1365
-        if (! empty($model_rows)) {
1366
-            return $this->createEntityFromWpdbResult(
1367
-                $model,
1368
-                array_shift($model_rows),
1369
-                $request
1370
-            );
1371
-        } else {
1372
-            //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
1373
-            $lowercase_model_name = strtolower($model->get_this_model_name());
1374
-            $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
1375
-            if (! empty($model_rows_found_sans_restrictions)) {
1376
-                //you got shafted- it existed but we didn't want to tell you!
1377
-                return new WP_Error(
1378
-                    'rest_user_cannot_' . $context,
1379
-                    sprintf(
1380
-                        __('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'),
1381
-                        $context,
1382
-                        strtolower($model->get_this_model_name()),
1383
-                        Capabilities::getMissingPermissionsString(
1384
-                            $model,
1385
-                            $context
1386
-                        )
1387
-                    ),
1388
-                    array('status' => 403)
1389
-                );
1390
-            } else {
1391
-                //it's not you. It just doesn't exist
1392
-                return new WP_Error(
1393
-                    sprintf('rest_%s_invalid_id', $lowercase_model_name),
1394
-                    sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
1395
-                    array('status' => 404)
1396
-                );
1397
-            }
1398
-        }
1399
-    }
1345
+	 * @param WP_REST_Request $request
1346
+	 * @param null             $context
1347
+	 * @return array|WP_Error
1348
+	 */
1349
+	public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null)
1350
+	{
1351
+		$query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
1352
+		if ($model instanceof \EEM_Soft_Delete_Base) {
1353
+			$query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
1354
+		}
1355
+		$restricted_query_params = $query_params;
1356
+		$restricted_query_params['caps'] = $context;
1357
+		$this->setDebugInfo('model query params', $restricted_query_params);
1358
+		$model_rows = $model->get_all_wpdb_results($restricted_query_params);
1359
+		if (! empty($model_rows)) {
1360
+			return $this->createEntityFromWpdbResult(
1361
+				$model,
1362
+				array_shift($model_rows),
1363
+				$request
1364
+			);
1365
+		} else {
1366
+			//ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
1367
+			$lowercase_model_name = strtolower($model->get_this_model_name());
1368
+			$model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
1369
+			if (! empty($model_rows_found_sans_restrictions)) {
1370
+				//you got shafted- it existed but we didn't want to tell you!
1371
+				return new WP_Error(
1372
+					'rest_user_cannot_' . $context,
1373
+					sprintf(
1374
+						__('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'),
1375
+						$context,
1376
+						strtolower($model->get_this_model_name()),
1377
+						Capabilities::getMissingPermissionsString(
1378
+							$model,
1379
+							$context
1380
+						)
1381
+					),
1382
+					array('status' => 403)
1383
+				);
1384
+			} else {
1385
+				//it's not you. It just doesn't exist
1386
+				return new WP_Error(
1387
+					sprintf('rest_%s_invalid_id', $lowercase_model_name),
1388
+					sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
1389
+					array('status' => 404)
1390
+				);
1391
+			}
1392
+		}
1393
+	}
1400 1394
 }
1401 1395
 
1402 1396
 
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 use EEM_Base;
21 21
 use EEM_CPT_Base;
22 22
 
23
-if (! defined('EVENT_ESPRESSO_VERSION')) {
23
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
24 24
     exit('No direct script access allowed');
25 25
 }
26 26
 
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
         $controller = new Read();
72 72
         try {
73 73
             $controller->setRequestedVersion($version);
74
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
74
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
75 75
                 return $controller->sendResponse(
76 76
                     new WP_Error(
77 77
                         'endpoint_parsing_error',
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
         $controller = new Read();
111 111
         try {
112 112
             $controller->setRequestedVersion($version);
113
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
113
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
114 114
                 return array();
115 115
             }
116 116
             //get the model for this version
@@ -207,9 +207,9 @@  discard block
 block discarded – undo
207 207
     protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema)
208 208
     {
209 209
         if ($field instanceof EE_Datetime_Field) {
210
-            $schema['properties'][$field_name . '_gmt'] = $field->getSchema();
210
+            $schema['properties'][$field_name.'_gmt'] = $field->getSchema();
211 211
             //modify the description
212
-            $schema['properties'][$field_name . '_gmt']['description'] = sprintf(
212
+            $schema['properties'][$field_name.'_gmt']['description'] = sprintf(
213 213
                 esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
214 214
                 $field->get_nicename()
215 215
             );
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
         $controller = new Read();
253 253
         try {
254 254
             $controller->setRequestedVersion($version);
255
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
255
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
256 256
                 return $controller->sendResponse(
257 257
                     new WP_Error(
258 258
                         'endpoint_parsing_error',
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
         $controller = new Read();
300 300
         try {
301 301
             $controller->setRequestedVersion($version);
302
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
302
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
303 303
                 return $controller->sendResponse(
304 304
                     new WP_Error(
305 305
                         'endpoint_parsing_error',
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
                 );
315 315
             }
316 316
             $main_model = $controller->getModelVersionInfo()->loadModel($model_name);
317
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
317
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
318 318
                 return $controller->sendResponse(
319 319
                     new WP_Error(
320 320
                         'endpoint_parsing_error',
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
     public function getEntitiesFromModel($model, $request)
354 354
     {
355 355
         $query_params = $this->createModelQueryParams($model, $request->get_params());
356
-        if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
356
+        if ( ! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
357 357
             $model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
358 358
             return new WP_Error(
359 359
                 sprintf('rest_%s_cannot_list', $model_name_plural),
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
                 array('status' => 403)
366 366
             );
367 367
         }
368
-        if (! $request->get_header('no_rest_headers')) {
368
+        if ( ! $request->get_header('no_rest_headers')) {
369 369
             $this->setHeadersFromQueryParams($model, $query_params);
370 370
         }
371 371
         /** @type array $results */
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
         $context = $this->validateContext($request->get_param('caps'));
402 402
         $model = $relation->get_this_model();
403 403
         $related_model = $relation->get_other_model();
404
-        if (! isset($primary_model_query_params[0])) {
404
+        if ( ! isset($primary_model_query_params[0])) {
405 405
             $primary_model_query_params[0] = array();
406 406
         }
407 407
         //check if they can access the 1st model object
@@ -418,7 +418,7 @@  discard block
 block discarded – undo
418 418
         $restricted_query_params['caps'] = $context;
419 419
         $this->setDebugInfo('main model query params', $restricted_query_params);
420 420
         $this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context));
421
-        if (! (
421
+        if ( ! (
422 422
             Capabilities::currentUserHasPartialAccessTo($related_model, $context)
423 423
             && $model->exists($restricted_query_params)
424 424
         )
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
         }
458 458
         $query_params['default_where_conditions'] = 'none';
459 459
         $query_params['caps'] = $context;
460
-        if (! $request->get_header('no_rest_headers')) {
460
+        if ( ! $request->get_header('no_rest_headers')) {
461 461
             $this->setHeadersFromQueryParams($relation->get_other_model(), $query_params);
462 462
         }
463 463
         /** @type array $results */
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
      */
511 511
     public function getEntitiesFromRelation($id, $relation, $request)
512 512
     {
513
-        if (! $relation->get_this_model()->has_primary_key_field()) {
513
+        if ( ! $relation->get_this_model()->has_primary_key_field()) {
514 514
             throw new EE_Error(
515 515
                 sprintf(
516 516
                     __(
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
             Capabilities::getMissingPermissionsString($model, $query_params['caps'])
554 554
         );
555 555
         //normally the limit to a 2-part array, where the 2nd item is the limit
556
-        if (! isset($query_params['limit'])) {
556
+        if ( ! isset($query_params['limit'])) {
557 557
             $query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
558 558
         }
559 559
         if (is_array($query_params['limit'])) {
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
      */
588 588
     public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null)
589 589
     {
590
-        if (! $rest_request instanceof WP_REST_Request) {
590
+        if ( ! $rest_request instanceof WP_REST_Request) {
591 591
             //ok so this was called in the old style, where the 3rd arg was
592 592
             //$include, and the 4th arg was $context
593 593
             //now setup the request just to avoid fatal errors, although we won't be able
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
             global $post;
672 672
             $old_post = $post;
673 673
             $post = get_post($result[$model->primary_key_name()]);
674
-            if (! $post instanceof \WP_Post) {
674
+            if ( ! $post instanceof \WP_Post) {
675 675
                 //well that's weird, because $result is what we JUST fetched from the database
676 676
                 throw new RestException(
677 677
                     'error_fetching_post_from_database_results',
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
                     )
682 682
                 );
683 683
             }
684
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
684
+            $model_object_classname = 'EE_'.$model->get_this_model_name();
685 685
             $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
686 686
                 $model_object_classname,
687 687
                 $result,
@@ -715,7 +715,7 @@  discard block
 block discarded – undo
715 715
                 $field_value = $field_obj->prepare_for_set_from_db($field_value);
716 716
                 $timezone = $field_value->getTimezone();
717 717
                 $field_value->setTimezone(new \DateTimeZone('UTC'));
718
-                $result[$field_name . '_gmt'] = ModelDataTranslator::prepareFieldValuesForJson(
718
+                $result[$field_name.'_gmt'] = ModelDataTranslator::prepareFieldValuesForJson(
719 719
                     $field_obj,
720 720
                     $field_value,
721 721
                     $this->getModelVersionInfo()->requestedVersion()
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
         if ($model->has_primary_key_field()) {
824 824
             foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) {
825 825
                 $related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj);
826
-                $links[EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
826
+                $links[EED_Core_Rest_Api::ee_api_link_namespace.$related_model_part] = array(
827 827
                     array(
828 828
                         'href'   => $this->getVersionedLinkTo(
829 829
                             EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
@@ -858,13 +858,13 @@  discard block
 block discarded – undo
858 858
         $db_row = array()
859 859
     ) {
860 860
         //if $db_row not included, hope the entity array has what we need
861
-        if (! $db_row) {
861
+        if ( ! $db_row) {
862 862
             $db_row = $entity_array;
863 863
         }
864 864
         $includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), '');
865 865
         $includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model);
866 866
         //if they passed in * or didn't specify any includes, return everything
867
-        if (! in_array('*', $includes_for_this_model)
867
+        if ( ! in_array('*', $includes_for_this_model)
868 868
             && ! empty($includes_for_this_model)
869 869
         ) {
870 870
             if ($model->has_primary_key_field()) {
@@ -1048,7 +1048,7 @@  discard block
 block discarded – undo
1048 1048
      */
1049 1049
     public function validateContext($context)
1050 1050
     {
1051
-        if (! $context) {
1051
+        if ( ! $context) {
1052 1052
             $context = EEM_Base::caps_read;
1053 1053
         }
1054 1054
         $valid_contexts = EEM_Base::valid_cap_contexts();
@@ -1074,7 +1074,7 @@  discard block
 block discarded – undo
1074 1074
             EEM_Base::default_where_conditions_minimum_all,
1075 1075
             EEM_Base::default_where_conditions_minimum_others,
1076 1076
         );
1077
-        if (! $default_query_params) {
1077
+        if ( ! $default_query_params) {
1078 1078
             $default_query_params = EEM_Base::default_where_conditions_all;
1079 1079
         }
1080 1080
         if (in_array(
@@ -1158,14 +1158,14 @@  discard block
 block discarded – undo
1158 1158
         }
1159 1159
         if (isset($query_parameters['limit'])) {
1160 1160
             //limit should be either a string like '23' or '23,43', or an array with two items in it
1161
-            if (! is_array($query_parameters['limit'])) {
1162
-                $limit_array = explode(',', (string)$query_parameters['limit']);
1161
+            if ( ! is_array($query_parameters['limit'])) {
1162
+                $limit_array = explode(',', (string) $query_parameters['limit']);
1163 1163
             } else {
1164 1164
                 $limit_array = $query_parameters['limit'];
1165 1165
             }
1166 1166
             $sanitized_limit = array();
1167 1167
             foreach ($limit_array as $key => $limit_part) {
1168
-                if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1168
+                if ($this->debug_mode && ( ! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1169 1169
                     throw new EE_Error(
1170 1170
                         sprintf(
1171 1171
                             __(
@@ -1178,7 +1178,7 @@  discard block
 block discarded – undo
1178 1178
                         )
1179 1179
                     );
1180 1180
                 }
1181
-                $sanitized_limit[] = (int)$limit_part;
1181
+                $sanitized_limit[] = (int) $limit_part;
1182 1182
             }
1183 1183
             $model_query_params['limit'] = implode(',', $sanitized_limit);
1184 1184
         } else {
@@ -1268,17 +1268,17 @@  discard block
 block discarded – undo
1268 1268
         foreach ($exploded_contents as $item) {
1269 1269
             $item = trim($item);
1270 1270
             //if no prefix was provided, so we look for items with no "." in them
1271
-            if (! $prefix) {
1271
+            if ( ! $prefix) {
1272 1272
                 //does this item have a period?
1273 1273
                 if (strpos($item, '.') === false) {
1274 1274
                     //if not, then its what we're looking for
1275 1275
                     $contents_with_prefix[] = $item;
1276 1276
                 }
1277
-            } elseif (strpos($item, $prefix . '.') === 0) {
1277
+            } elseif (strpos($item, $prefix.'.') === 0) {
1278 1278
                 //this item has the prefix and a period, grab it
1279 1279
                 $contents_with_prefix[] = substr(
1280 1280
                     $item,
1281
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1281
+                    strpos($item, $prefix.'.') + strlen($prefix.'.')
1282 1282
                 );
1283 1283
             } elseif ($item === $prefix) {
1284 1284
                 //this item is JUST the prefix
@@ -1318,9 +1318,9 @@  discard block
 block discarded – undo
1318 1318
         if ($model_name) {
1319 1319
             foreach ($includes as $field_to_include) {
1320 1320
                 $field_to_include = trim($field_to_include);
1321
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1321
+                if (strpos($field_to_include, $model_name.'.') === 0) {
1322 1322
                     //found the model name at the exact start
1323
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1323
+                    $field_sans_model_name = str_replace($model_name.'.', '', $field_to_include);
1324 1324
                     $extracted_fields_to_include[] = $field_sans_model_name;
1325 1325
                 } elseif ($field_to_include == $model_name) {
1326 1326
                     $extracted_fields_to_include[] = '*';
@@ -1362,7 +1362,7 @@  discard block
 block discarded – undo
1362 1362
         $restricted_query_params['caps'] = $context;
1363 1363
         $this->setDebugInfo('model query params', $restricted_query_params);
1364 1364
         $model_rows = $model->get_all_wpdb_results($restricted_query_params);
1365
-        if (! empty($model_rows)) {
1365
+        if ( ! empty($model_rows)) {
1366 1366
             return $this->createEntityFromWpdbResult(
1367 1367
                 $model,
1368 1368
                 array_shift($model_rows),
@@ -1372,10 +1372,10 @@  discard block
 block discarded – undo
1372 1372
             //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
1373 1373
             $lowercase_model_name = strtolower($model->get_this_model_name());
1374 1374
             $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
1375
-            if (! empty($model_rows_found_sans_restrictions)) {
1375
+            if ( ! empty($model_rows_found_sans_restrictions)) {
1376 1376
                 //you got shafted- it existed but we didn't want to tell you!
1377 1377
                 return new WP_Error(
1378
-                    'rest_user_cannot_' . $context,
1378
+                    'rest_user_cannot_'.$context,
1379 1379
                     sprintf(
1380 1380
                         __('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'),
1381 1381
                         $context,
Please login to merge, or discard this patch.
core/db_models/strategies/EE_Restriction_Generator_Reg_Form.strategy.php 2 patches
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -49,18 +49,18 @@
 block discarded – undo
49 49
 			EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() ) => new EE_Return_None_Where_Conditions(),
50 50
 		);
51 51
 		//there is no "ee_read_system_questions" cap; in order to read reg form items you only need "ee_read_{model_name}".
52
-        //there is also no "ee_delete_system_questions" cap. But folks shouldn't be deleting system questions anyway
52
+		//there is also no "ee_delete_system_questions" cap. But folks shouldn't be deleting system questions anyway
53 53
 		if ($this->action() !== EEM_Base::caps_read) {
54
-            $restrictions[EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action() . '_system')] = new EE_Default_Where_Conditions(
55
-                array(
56
-                    'OR*no_' . EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action() . '_system') => array(
57
-                        $this->_system_field_name       => array('IN', array('', 0)),
58
-                        $this->_system_field_name . '*' => array('IS_NULL')
59
-                    )
60
-                )
61
-            );
62
-        }
63
-        return $restrictions;
54
+			$restrictions[EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action() . '_system')] = new EE_Default_Where_Conditions(
55
+				array(
56
+					'OR*no_' . EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action() . '_system') => array(
57
+						$this->_system_field_name       => array('IN', array('', 0)),
58
+						$this->_system_field_name . '*' => array('IS_NULL')
59
+					)
60
+				)
61
+			);
62
+		}
63
+		return $restrictions;
64 64
 	}
65 65
 }
66 66
 
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
3
-	exit( 'No direct script access allowed' );
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3
+	exit('No direct script access allowed');
4 4
 }
5 5
 
6 6
 /**
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
  * @author				Mike Nelson
16 16
  *
17 17
  */
18
-class EE_Restriction_Generator_Reg_Form extends EE_Restriction_Generator_Base{
18
+class EE_Restriction_Generator_Reg_Form extends EE_Restriction_Generator_Base {
19 19
 
20 20
 	/**
21 21
 	 *
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
 	 * Accepts the name of the field that indicates whether or not an object is a "system" one or not
28 28
 	 * @param string $system_field_name
29 29
 	 */
30
-	public function __construct( $system_field_name ) {
30
+	public function __construct($system_field_name) {
31 31
 		$this->_system_field_name = $system_field_name;
32 32
 	}
33 33
 
@@ -40,22 +40,22 @@  discard block
 block discarded – undo
40 40
 	protected function _generate_restrictions() {
41 41
 		//if there are no standard caps for this model, then for now all we know
42 42
 		//if they need the default cap to access this
43
-		if( ! $this->model()->cap_slug() ) {
43
+		if ( ! $this->model()->cap_slug()) {
44 44
 			return array(
45 45
 				EE_Restriction_Generator_Base::get_default_restrictions_cap() => new EE_Return_None_Where_Conditions()
46 46
 			);
47 47
 		}
48 48
 		$restrictions = array(
49
-			EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() ) => new EE_Return_None_Where_Conditions(),
49
+			EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action()) => new EE_Return_None_Where_Conditions(),
50 50
 		);
51 51
 		//there is no "ee_read_system_questions" cap; in order to read reg form items you only need "ee_read_{model_name}".
52 52
         //there is also no "ee_delete_system_questions" cap. But folks shouldn't be deleting system questions anyway
53 53
 		if ($this->action() !== EEM_Base::caps_read) {
54
-            $restrictions[EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action() . '_system')] = new EE_Default_Where_Conditions(
54
+            $restrictions[EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action().'_system')] = new EE_Default_Where_Conditions(
55 55
                 array(
56
-                    'OR*no_' . EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action() . '_system') => array(
56
+                    'OR*no_'.EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action().'_system') => array(
57 57
                         $this->_system_field_name       => array('IN', array('', 0)),
58
-                        $this->_system_field_name . '*' => array('IS_NULL')
58
+                        $this->_system_field_name.'*' => array('IS_NULL')
59 59
                     )
60 60
                 )
61 61
             );
Please login to merge, or discard this patch.
core/db_models/EEM_Question_Option.model.php 1 patch
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -21,8 +21,8 @@  discard block
 block discarded – undo
21 21
  *
22 22
  * ------------------------------------------------------------------------
23 23
  */
24
-require_once ( EE_MODELS . 'EEM_Soft_Delete_Base.model.php' );
25
-require_once( EE_CLASSES . 'EE_Question_Option.class.php');
24
+require_once (EE_MODELS.'EEM_Soft_Delete_Base.model.php');
25
+require_once(EE_CLASSES.'EE_Question_Option.class.php');
26 26
 
27 27
 
28 28
 class EEM_Question_Option extends EEM_Soft_Delete_Base {
@@ -30,22 +30,22 @@  discard block
 block discarded – undo
30 30
   	// private instance of the Attendee object
31 31
 	protected static $_instance = NULL;
32 32
 
33
-	protected function __construct( $timezone = NULL ) {
34
-		$this->singular_item = __('Question Option','event_espresso');
35
-		$this->plural_item = __('Question Options','event_espresso');
33
+	protected function __construct($timezone = NULL) {
34
+		$this->singular_item = __('Question Option', 'event_espresso');
35
+		$this->plural_item = __('Question Options', 'event_espresso');
36 36
 
37 37
 		$this->_tables = array(
38
-			'Question_Option'=>new EE_Primary_Table('esp_question_option','QSO_ID')
38
+			'Question_Option'=>new EE_Primary_Table('esp_question_option', 'QSO_ID')
39 39
 		);
40 40
 		$this->_fields = array(
41 41
 			'Question_Option'=>array(
42
-					'QSO_ID'=>new EE_Primary_Key_Int_Field('QSO_ID', __('Question Option ID','event_espresso')),
43
-					'QST_ID'=>new EE_Foreign_Key_Int_Field('QST_ID', __('Question ID','event_espresso'), false, 0, 'Question'),
44
-					'QSO_value'=>new EE_Plain_Text_Field('QSO_value',  __("Question Option Value", "event_espresso"),false,''),
45
-					'QSO_desc'=>new EE_Post_Content_Field('QSO_desc', __('Question Option Description','event_espresso'), false, ''),
46
-					'QSO_order' => new EE_Integer_Field('QSO_order', __('Question Option Order', 'event_espresso' ), false, 0 ),
47
-					'QSO_system'=>new EE_Plain_Text_Field('QSO_system', __('Internal string ID for question option','event_espresso'), TRUE, NULL ),
48
-					'QSO_deleted'=>new EE_Trashed_Flag_Field('QSO_deleted', __('Flag indicating Option was trashed','event_espresso'), false, false)
42
+					'QSO_ID'=>new EE_Primary_Key_Int_Field('QSO_ID', __('Question Option ID', 'event_espresso')),
43
+					'QST_ID'=>new EE_Foreign_Key_Int_Field('QST_ID', __('Question ID', 'event_espresso'), false, 0, 'Question'),
44
+					'QSO_value'=>new EE_Plain_Text_Field('QSO_value', __("Question Option Value", "event_espresso"), false, ''),
45
+					'QSO_desc'=>new EE_Post_Content_Field('QSO_desc', __('Question Option Description', 'event_espresso'), false, ''),
46
+					'QSO_order' => new EE_Integer_Field('QSO_order', __('Question Option Order', 'event_espresso'), false, 0),
47
+					'QSO_system'=>new EE_Plain_Text_Field('QSO_system', __('Internal string ID for question option', 'event_espresso'), TRUE, NULL),
48
+					'QSO_deleted'=>new EE_Trashed_Flag_Field('QSO_deleted', __('Flag indicating Option was trashed', 'event_espresso'), false, false)
49 49
 				)
50 50
 		);
51 51
 		$this->_model_relations = array(
@@ -54,12 +54,12 @@  discard block
 block discarded – undo
54 54
 
55 55
 		$this->_model_chain_to_wp_user = 'Question';
56 56
 		//this model is generally available for reading
57
-		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
58
-		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Reg_Form('QSO_system');
59
-		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Reg_Form('QSO_system');
60
-		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Reg_Form('QSO_system');
57
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
58
+		$this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Reg_Form('QSO_system');
59
+		$this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Reg_Form('QSO_system');
60
+		$this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Reg_Form('QSO_system');
61 61
 		$this->_caps_slug = 'questions';
62
-		parent::__construct( $timezone );
62
+		parent::__construct($timezone);
63 63
 	}
64 64
 
65 65
 
Please login to merge, or discard this patch.
core/libraries/rest_api/ModelDataTranslator.php 3 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -1,11 +1,9 @@
 block discarded – undo
1 1
 <?php
2 2
 namespace EventEspresso\core\libraries\rest_api;
3 3
 
4
-use EE_Capabilities;
5 4
 use EE_Datetime_Field;
6 5
 use EE_Error;
7 6
 use EE_Infinite_Integer_Field;
8
-use EE_Maybe_Serialized_Simple_HTML_Field;
9 7
 use EE_Model_Field_Base;
10 8
 use EE_Serialized_Text_Field;
11 9
 use EEM_Base;
Please login to merge, or discard this patch.
Indentation   +789 added lines, -789 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 use EEM_Base;
12 12
 
13 13
 if (! defined('EVENT_ESPRESSO_VERSION')) {
14
-    exit('No direct script access allowed');
14
+	exit('No direct script access allowed');
15 15
 }
16 16
 
17 17
 
@@ -36,792 +36,792 @@  discard block
 block discarded – undo
36 36
 class ModelDataTranslator
37 37
 {
38 38
 
39
-    /**
40
-     * We used to use -1 for infinity in the rest api, but that's ambiguous for
41
-     * fields that COULD contain -1; so we use null
42
-     */
43
-    const EE_INF_IN_REST = null;
44
-
45
-
46
-
47
-    /**
48
-     * Prepares a possible array of input values from JSON for use by the models
49
-     *
50
-     * @param EE_Model_Field_Base $field_obj
51
-     * @param mixed                $original_value_maybe_array
52
-     * @param string               $requested_version
53
-     * @param string               $timezone_string treat values as being in this timezone
54
-     * @return mixed
55
-     * @throws RestException
56
-     */
57
-    public static function prepareFieldValuesFromJson(
58
-        $field_obj,
59
-        $original_value_maybe_array,
60
-        $requested_version,
61
-        $timezone_string = 'UTC'
62
-    ) {
63
-        if (is_array($original_value_maybe_array)
64
-            && ! $field_obj instanceof EE_Serialized_Text_Field
65
-        ) {
66
-            $new_value_maybe_array = array();
67
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
68
-                $new_value_maybe_array[$array_key] = ModelDataTranslator::prepareFieldValueFromJson(
69
-                    $field_obj,
70
-                    $array_item,
71
-                    $requested_version,
72
-                    $timezone_string
73
-                );
74
-            }
75
-        } else {
76
-            $new_value_maybe_array = ModelDataTranslator::prepareFieldValueFromJson(
77
-                $field_obj,
78
-                $original_value_maybe_array,
79
-                $requested_version,
80
-                $timezone_string
81
-            );
82
-        }
83
-        return $new_value_maybe_array;
84
-    }
85
-
86
-
87
-
88
-    /**
89
-     * Prepares an array of field values FOR use in JSON/REST API
90
-     *
91
-     * @param EE_Model_Field_Base $field_obj
92
-     * @param mixed                $original_value_maybe_array
93
-     * @param string               $request_version (eg 4.8.36)
94
-     * @return array
95
-     */
96
-    public static function prepareFieldValuesForJson($field_obj, $original_value_maybe_array, $request_version)
97
-    {
98
-        if (is_array($original_value_maybe_array)) {
99
-            $new_value = array();
100
-            foreach ($original_value_maybe_array as $key => $value) {
101
-                $new_value[$key] = ModelDataTranslator::prepareFieldValuesForJson($field_obj, $value, $request_version);
102
-            }
103
-        } else {
104
-            $new_value = ModelDataTranslator::prepareFieldValueForJson(
105
-                $field_obj,
106
-                $original_value_maybe_array,
107
-                $request_version
108
-            );
109
-        }
110
-        return $new_value;
111
-    }
112
-
113
-
114
-
115
-    /**
116
-     * Prepares incoming data from the json or $_REQUEST parameters for the models'
117
-     * "$query_params".
118
-     *
119
-     * @param EE_Model_Field_Base $field_obj
120
-     * @param mixed                $original_value
121
-     * @param string               $requested_version
122
-     * @param string               $timezone_string treat values as being in this timezone
123
-     * @return mixed
124
-     * @throws RestException
125
-     */
126
-    public static function prepareFieldValueFromJson(
127
-        $field_obj,
128
-        $original_value,
129
-        $requested_version,
130
-        $timezone_string = 'UTC' // UTC
131
-    ) {
132
-        //check if they accidentally submitted an error value. If so throw an exception
133
-        if (is_array($original_value)
134
-            && isset($original_value['error_code'], $original_value['error_message'])) {
135
-            throw new RestException(
136
-                'rest_submitted_error_value',
137
-                sprintf(
138
-                    esc_html__(
139
-                        'You tried to submit a JSON error object as a value for %1$s. That\'s not allowed.',
140
-                        'event_espresso'
141
-                    ),
142
-                    $field_obj->get_name()
143
-                ),
144
-                array(
145
-                    'status' => 400,
146
-                )
147
-            );
148
-        }
149
-        //double-check for serialized PHP. We never accept serialized PHP. No way Jose.
150
-        ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
151
-        $timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
152
-        $new_value = null;
153
-        //walk through the submitted data and double-check for serialized PHP. We never accept serialized PHP. No
154
-        // way Jose.
155
-        ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
156
-        if ($field_obj instanceof EE_Infinite_Integer_Field
157
-            && in_array($original_value, array(null, ''), true)
158
-        ) {
159
-            $new_value = EE_INF;
160
-        } elseif ($field_obj instanceof EE_Datetime_Field) {
161
-            list($offset_sign, $offset_secs) = ModelDataTranslator::parseTimezoneOffset(
162
-                $field_obj->get_timezone_offset(
163
-                    new \DateTimeZone($timezone_string),
164
-                    $original_value
165
-                )
166
-            );
167
-            $offset_string =
168
-                str_pad(
169
-                    floor($offset_secs / HOUR_IN_SECONDS),
170
-                    2,
171
-                    '0',
172
-                    STR_PAD_LEFT
173
-                )
174
-                . ':'
175
-                . str_pad(
176
-                    ($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
177
-                    2,
178
-                    '0',
179
-                    STR_PAD_LEFT
180
-                );
181
-            $new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
182
-        } else {
183
-            $new_value = $original_value;
184
-        }
185
-        return $new_value;
186
-    }
187
-
188
-
189
-
190
-    /**
191
-     * Throws an exception if $data is a serialized PHP string (or somehow an actually PHP object, although I don't
192
-     * think that can happen). If $data is an array, recurses into its keys and values
193
-     * @param mixed $data
194
-     * @throws RestException
195
-     * @return void
196
-     */
197
-    public static function throwExceptionIfContainsSerializedData($data)
198
-    {
199
-        if (is_array($data)) {
200
-            foreach ($data as $key => $value) {
201
-                ModelDataTranslator::throwExceptionIfContainsSerializedData($key);
202
-                ModelDataTranslator::throwExceptionIfContainsSerializedData($value);
203
-            }
204
-        } else {
205
-            if (is_serialized($data) || is_object($data)) {
206
-                throw new RestException(
207
-                    'serialized_data_submission_prohibited',
208
-                    esc_html__(
209
-                        // @codingStandardsIgnoreStart
210
-                        'You tried to submit a string of serialized text. Serialized PHP is prohibited over the EE4 REST API.',
211
-                        // @codingStandardsIgnoreEnd
212
-                        'event_espresso'
213
-                    )
214
-                );
215
-            }
216
-        }
217
-    }
218
-
219
-
220
-
221
-    /**
222
-     * determines what's going on with them timezone strings
223
-     *
224
-     * @param int $timezone_offset
225
-     * @return array
226
-     */
227
-    private static function parseTimezoneOffset($timezone_offset)
228
-    {
229
-        $first_char = substr((string)$timezone_offset, 0, 1);
230
-        if ($first_char === '+' || $first_char === '-') {
231
-            $offset_sign = $first_char;
232
-            $offset_secs = substr((string)$timezone_offset, 1);
233
-        } else {
234
-            $offset_sign = '+';
235
-            $offset_secs = $timezone_offset;
236
-        }
237
-        return array($offset_sign, $offset_secs);
238
-    }
239
-
240
-
241
-
242
-    /**
243
-     * Prepares a field's value for display in the API
244
-     *
245
-     * @param EE_Model_Field_Base $field_obj
246
-     * @param mixed                $original_value
247
-     * @param string               $requested_version
248
-     * @return mixed
249
-     */
250
-    public static function prepareFieldValueForJson($field_obj, $original_value, $requested_version)
251
-    {
252
-        if ($original_value === EE_INF) {
253
-            $new_value = ModelDataTranslator::EE_INF_IN_REST;
254
-        } elseif ($field_obj instanceof EE_Datetime_Field) {
255
-            if (is_string($original_value)) {
256
-                //did they submit a string of a unix timestamp?
257
-                if (is_numeric($original_value)) {
258
-                    $datetime_obj = new \DateTime();
259
-                    $datetime_obj->setTimestamp((int)$original_value);
260
-                } else {
261
-                    //first, check if its a MySQL timestamp in GMT
262
-                    $datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
263
-                }
264
-                if (! $datetime_obj instanceof \DateTime) {
265
-                    //so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
266
-                    $datetime_obj = $field_obj->prepare_for_set($original_value);
267
-                }
268
-                $original_value = $datetime_obj;
269
-            }
270
-            if ($original_value instanceof \DateTime) {
271
-                $new_value = $original_value->format('Y-m-d H:i:s');
272
-            } elseif (is_int($original_value) || is_float($original_value)) {
273
-                $new_value = date('Y-m-d H:i:s', $original_value);
274
-            } elseif($original_value === null || $original_value === '') {
275
-                $new_value = null;
276
-            } else {
277
-                //so it's not a datetime object, unix timestamp (as string or int),
278
-                //MySQL timestamp, or even a string in the field object's format. So no idea what it is
279
-                throw new \EE_Error(
280
-                    sprintf(
281
-                        esc_html__(
282
-                        // @codingStandardsIgnoreStart
283
-                            'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
284
-                            // @codingStandardsIgnoreEnd
285
-                            'event_espressso'
286
-                        ),
287
-                        $original_value,
288
-                        $field_obj->get_name(),
289
-                        $field_obj->get_model_name(),
290
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
291
-                    )
292
-                );
293
-            }
294
-            $new_value = mysql_to_rfc3339($new_value);
295
-        } else {
296
-            $new_value = $original_value;
297
-        }
298
-        //are we about to send an object? just don't. We have no good way to represent it in JSON.
299
-        // can't just check using is_object() because that missed PHP incomplete objects
300
-        if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
301
-            $new_value = array(
302
-                'error_code' => 'php_object_not_return',
303
-                'error_message' => esc_html__('The value of this field in the database is a PHP object, which can\'t be represented in JSON.', 'event_espresso')
304
-            );
305
-        }
306
-        return apply_filters(
307
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
308
-            $new_value,
309
-            $field_obj,
310
-            $original_value,
311
-            $requested_version
312
-        );
313
-    }
314
-
315
-
316
-
317
-    /**
318
-     * Prepares condition-query-parameters (like what's in where and having) from
319
-     * the format expected in the API to use in the models
320
-     *
321
-     * @param array     $inputted_query_params_of_this_type
322
-     * @param EEM_Base $model
323
-     * @param string    $requested_version
324
-     * @param boolean $writing whether this data will be written to the DB, or if we're just building a query.
325
-     *                         If we're writing to the DB, we don't expect any operators, or any logic query parameters,
326
-     *                         and we also won't accept serialized data unless the current user has unfiltered_html.
327
-     * @return array
328
-     * @throws \DomainException
329
-     * @throws RestException
330
-     * @throws EE_Error
331
-     */
332
-    public static function prepareConditionsQueryParamsForModels(
333
-        $inputted_query_params_of_this_type,
334
-        EEM_Base $model,
335
-        $requested_version,
336
-        $writing = false
337
-    ) {
338
-        $query_param_for_models = array();
339
-        $valid_operators = $model->valid_operators();
340
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
341
-            $is_gmt_datetime_field = false;
342
-            $query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
343
-                $query_param_key
344
-            );
345
-            $field = ModelDataTranslator::deduceFieldFromQueryParam(
346
-                $query_param_sans_stars,
347
-                $model
348
-            );
349
-            //double-check is it a *_gmt field?
350
-            if (! $field instanceof EE_Model_Field_Base
351
-                && ModelDataTranslator::isGmtDateFieldName($query_param_sans_stars)
352
-            ) {
353
-                //yep, take off '_gmt', and find the field
354
-                $query_param_key = ModelDataTranslator::removeGmtFromFieldName($query_param_sans_stars);
355
-                $field = ModelDataTranslator::deduceFieldFromQueryParam(
356
-                    $query_param_key,
357
-                    $model
358
-                );
359
-                $timezone = 'UTC';
360
-                $is_gmt_datetime_field = true;
361
-            } elseif ($field instanceof EE_Datetime_Field) {
362
-                //so it's not a GMT field. Set the timezone on the model to the default
363
-                $timezone = \EEH_DTT_Helper::get_valid_timezone_string();
364
-            } else {
365
-                //just keep using what's already set for the timezone
366
-                $timezone = $model->get_timezone();
367
-            }
368
-            if ($field instanceof EE_Model_Field_Base) {
369
-                if (! $writing && is_array($query_param_value)) {
370
-                    if (! \EEH_Array::is_array_numerically_and_sequentially_indexed($query_param_value)) {
371
-                        if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
372
-                            throw new RestException(
373
-                                'numerically_indexed_array_of_values_only',
374
-                                sprintf(
375
-                                    esc_html__(
376
-                                        'The array provided for the parameter "%1$s" should be numerically indexed.',
377
-                                        'event_espresso'
378
-                                    ),
379
-                                    $query_param_key
380
-                                ),
381
-                                array(
382
-                                    'status' => 400,
383
-                                )
384
-                            );
385
-                        }
386
-                    }
387
-                    //did they specify an operator?
388
-                    if (isset($query_param_value[0])
389
-                        && isset($valid_operators[$query_param_value[0]])
390
-                    ) {
391
-                        $op = $query_param_value[0];
392
-                        $translated_value = array($op);
393
-                        if (array_key_exists($op, $model->valid_in_style_operators())
394
-                            && isset($query_param_value[1])
395
-                            && ! isset($query_param_value[2])
396
-                        ) {
397
-                            $translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
398
-                                $field,
399
-                                $query_param_value[1],
400
-                                $requested_version,
401
-                                $timezone
402
-                            );
403
-                        } elseif (array_key_exists($op, $model->valid_between_style_operators())
404
-                            && isset($query_param_value[1], $query_param_value[2])
405
-                            && !isset($query_param_value[3])
406
-                        ) {
407
-                            $translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
408
-                                $field,
409
-                                $query_param_value[1],
410
-                                $requested_version,
411
-                                $timezone
412
-                            );
413
-                            $translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
414
-                                $field,
415
-                                $query_param_value[2],
416
-                                $requested_version,
417
-                                $timezone
418
-                            );
419
-                        } elseif (array_key_exists($op, $model->valid_like_style_operators())
420
-                            && isset($query_param_value[1])
421
-                            && ! isset($query_param_value[2])
422
-                        ) {
423
-                            //we want to leave this value mostly-as-is (eg don't force it to be a float
424
-                            //or a boolean or an enum value. Leave it as-is with wildcards etc)
425
-                            //but do verify it at least doesn't have any serialized data
426
-                            ModelDataTranslator::throwExceptionIfContainsSerializedData($query_param_value[1]);
427
-                            $translated_value[] = $query_param_value[1];
428
-                        } elseif (array_key_exists($op, $model->valid_null_style_operators())
429
-                            && !isset($query_param_value[1])) {
430
-                            //no arguments should have been provided, so don't look for any
431
-                        } elseif (isset($query_param_value[1])
432
-                            && !isset($query_param_value[2])
433
-                            && ! array_key_exists(
434
-                                $op,
435
-                                array_merge(
436
-                                    $model->valid_in_style_operators(),
437
-                                    $model->valid_null_style_operators(),
438
-                                    $model->valid_like_style_operators(),
439
-                                    $model->valid_between_style_operators()
440
-                                )
441
-                            )
442
-                        ) {
443
-                            //it's a valid operator, but none of the exceptions. Treat it normally.
444
-                            $translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
445
-                                $field,
446
-                                $query_param_value[1],
447
-                                $requested_version,
448
-                                $timezone
449
-                            );
450
-                        } else {
451
-                            //so they provided a valid operator, but wrong number of arguments
452
-                            if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
453
-                                throw new RestException(
454
-                                    'wrong_number_of_arguments',
455
-                                    sprintf(
456
-                                        esc_html__(
457
-                                            'The operator you provided, "%1$s" had the wrong number of arguments',
458
-                                            'event_espresso'
459
-                                        ),
460
-                                        $op
461
-                                    ),
462
-                                    array(
463
-                                        'status' => 400,
464
-                                    )
465
-                                );
466
-                            }
467
-                            $translated_value = null;
468
-                        }
469
-                    } else {
470
-                        //so they didn't provide a valid operator
471
-                        if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
472
-                            throw new RestException(
473
-                                'invalid_operator',
474
-                                sprintf(
475
-                                    esc_html__(
476
-                                        'You provided an invalid parameter, with key "%1$s" and value "%2$s"',
477
-                                        'event_espresso'
478
-                                    ),
479
-                                    $query_param_key,
480
-                                    $query_param_value
481
-                                ),
482
-                                array(
483
-                                    'status' => 400,
484
-                                )
485
-                            );
486
-                        }
487
-                        //if we aren't in debug mode, then just try our best to fulfill the user's request
488
-                        $translated_value = null;
489
-                    }
490
-                } else {
491
-                    $translated_value = ModelDataTranslator::prepareFieldValueFromJson(
492
-                        $field,
493
-                        $query_param_value,
494
-                        $requested_version,
495
-                        $timezone
496
-                    );
497
-                }
498
-                if (
499
-                    (isset($query_param_for_models[$query_param_key]) && $is_gmt_datetime_field)
500
-                    ||
501
-                    $translated_value === null
502
-                ) {
503
-                    //they have already provided a non-gmt field, ignore the gmt one. That's what WP core
504
-                    //currently does (they might change it though). See https://core.trac.wordpress.org/ticket/39954
505
-                    //OR we couldn't create a translated value from their input
506
-                    continue;
507
-                }
508
-                $query_param_for_models[$query_param_key] = $translated_value;
509
-            } else {
510
-                //so this param doesn't correspond to a field eh?
511
-                if ($writing) {
512
-                    //always tell API clients about invalid parameters when they're creating data. Otherwise,
513
-                    //they are probably going to create invalid data
514
-                    throw new RestException(
515
-                        'invalid_field',
516
-                        sprintf(
517
-                            esc_html__('You have provided an invalid parameter: "%1$s"', 'event_espresso'),
518
-                            $query_param_key
519
-                        )
520
-                    );
521
-                } else {
522
-                    //so it's not for a field, is it a logic query param key?
523
-                    if (in_array(
524
-                        $query_param_sans_stars,
525
-                        $model->logic_query_param_keys()
526
-                    )) {
527
-                        $query_param_for_models[$query_param_key] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
528
-                            $query_param_value,
529
-                            $model,
530
-                            $requested_version
531
-                        );
532
-                    } elseif (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
533
-                        //only tell API clients they got it wrong if we're in debug mode
534
-                        //otherwise try our best ot fulfill their request by ignoring this invalid data
535
-                        throw new RestException(
536
-                            'invalid_parameter',
537
-                            sprintf(
538
-                                esc_html__(
539
-                                    'You provided an invalid parameter, with key "%1$s"',
540
-                                    'event_espresso'
541
-                                ),
542
-                                $query_param_sans_stars
543
-                            ),
544
-                            array(
545
-                                'status' => 400,
546
-                            )
547
-                        );
548
-                    }
549
-                }
550
-            }
551
-        }
552
-        return $query_param_for_models;
553
-    }
554
-
555
-
556
-
557
-    /**
558
-     * Mostly checks if the last 4 characters are "_gmt", indicating its a
559
-     * gmt date field name
560
-     *
561
-     * @param string $field_name
562
-     * @return boolean
563
-     */
564
-    public static function isGmtDateFieldName($field_name)
565
-    {
566
-        return substr(
567
-            ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($field_name),
568
-            -4,
569
-            4
570
-        ) === '_gmt';
571
-    }
572
-
573
-
574
-
575
-    /**
576
-     * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
577
-     *
578
-     * @param string $field_name
579
-     * @return string
580
-     */
581
-    public static function removeGmtFromFieldName($field_name)
582
-    {
583
-        if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
584
-            return $field_name;
585
-        }
586
-        $query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
587
-            $field_name
588
-        );
589
-        $query_param_sans_gmt_and_sans_stars = substr(
590
-            $query_param_sans_stars,
591
-            0,
592
-            strrpos(
593
-                $field_name,
594
-                '_gmt'
595
-            )
596
-        );
597
-        return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
598
-    }
599
-
600
-
601
-
602
-    /**
603
-     * Takes a field name from the REST API and prepares it for the model querying
604
-     *
605
-     * @param string $field_name
606
-     * @return string
607
-     */
608
-    public static function prepareFieldNameFromJson($field_name)
609
-    {
610
-        if (ModelDataTranslator::isGmtDateFieldName($field_name)) {
611
-            return ModelDataTranslator::removeGmtFromFieldName($field_name);
612
-        }
613
-        return $field_name;
614
-    }
615
-
616
-
617
-
618
-    /**
619
-     * Takes array of field names from REST API and prepares for models
620
-     *
621
-     * @param array $field_names
622
-     * @return array of field names (possibly include model prefixes)
623
-     */
624
-    public static function prepareFieldNamesFromJson(array $field_names)
625
-    {
626
-        $new_array = array();
627
-        foreach ($field_names as $key => $field_name) {
628
-            $new_array[$key] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
629
-        }
630
-        return $new_array;
631
-    }
632
-
633
-
634
-
635
-    /**
636
-     * Takes array where array keys are field names (possibly with model path prefixes)
637
-     * from the REST API and prepares them for model querying
638
-     *
639
-     * @param array $field_names_as_keys
640
-     * @return array
641
-     */
642
-    public static function prepareFieldNamesInArrayKeysFromJson(array $field_names_as_keys)
643
-    {
644
-        $new_array = array();
645
-        foreach ($field_names_as_keys as $field_name => $value) {
646
-            $new_array[ModelDataTranslator::prepareFieldNameFromJson($field_name)] = $value;
647
-        }
648
-        return $new_array;
649
-    }
650
-
651
-
652
-
653
-    /**
654
-     * Prepares an array of model query params for use in the REST API
655
-     *
656
-     * @param array     $model_query_params
657
-     * @param EEM_Base $model
658
-     * @param string    $requested_version eg "4.8.36". If null is provided, defaults to the latest release of the EE4
659
-     *                                     REST API
660
-     * @return array which can be passed into the EE4 REST API when querying a model resource
661
-     * @throws EE_Error
662
-     */
663
-    public static function prepareQueryParamsForRestApi(
664
-        array $model_query_params,
665
-        EEM_Base $model,
666
-        $requested_version = null
667
-    ) {
668
-        if ($requested_version === null) {
669
-            $requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
670
-        }
671
-        $rest_query_params = $model_query_params;
672
-        if (isset($model_query_params[0])) {
673
-            $rest_query_params['where'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
674
-                $model_query_params[0],
675
-                $model,
676
-                $requested_version
677
-            );
678
-            unset($rest_query_params[0]);
679
-        }
680
-        if (isset($model_query_params['having'])) {
681
-            $rest_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
682
-                $model_query_params['having'],
683
-                $model,
684
-                $requested_version
685
-            );
686
-        }
687
-        return apply_filters(
688
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
689
-            $rest_query_params,
690
-            $model_query_params,
691
-            $model,
692
-            $requested_version
693
-        );
694
-    }
695
-
696
-
697
-
698
-    /**
699
-     * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
700
-     *
701
-     * @param array     $inputted_query_params_of_this_type eg like the "where" or "having" conditions query params
702
-     *                                                      passed into EEM_Base::get_all()
703
-     * @param EEM_Base $model
704
-     * @param string    $requested_version                  eg "4.8.36"
705
-     * @return array ready for use in the rest api query params
706
-     * @throws EE_Error
707
-     * @throws ObjectDetectedException if somehow a PHP object were in the query params' values,
708
-     *                                     (which would be really unusual)
709
-     */
710
-    public static function prepareConditionsQueryParamsForRestApi(
711
-        $inputted_query_params_of_this_type,
712
-        EEM_Base $model,
713
-        $requested_version
714
-    ) {
715
-        $query_param_for_models = array();
716
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
717
-            $field = ModelDataTranslator::deduceFieldFromQueryParam(
718
-                ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($query_param_key),
719
-                $model
720
-            );
721
-            if ($field instanceof EE_Model_Field_Base) {
722
-                //did they specify an operator?
723
-                if (is_array($query_param_value)) {
724
-                    $op = $query_param_value[0];
725
-                    $translated_value = array($op);
726
-                    if (isset($query_param_value[1])) {
727
-                        $value = $query_param_value[1];
728
-                        $translated_value[1] = ModelDataTranslator::prepareFieldValuesForJson(
729
-                            $field,
730
-                            $value,
731
-                            $requested_version
732
-                        );
733
-                    }
734
-                } else {
735
-                    $translated_value = ModelDataTranslator::prepareFieldValueForJson(
736
-                        $field,
737
-                        $query_param_value,
738
-                        $requested_version
739
-                    );
740
-                }
741
-                $query_param_for_models[$query_param_key] = $translated_value;
742
-            } else {
743
-                //so it's not for a field, assume it's a logic query param key
744
-                $query_param_for_models[$query_param_key] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
745
-                    $query_param_value,
746
-                    $model,
747
-                    $requested_version
748
-                );
749
-            }
750
-        }
751
-        return $query_param_for_models;
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * @param $condition_query_param_key
758
-     * @return string
759
-     */
760
-    public static function removeStarsAndAnythingAfterFromConditionQueryParamKey($condition_query_param_key)
761
-    {
762
-        $pos_of_star = strpos($condition_query_param_key, '*');
763
-        if ($pos_of_star === false) {
764
-            return $condition_query_param_key;
765
-        } else {
766
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
767
-            return $condition_query_param_sans_star;
768
-        }
769
-    }
770
-
771
-
772
-
773
-    /**
774
-     * Takes the input parameter and finds the model field that it indicates.
775
-     *
776
-     * @param string    $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
777
-     * @param EEM_Base $model
778
-     * @return EE_Model_Field_Base
779
-     * @throws EE_Error
780
-     */
781
-    public static function deduceFieldFromQueryParam($query_param_name, EEM_Base $model)
782
-    {
783
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
784
-        //which will help us find the database table and column
785
-        $query_param_parts = explode('.', $query_param_name);
786
-        if (empty($query_param_parts)) {
787
-            throw new EE_Error(
788
-                sprintf(
789
-                    __(
790
-                        '_extract_column_name is empty when trying to extract column and table name from %s',
791
-                        'event_espresso'
792
-                    ),
793
-                    $query_param_name
794
-                )
795
-            );
796
-        }
797
-        $number_of_parts = count($query_param_parts);
798
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
799
-        if ($number_of_parts === 1) {
800
-            $field_name = $last_query_param_part;
801
-        } else {// $number_of_parts >= 2
802
-            //the last part is the column name, and there are only 2parts. therefore...
803
-            $field_name = $last_query_param_part;
804
-            $model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
805
-        }
806
-        try {
807
-            return $model->field_settings_for($field_name, false);
808
-        } catch (EE_Error $e) {
809
-            return null;
810
-        }
811
-    }
812
-
813
-
814
-
815
-    /**
816
-     * Returns true if $data can be easily represented in JSON.
817
-     * Basically, objects and resources can't be represented in JSON easily.
818
-     * @param mixed $data
819
-     * @return bool
820
-     */
821
-    protected static function isRepresentableInJson($data)
822
-    {
823
-        return is_scalar($data)
824
-               || is_array($data)
825
-               || is_null($data);
826
-    }
39
+	/**
40
+	 * We used to use -1 for infinity in the rest api, but that's ambiguous for
41
+	 * fields that COULD contain -1; so we use null
42
+	 */
43
+	const EE_INF_IN_REST = null;
44
+
45
+
46
+
47
+	/**
48
+	 * Prepares a possible array of input values from JSON for use by the models
49
+	 *
50
+	 * @param EE_Model_Field_Base $field_obj
51
+	 * @param mixed                $original_value_maybe_array
52
+	 * @param string               $requested_version
53
+	 * @param string               $timezone_string treat values as being in this timezone
54
+	 * @return mixed
55
+	 * @throws RestException
56
+	 */
57
+	public static function prepareFieldValuesFromJson(
58
+		$field_obj,
59
+		$original_value_maybe_array,
60
+		$requested_version,
61
+		$timezone_string = 'UTC'
62
+	) {
63
+		if (is_array($original_value_maybe_array)
64
+			&& ! $field_obj instanceof EE_Serialized_Text_Field
65
+		) {
66
+			$new_value_maybe_array = array();
67
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
68
+				$new_value_maybe_array[$array_key] = ModelDataTranslator::prepareFieldValueFromJson(
69
+					$field_obj,
70
+					$array_item,
71
+					$requested_version,
72
+					$timezone_string
73
+				);
74
+			}
75
+		} else {
76
+			$new_value_maybe_array = ModelDataTranslator::prepareFieldValueFromJson(
77
+				$field_obj,
78
+				$original_value_maybe_array,
79
+				$requested_version,
80
+				$timezone_string
81
+			);
82
+		}
83
+		return $new_value_maybe_array;
84
+	}
85
+
86
+
87
+
88
+	/**
89
+	 * Prepares an array of field values FOR use in JSON/REST API
90
+	 *
91
+	 * @param EE_Model_Field_Base $field_obj
92
+	 * @param mixed                $original_value_maybe_array
93
+	 * @param string               $request_version (eg 4.8.36)
94
+	 * @return array
95
+	 */
96
+	public static function prepareFieldValuesForJson($field_obj, $original_value_maybe_array, $request_version)
97
+	{
98
+		if (is_array($original_value_maybe_array)) {
99
+			$new_value = array();
100
+			foreach ($original_value_maybe_array as $key => $value) {
101
+				$new_value[$key] = ModelDataTranslator::prepareFieldValuesForJson($field_obj, $value, $request_version);
102
+			}
103
+		} else {
104
+			$new_value = ModelDataTranslator::prepareFieldValueForJson(
105
+				$field_obj,
106
+				$original_value_maybe_array,
107
+				$request_version
108
+			);
109
+		}
110
+		return $new_value;
111
+	}
112
+
113
+
114
+
115
+	/**
116
+	 * Prepares incoming data from the json or $_REQUEST parameters for the models'
117
+	 * "$query_params".
118
+	 *
119
+	 * @param EE_Model_Field_Base $field_obj
120
+	 * @param mixed                $original_value
121
+	 * @param string               $requested_version
122
+	 * @param string               $timezone_string treat values as being in this timezone
123
+	 * @return mixed
124
+	 * @throws RestException
125
+	 */
126
+	public static function prepareFieldValueFromJson(
127
+		$field_obj,
128
+		$original_value,
129
+		$requested_version,
130
+		$timezone_string = 'UTC' // UTC
131
+	) {
132
+		//check if they accidentally submitted an error value. If so throw an exception
133
+		if (is_array($original_value)
134
+			&& isset($original_value['error_code'], $original_value['error_message'])) {
135
+			throw new RestException(
136
+				'rest_submitted_error_value',
137
+				sprintf(
138
+					esc_html__(
139
+						'You tried to submit a JSON error object as a value for %1$s. That\'s not allowed.',
140
+						'event_espresso'
141
+					),
142
+					$field_obj->get_name()
143
+				),
144
+				array(
145
+					'status' => 400,
146
+				)
147
+			);
148
+		}
149
+		//double-check for serialized PHP. We never accept serialized PHP. No way Jose.
150
+		ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
151
+		$timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
152
+		$new_value = null;
153
+		//walk through the submitted data and double-check for serialized PHP. We never accept serialized PHP. No
154
+		// way Jose.
155
+		ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
156
+		if ($field_obj instanceof EE_Infinite_Integer_Field
157
+			&& in_array($original_value, array(null, ''), true)
158
+		) {
159
+			$new_value = EE_INF;
160
+		} elseif ($field_obj instanceof EE_Datetime_Field) {
161
+			list($offset_sign, $offset_secs) = ModelDataTranslator::parseTimezoneOffset(
162
+				$field_obj->get_timezone_offset(
163
+					new \DateTimeZone($timezone_string),
164
+					$original_value
165
+				)
166
+			);
167
+			$offset_string =
168
+				str_pad(
169
+					floor($offset_secs / HOUR_IN_SECONDS),
170
+					2,
171
+					'0',
172
+					STR_PAD_LEFT
173
+				)
174
+				. ':'
175
+				. str_pad(
176
+					($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
177
+					2,
178
+					'0',
179
+					STR_PAD_LEFT
180
+				);
181
+			$new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
182
+		} else {
183
+			$new_value = $original_value;
184
+		}
185
+		return $new_value;
186
+	}
187
+
188
+
189
+
190
+	/**
191
+	 * Throws an exception if $data is a serialized PHP string (or somehow an actually PHP object, although I don't
192
+	 * think that can happen). If $data is an array, recurses into its keys and values
193
+	 * @param mixed $data
194
+	 * @throws RestException
195
+	 * @return void
196
+	 */
197
+	public static function throwExceptionIfContainsSerializedData($data)
198
+	{
199
+		if (is_array($data)) {
200
+			foreach ($data as $key => $value) {
201
+				ModelDataTranslator::throwExceptionIfContainsSerializedData($key);
202
+				ModelDataTranslator::throwExceptionIfContainsSerializedData($value);
203
+			}
204
+		} else {
205
+			if (is_serialized($data) || is_object($data)) {
206
+				throw new RestException(
207
+					'serialized_data_submission_prohibited',
208
+					esc_html__(
209
+						// @codingStandardsIgnoreStart
210
+						'You tried to submit a string of serialized text. Serialized PHP is prohibited over the EE4 REST API.',
211
+						// @codingStandardsIgnoreEnd
212
+						'event_espresso'
213
+					)
214
+				);
215
+			}
216
+		}
217
+	}
218
+
219
+
220
+
221
+	/**
222
+	 * determines what's going on with them timezone strings
223
+	 *
224
+	 * @param int $timezone_offset
225
+	 * @return array
226
+	 */
227
+	private static function parseTimezoneOffset($timezone_offset)
228
+	{
229
+		$first_char = substr((string)$timezone_offset, 0, 1);
230
+		if ($first_char === '+' || $first_char === '-') {
231
+			$offset_sign = $first_char;
232
+			$offset_secs = substr((string)$timezone_offset, 1);
233
+		} else {
234
+			$offset_sign = '+';
235
+			$offset_secs = $timezone_offset;
236
+		}
237
+		return array($offset_sign, $offset_secs);
238
+	}
239
+
240
+
241
+
242
+	/**
243
+	 * Prepares a field's value for display in the API
244
+	 *
245
+	 * @param EE_Model_Field_Base $field_obj
246
+	 * @param mixed                $original_value
247
+	 * @param string               $requested_version
248
+	 * @return mixed
249
+	 */
250
+	public static function prepareFieldValueForJson($field_obj, $original_value, $requested_version)
251
+	{
252
+		if ($original_value === EE_INF) {
253
+			$new_value = ModelDataTranslator::EE_INF_IN_REST;
254
+		} elseif ($field_obj instanceof EE_Datetime_Field) {
255
+			if (is_string($original_value)) {
256
+				//did they submit a string of a unix timestamp?
257
+				if (is_numeric($original_value)) {
258
+					$datetime_obj = new \DateTime();
259
+					$datetime_obj->setTimestamp((int)$original_value);
260
+				} else {
261
+					//first, check if its a MySQL timestamp in GMT
262
+					$datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
263
+				}
264
+				if (! $datetime_obj instanceof \DateTime) {
265
+					//so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
266
+					$datetime_obj = $field_obj->prepare_for_set($original_value);
267
+				}
268
+				$original_value = $datetime_obj;
269
+			}
270
+			if ($original_value instanceof \DateTime) {
271
+				$new_value = $original_value->format('Y-m-d H:i:s');
272
+			} elseif (is_int($original_value) || is_float($original_value)) {
273
+				$new_value = date('Y-m-d H:i:s', $original_value);
274
+			} elseif($original_value === null || $original_value === '') {
275
+				$new_value = null;
276
+			} else {
277
+				//so it's not a datetime object, unix timestamp (as string or int),
278
+				//MySQL timestamp, or even a string in the field object's format. So no idea what it is
279
+				throw new \EE_Error(
280
+					sprintf(
281
+						esc_html__(
282
+						// @codingStandardsIgnoreStart
283
+							'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
284
+							// @codingStandardsIgnoreEnd
285
+							'event_espressso'
286
+						),
287
+						$original_value,
288
+						$field_obj->get_name(),
289
+						$field_obj->get_model_name(),
290
+						$field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
291
+					)
292
+				);
293
+			}
294
+			$new_value = mysql_to_rfc3339($new_value);
295
+		} else {
296
+			$new_value = $original_value;
297
+		}
298
+		//are we about to send an object? just don't. We have no good way to represent it in JSON.
299
+		// can't just check using is_object() because that missed PHP incomplete objects
300
+		if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
301
+			$new_value = array(
302
+				'error_code' => 'php_object_not_return',
303
+				'error_message' => esc_html__('The value of this field in the database is a PHP object, which can\'t be represented in JSON.', 'event_espresso')
304
+			);
305
+		}
306
+		return apply_filters(
307
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
308
+			$new_value,
309
+			$field_obj,
310
+			$original_value,
311
+			$requested_version
312
+		);
313
+	}
314
+
315
+
316
+
317
+	/**
318
+	 * Prepares condition-query-parameters (like what's in where and having) from
319
+	 * the format expected in the API to use in the models
320
+	 *
321
+	 * @param array     $inputted_query_params_of_this_type
322
+	 * @param EEM_Base $model
323
+	 * @param string    $requested_version
324
+	 * @param boolean $writing whether this data will be written to the DB, or if we're just building a query.
325
+	 *                         If we're writing to the DB, we don't expect any operators, or any logic query parameters,
326
+	 *                         and we also won't accept serialized data unless the current user has unfiltered_html.
327
+	 * @return array
328
+	 * @throws \DomainException
329
+	 * @throws RestException
330
+	 * @throws EE_Error
331
+	 */
332
+	public static function prepareConditionsQueryParamsForModels(
333
+		$inputted_query_params_of_this_type,
334
+		EEM_Base $model,
335
+		$requested_version,
336
+		$writing = false
337
+	) {
338
+		$query_param_for_models = array();
339
+		$valid_operators = $model->valid_operators();
340
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
341
+			$is_gmt_datetime_field = false;
342
+			$query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
343
+				$query_param_key
344
+			);
345
+			$field = ModelDataTranslator::deduceFieldFromQueryParam(
346
+				$query_param_sans_stars,
347
+				$model
348
+			);
349
+			//double-check is it a *_gmt field?
350
+			if (! $field instanceof EE_Model_Field_Base
351
+				&& ModelDataTranslator::isGmtDateFieldName($query_param_sans_stars)
352
+			) {
353
+				//yep, take off '_gmt', and find the field
354
+				$query_param_key = ModelDataTranslator::removeGmtFromFieldName($query_param_sans_stars);
355
+				$field = ModelDataTranslator::deduceFieldFromQueryParam(
356
+					$query_param_key,
357
+					$model
358
+				);
359
+				$timezone = 'UTC';
360
+				$is_gmt_datetime_field = true;
361
+			} elseif ($field instanceof EE_Datetime_Field) {
362
+				//so it's not a GMT field. Set the timezone on the model to the default
363
+				$timezone = \EEH_DTT_Helper::get_valid_timezone_string();
364
+			} else {
365
+				//just keep using what's already set for the timezone
366
+				$timezone = $model->get_timezone();
367
+			}
368
+			if ($field instanceof EE_Model_Field_Base) {
369
+				if (! $writing && is_array($query_param_value)) {
370
+					if (! \EEH_Array::is_array_numerically_and_sequentially_indexed($query_param_value)) {
371
+						if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
372
+							throw new RestException(
373
+								'numerically_indexed_array_of_values_only',
374
+								sprintf(
375
+									esc_html__(
376
+										'The array provided for the parameter "%1$s" should be numerically indexed.',
377
+										'event_espresso'
378
+									),
379
+									$query_param_key
380
+								),
381
+								array(
382
+									'status' => 400,
383
+								)
384
+							);
385
+						}
386
+					}
387
+					//did they specify an operator?
388
+					if (isset($query_param_value[0])
389
+						&& isset($valid_operators[$query_param_value[0]])
390
+					) {
391
+						$op = $query_param_value[0];
392
+						$translated_value = array($op);
393
+						if (array_key_exists($op, $model->valid_in_style_operators())
394
+							&& isset($query_param_value[1])
395
+							&& ! isset($query_param_value[2])
396
+						) {
397
+							$translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
398
+								$field,
399
+								$query_param_value[1],
400
+								$requested_version,
401
+								$timezone
402
+							);
403
+						} elseif (array_key_exists($op, $model->valid_between_style_operators())
404
+							&& isset($query_param_value[1], $query_param_value[2])
405
+							&& !isset($query_param_value[3])
406
+						) {
407
+							$translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
408
+								$field,
409
+								$query_param_value[1],
410
+								$requested_version,
411
+								$timezone
412
+							);
413
+							$translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
414
+								$field,
415
+								$query_param_value[2],
416
+								$requested_version,
417
+								$timezone
418
+							);
419
+						} elseif (array_key_exists($op, $model->valid_like_style_operators())
420
+							&& isset($query_param_value[1])
421
+							&& ! isset($query_param_value[2])
422
+						) {
423
+							//we want to leave this value mostly-as-is (eg don't force it to be a float
424
+							//or a boolean or an enum value. Leave it as-is with wildcards etc)
425
+							//but do verify it at least doesn't have any serialized data
426
+							ModelDataTranslator::throwExceptionIfContainsSerializedData($query_param_value[1]);
427
+							$translated_value[] = $query_param_value[1];
428
+						} elseif (array_key_exists($op, $model->valid_null_style_operators())
429
+							&& !isset($query_param_value[1])) {
430
+							//no arguments should have been provided, so don't look for any
431
+						} elseif (isset($query_param_value[1])
432
+							&& !isset($query_param_value[2])
433
+							&& ! array_key_exists(
434
+								$op,
435
+								array_merge(
436
+									$model->valid_in_style_operators(),
437
+									$model->valid_null_style_operators(),
438
+									$model->valid_like_style_operators(),
439
+									$model->valid_between_style_operators()
440
+								)
441
+							)
442
+						) {
443
+							//it's a valid operator, but none of the exceptions. Treat it normally.
444
+							$translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
445
+								$field,
446
+								$query_param_value[1],
447
+								$requested_version,
448
+								$timezone
449
+							);
450
+						} else {
451
+							//so they provided a valid operator, but wrong number of arguments
452
+							if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
453
+								throw new RestException(
454
+									'wrong_number_of_arguments',
455
+									sprintf(
456
+										esc_html__(
457
+											'The operator you provided, "%1$s" had the wrong number of arguments',
458
+											'event_espresso'
459
+										),
460
+										$op
461
+									),
462
+									array(
463
+										'status' => 400,
464
+									)
465
+								);
466
+							}
467
+							$translated_value = null;
468
+						}
469
+					} else {
470
+						//so they didn't provide a valid operator
471
+						if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
472
+							throw new RestException(
473
+								'invalid_operator',
474
+								sprintf(
475
+									esc_html__(
476
+										'You provided an invalid parameter, with key "%1$s" and value "%2$s"',
477
+										'event_espresso'
478
+									),
479
+									$query_param_key,
480
+									$query_param_value
481
+								),
482
+								array(
483
+									'status' => 400,
484
+								)
485
+							);
486
+						}
487
+						//if we aren't in debug mode, then just try our best to fulfill the user's request
488
+						$translated_value = null;
489
+					}
490
+				} else {
491
+					$translated_value = ModelDataTranslator::prepareFieldValueFromJson(
492
+						$field,
493
+						$query_param_value,
494
+						$requested_version,
495
+						$timezone
496
+					);
497
+				}
498
+				if (
499
+					(isset($query_param_for_models[$query_param_key]) && $is_gmt_datetime_field)
500
+					||
501
+					$translated_value === null
502
+				) {
503
+					//they have already provided a non-gmt field, ignore the gmt one. That's what WP core
504
+					//currently does (they might change it though). See https://core.trac.wordpress.org/ticket/39954
505
+					//OR we couldn't create a translated value from their input
506
+					continue;
507
+				}
508
+				$query_param_for_models[$query_param_key] = $translated_value;
509
+			} else {
510
+				//so this param doesn't correspond to a field eh?
511
+				if ($writing) {
512
+					//always tell API clients about invalid parameters when they're creating data. Otherwise,
513
+					//they are probably going to create invalid data
514
+					throw new RestException(
515
+						'invalid_field',
516
+						sprintf(
517
+							esc_html__('You have provided an invalid parameter: "%1$s"', 'event_espresso'),
518
+							$query_param_key
519
+						)
520
+					);
521
+				} else {
522
+					//so it's not for a field, is it a logic query param key?
523
+					if (in_array(
524
+						$query_param_sans_stars,
525
+						$model->logic_query_param_keys()
526
+					)) {
527
+						$query_param_for_models[$query_param_key] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
528
+							$query_param_value,
529
+							$model,
530
+							$requested_version
531
+						);
532
+					} elseif (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
533
+						//only tell API clients they got it wrong if we're in debug mode
534
+						//otherwise try our best ot fulfill their request by ignoring this invalid data
535
+						throw new RestException(
536
+							'invalid_parameter',
537
+							sprintf(
538
+								esc_html__(
539
+									'You provided an invalid parameter, with key "%1$s"',
540
+									'event_espresso'
541
+								),
542
+								$query_param_sans_stars
543
+							),
544
+							array(
545
+								'status' => 400,
546
+							)
547
+						);
548
+					}
549
+				}
550
+			}
551
+		}
552
+		return $query_param_for_models;
553
+	}
554
+
555
+
556
+
557
+	/**
558
+	 * Mostly checks if the last 4 characters are "_gmt", indicating its a
559
+	 * gmt date field name
560
+	 *
561
+	 * @param string $field_name
562
+	 * @return boolean
563
+	 */
564
+	public static function isGmtDateFieldName($field_name)
565
+	{
566
+		return substr(
567
+			ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($field_name),
568
+			-4,
569
+			4
570
+		) === '_gmt';
571
+	}
572
+
573
+
574
+
575
+	/**
576
+	 * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
577
+	 *
578
+	 * @param string $field_name
579
+	 * @return string
580
+	 */
581
+	public static function removeGmtFromFieldName($field_name)
582
+	{
583
+		if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
584
+			return $field_name;
585
+		}
586
+		$query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
587
+			$field_name
588
+		);
589
+		$query_param_sans_gmt_and_sans_stars = substr(
590
+			$query_param_sans_stars,
591
+			0,
592
+			strrpos(
593
+				$field_name,
594
+				'_gmt'
595
+			)
596
+		);
597
+		return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
598
+	}
599
+
600
+
601
+
602
+	/**
603
+	 * Takes a field name from the REST API and prepares it for the model querying
604
+	 *
605
+	 * @param string $field_name
606
+	 * @return string
607
+	 */
608
+	public static function prepareFieldNameFromJson($field_name)
609
+	{
610
+		if (ModelDataTranslator::isGmtDateFieldName($field_name)) {
611
+			return ModelDataTranslator::removeGmtFromFieldName($field_name);
612
+		}
613
+		return $field_name;
614
+	}
615
+
616
+
617
+
618
+	/**
619
+	 * Takes array of field names from REST API and prepares for models
620
+	 *
621
+	 * @param array $field_names
622
+	 * @return array of field names (possibly include model prefixes)
623
+	 */
624
+	public static function prepareFieldNamesFromJson(array $field_names)
625
+	{
626
+		$new_array = array();
627
+		foreach ($field_names as $key => $field_name) {
628
+			$new_array[$key] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
629
+		}
630
+		return $new_array;
631
+	}
632
+
633
+
634
+
635
+	/**
636
+	 * Takes array where array keys are field names (possibly with model path prefixes)
637
+	 * from the REST API and prepares them for model querying
638
+	 *
639
+	 * @param array $field_names_as_keys
640
+	 * @return array
641
+	 */
642
+	public static function prepareFieldNamesInArrayKeysFromJson(array $field_names_as_keys)
643
+	{
644
+		$new_array = array();
645
+		foreach ($field_names_as_keys as $field_name => $value) {
646
+			$new_array[ModelDataTranslator::prepareFieldNameFromJson($field_name)] = $value;
647
+		}
648
+		return $new_array;
649
+	}
650
+
651
+
652
+
653
+	/**
654
+	 * Prepares an array of model query params for use in the REST API
655
+	 *
656
+	 * @param array     $model_query_params
657
+	 * @param EEM_Base $model
658
+	 * @param string    $requested_version eg "4.8.36". If null is provided, defaults to the latest release of the EE4
659
+	 *                                     REST API
660
+	 * @return array which can be passed into the EE4 REST API when querying a model resource
661
+	 * @throws EE_Error
662
+	 */
663
+	public static function prepareQueryParamsForRestApi(
664
+		array $model_query_params,
665
+		EEM_Base $model,
666
+		$requested_version = null
667
+	) {
668
+		if ($requested_version === null) {
669
+			$requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
670
+		}
671
+		$rest_query_params = $model_query_params;
672
+		if (isset($model_query_params[0])) {
673
+			$rest_query_params['where'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
674
+				$model_query_params[0],
675
+				$model,
676
+				$requested_version
677
+			);
678
+			unset($rest_query_params[0]);
679
+		}
680
+		if (isset($model_query_params['having'])) {
681
+			$rest_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
682
+				$model_query_params['having'],
683
+				$model,
684
+				$requested_version
685
+			);
686
+		}
687
+		return apply_filters(
688
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
689
+			$rest_query_params,
690
+			$model_query_params,
691
+			$model,
692
+			$requested_version
693
+		);
694
+	}
695
+
696
+
697
+
698
+	/**
699
+	 * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
700
+	 *
701
+	 * @param array     $inputted_query_params_of_this_type eg like the "where" or "having" conditions query params
702
+	 *                                                      passed into EEM_Base::get_all()
703
+	 * @param EEM_Base $model
704
+	 * @param string    $requested_version                  eg "4.8.36"
705
+	 * @return array ready for use in the rest api query params
706
+	 * @throws EE_Error
707
+	 * @throws ObjectDetectedException if somehow a PHP object were in the query params' values,
708
+	 *                                     (which would be really unusual)
709
+	 */
710
+	public static function prepareConditionsQueryParamsForRestApi(
711
+		$inputted_query_params_of_this_type,
712
+		EEM_Base $model,
713
+		$requested_version
714
+	) {
715
+		$query_param_for_models = array();
716
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
717
+			$field = ModelDataTranslator::deduceFieldFromQueryParam(
718
+				ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($query_param_key),
719
+				$model
720
+			);
721
+			if ($field instanceof EE_Model_Field_Base) {
722
+				//did they specify an operator?
723
+				if (is_array($query_param_value)) {
724
+					$op = $query_param_value[0];
725
+					$translated_value = array($op);
726
+					if (isset($query_param_value[1])) {
727
+						$value = $query_param_value[1];
728
+						$translated_value[1] = ModelDataTranslator::prepareFieldValuesForJson(
729
+							$field,
730
+							$value,
731
+							$requested_version
732
+						);
733
+					}
734
+				} else {
735
+					$translated_value = ModelDataTranslator::prepareFieldValueForJson(
736
+						$field,
737
+						$query_param_value,
738
+						$requested_version
739
+					);
740
+				}
741
+				$query_param_for_models[$query_param_key] = $translated_value;
742
+			} else {
743
+				//so it's not for a field, assume it's a logic query param key
744
+				$query_param_for_models[$query_param_key] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
745
+					$query_param_value,
746
+					$model,
747
+					$requested_version
748
+				);
749
+			}
750
+		}
751
+		return $query_param_for_models;
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * @param $condition_query_param_key
758
+	 * @return string
759
+	 */
760
+	public static function removeStarsAndAnythingAfterFromConditionQueryParamKey($condition_query_param_key)
761
+	{
762
+		$pos_of_star = strpos($condition_query_param_key, '*');
763
+		if ($pos_of_star === false) {
764
+			return $condition_query_param_key;
765
+		} else {
766
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
767
+			return $condition_query_param_sans_star;
768
+		}
769
+	}
770
+
771
+
772
+
773
+	/**
774
+	 * Takes the input parameter and finds the model field that it indicates.
775
+	 *
776
+	 * @param string    $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
777
+	 * @param EEM_Base $model
778
+	 * @return EE_Model_Field_Base
779
+	 * @throws EE_Error
780
+	 */
781
+	public static function deduceFieldFromQueryParam($query_param_name, EEM_Base $model)
782
+	{
783
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
784
+		//which will help us find the database table and column
785
+		$query_param_parts = explode('.', $query_param_name);
786
+		if (empty($query_param_parts)) {
787
+			throw new EE_Error(
788
+				sprintf(
789
+					__(
790
+						'_extract_column_name is empty when trying to extract column and table name from %s',
791
+						'event_espresso'
792
+					),
793
+					$query_param_name
794
+				)
795
+			);
796
+		}
797
+		$number_of_parts = count($query_param_parts);
798
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
799
+		if ($number_of_parts === 1) {
800
+			$field_name = $last_query_param_part;
801
+		} else {// $number_of_parts >= 2
802
+			//the last part is the column name, and there are only 2parts. therefore...
803
+			$field_name = $last_query_param_part;
804
+			$model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
805
+		}
806
+		try {
807
+			return $model->field_settings_for($field_name, false);
808
+		} catch (EE_Error $e) {
809
+			return null;
810
+		}
811
+	}
812
+
813
+
814
+
815
+	/**
816
+	 * Returns true if $data can be easily represented in JSON.
817
+	 * Basically, objects and resources can't be represented in JSON easily.
818
+	 * @param mixed $data
819
+	 * @return bool
820
+	 */
821
+	protected static function isRepresentableInJson($data)
822
+	{
823
+		return is_scalar($data)
824
+			   || is_array($data)
825
+			   || is_null($data);
826
+	}
827 827
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -10,7 +10,7 @@  discard block
 block discarded – undo
10 10
 use EE_Serialized_Text_Field;
11 11
 use EEM_Base;
12 12
 
13
-if (! defined('EVENT_ESPRESSO_VERSION')) {
13
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
14 14
     exit('No direct script access allowed');
15 15
 }
16 16
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
                     '0',
179 179
                     STR_PAD_LEFT
180 180
                 );
181
-            $new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
181
+            $new_value = rest_parse_date($original_value.$offset_sign.$offset_string);
182 182
         } else {
183 183
             $new_value = $original_value;
184 184
         }
@@ -226,10 +226,10 @@  discard block
 block discarded – undo
226 226
      */
227 227
     private static function parseTimezoneOffset($timezone_offset)
228 228
     {
229
-        $first_char = substr((string)$timezone_offset, 0, 1);
229
+        $first_char = substr((string) $timezone_offset, 0, 1);
230 230
         if ($first_char === '+' || $first_char === '-') {
231 231
             $offset_sign = $first_char;
232
-            $offset_secs = substr((string)$timezone_offset, 1);
232
+            $offset_secs = substr((string) $timezone_offset, 1);
233 233
         } else {
234 234
             $offset_sign = '+';
235 235
             $offset_secs = $timezone_offset;
@@ -256,12 +256,12 @@  discard block
 block discarded – undo
256 256
                 //did they submit a string of a unix timestamp?
257 257
                 if (is_numeric($original_value)) {
258 258
                     $datetime_obj = new \DateTime();
259
-                    $datetime_obj->setTimestamp((int)$original_value);
259
+                    $datetime_obj->setTimestamp((int) $original_value);
260 260
                 } else {
261 261
                     //first, check if its a MySQL timestamp in GMT
262 262
                     $datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
263 263
                 }
264
-                if (! $datetime_obj instanceof \DateTime) {
264
+                if ( ! $datetime_obj instanceof \DateTime) {
265 265
                     //so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
266 266
                     $datetime_obj = $field_obj->prepare_for_set($original_value);
267 267
                 }
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
                 $new_value = $original_value->format('Y-m-d H:i:s');
272 272
             } elseif (is_int($original_value) || is_float($original_value)) {
273 273
                 $new_value = date('Y-m-d H:i:s', $original_value);
274
-            } elseif($original_value === null || $original_value === '') {
274
+            } elseif ($original_value === null || $original_value === '') {
275 275
                 $new_value = null;
276 276
             } else {
277 277
                 //so it's not a datetime object, unix timestamp (as string or int),
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
                         $original_value,
288 288
                         $field_obj->get_name(),
289 289
                         $field_obj->get_model_name(),
290
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
290
+                        $field_obj->get_time_format().' '.$field_obj->get_time_format()
291 291
                     )
292 292
                 );
293 293
             }
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
         }
298 298
         //are we about to send an object? just don't. We have no good way to represent it in JSON.
299 299
         // can't just check using is_object() because that missed PHP incomplete objects
300
-        if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
300
+        if ( ! ModelDataTranslator::isRepresentableInJson($new_value)) {
301 301
             $new_value = array(
302 302
                 'error_code' => 'php_object_not_return',
303 303
                 'error_message' => esc_html__('The value of this field in the database is a PHP object, which can\'t be represented in JSON.', 'event_espresso')
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
                 $model
348 348
             );
349 349
             //double-check is it a *_gmt field?
350
-            if (! $field instanceof EE_Model_Field_Base
350
+            if ( ! $field instanceof EE_Model_Field_Base
351 351
                 && ModelDataTranslator::isGmtDateFieldName($query_param_sans_stars)
352 352
             ) {
353 353
                 //yep, take off '_gmt', and find the field
@@ -366,8 +366,8 @@  discard block
 block discarded – undo
366 366
                 $timezone = $model->get_timezone();
367 367
             }
368 368
             if ($field instanceof EE_Model_Field_Base) {
369
-                if (! $writing && is_array($query_param_value)) {
370
-                    if (! \EEH_Array::is_array_numerically_and_sequentially_indexed($query_param_value)) {
369
+                if ( ! $writing && is_array($query_param_value)) {
370
+                    if ( ! \EEH_Array::is_array_numerically_and_sequentially_indexed($query_param_value)) {
371 371
                         if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
372 372
                             throw new RestException(
373 373
                                 'numerically_indexed_array_of_values_only',
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
                             );
403 403
                         } elseif (array_key_exists($op, $model->valid_between_style_operators())
404 404
                             && isset($query_param_value[1], $query_param_value[2])
405
-                            && !isset($query_param_value[3])
405
+                            && ! isset($query_param_value[3])
406 406
                         ) {
407 407
                             $translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
408 408
                                 $field,
@@ -426,10 +426,10 @@  discard block
 block discarded – undo
426 426
                             ModelDataTranslator::throwExceptionIfContainsSerializedData($query_param_value[1]);
427 427
                             $translated_value[] = $query_param_value[1];
428 428
                         } elseif (array_key_exists($op, $model->valid_null_style_operators())
429
-                            && !isset($query_param_value[1])) {
429
+                            && ! isset($query_param_value[1])) {
430 430
                             //no arguments should have been provided, so don't look for any
431 431
                         } elseif (isset($query_param_value[1])
432
-                            && !isset($query_param_value[2])
432
+                            && ! isset($query_param_value[2])
433 433
                             && ! array_key_exists(
434 434
                                 $op,
435 435
                                 array_merge(
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
      */
581 581
     public static function removeGmtFromFieldName($field_name)
582 582
     {
583
-        if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
583
+        if ( ! ModelDataTranslator::isGmtDateFieldName($field_name)) {
584 584
             return $field_name;
585 585
         }
586 586
         $query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
Please login to merge, or discard this patch.