Completed
Branch decaf-fixes/sanitize-all-reque... (b7fe86)
by
unknown
06:39 queued 04:47
created
core/services/shortcodes/EspressoShortcode.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -20,223 +20,223 @@
 block discarded – undo
20 20
 abstract class EspressoShortcode implements ShortcodeInterface
21 21
 {
22 22
 
23
-    /**
24
-     * transient prefix
25
-     *
26
-     * @type string
27
-     */
28
-    const CACHE_TRANSIENT_PREFIX = 'ee_sc_';
29
-
30
-    /**
31
-     * @var PostRelatedCacheManager $cache_manager
32
-     */
33
-    private $cache_manager;
34
-
35
-    /**
36
-     * true if ShortcodeInterface::initializeShortcode() has been called
37
-     * if false, then that will get called before processing
38
-     *
39
-     * @var boolean $initialized
40
-     */
41
-    private $initialized = false;
42
-
43
-
44
-    /**
45
-     * EspressoShortcode constructor
46
-     *
47
-     * @param PostRelatedCacheManager $cache_manager
48
-     */
49
-    public function __construct(PostRelatedCacheManager $cache_manager)
50
-    {
51
-        $this->cache_manager = $cache_manager;
52
-    }
53
-
54
-
55
-    /**
56
-     * @return void
57
-     */
58
-    public function shortcodeHasBeenInitialized()
59
-    {
60
-        $this->initialized = true;
61
-    }
62
-
63
-
64
-    /**
65
-     * enqueues scripts then processes the shortcode
66
-     *
67
-     * @param array $attributes
68
-     * @return string
69
-     * @throws EE_Error
70
-     * @throws ReflectionException
71
-     */
72
-    final public function processShortcodeCallback($attributes = array())
73
-    {
74
-        if ($this instanceof EnqueueAssetsInterface) {
75
-            if (is_admin()) {
76
-                $this->enqueueAdminScripts();
77
-            } else {
78
-                $this->enqueueScripts();
79
-            }
80
-        }
81
-        return $this->shortcodeContent(
82
-            $this->sanitizeAttributes((array) $attributes)
83
-        );
84
-    }
85
-
86
-
87
-    /**
88
-     * If shortcode caching is enabled for the shortcode,
89
-     * and cached results exist, then that will be returned
90
-     * else new content will be generated.
91
-     * If caching is enabled, then the new content will be cached for later.
92
-     *
93
-     * @param array $attributes
94
-     * @return mixed|string
95
-     * @throws EE_Error
96
-     * @throws ReflectionException
97
-     */
98
-    private function shortcodeContent(array $attributes)
99
-    {
100
-        $shortcode = $this;
101
-        $post_ID = $this->currentPostID();
102
-        // something like "SC_EVENTS-123"
103
-        $cache_ID = $this->shortcodeCacheID($post_ID);
104
-        $this->cache_manager->clearPostRelatedCacheOnUpdate($post_ID, $cache_ID);
105
-        return $this->cache_manager->get(
106
-            $cache_ID,
107
-            // serialized attributes
108
-            wp_json_encode($attributes),
109
-            // Closure for generating content if cache is expired
110
-            function () use ($shortcode, $attributes) {
111
-                if ($shortcode->initialized() === false) {
112
-                    $shortcode->initializeShortcode();
113
-                }
114
-                return $shortcode->processShortcode($attributes);
115
-            },
116
-            // filterable cache expiration set by each shortcode
117
-            apply_filters(
118
-                'FHEE__EventEspresso_core_services_shortcodes_EspressoShortcode__shortcodeContent__cache_expiration',
119
-                $this->cacheExpiration(),
120
-                $this->getTag(),
121
-                $this
122
-            )
123
-        );
124
-    }
125
-
126
-
127
-    /**
128
-     * @return int
129
-     * @throws EE_Error
130
-     * @throws ReflectionException
131
-     */
132
-    private function currentPostID()
133
-    {
134
-        // try to get EE_Event any way we can
135
-        $event = EEH_Event_View::get_event();
136
-        // then get some kind of ID
137
-        if ($event instanceof EE_Event) {
138
-            return $event->ID();
139
-        }
140
-        global $post;
141
-        if ($post instanceof WP_Post) {
142
-            return $post->ID;
143
-        }
144
-        return 0;
145
-    }
146
-
147
-
148
-    /**
149
-     * @param int $post_ID
150
-     * @return string
151
-     */
152
-    private function shortcodeCacheID($post_ID)
153
-    {
154
-        $tag = str_replace('ESPRESSO_', '', $this->getTag());
155
-        return "SC_{$tag}-{$post_ID}";
156
-    }
157
-
158
-
159
-    /**
160
-     * array for defining custom attribute sanitization callbacks,
161
-     * where keys match keys in your attributes array,
162
-     * and values represent the sanitization function you wish to be applied to that attribute.
163
-     * So for example, if you had an integer attribute named "event_id"
164
-     * that you wanted to be sanitized using absint(),
165
-     * then you would return the following:
166
-     *      array('event_id' => 'absint')
167
-     * Entering 'skip_sanitization' for the callback value
168
-     * means that no sanitization will be applied
169
-     * on the assumption that the attribute
170
-     * will be sanitized at some point... right?
171
-     * You wouldn't pass around unsanitized attributes would you?
172
-     * That would be very Tom Foolery of you!!!
173
-     *
174
-     * @return array
175
-     */
176
-    protected function customAttributeSanitizationMap()
177
-    {
178
-        return array();
179
-    }
180
-
181
-
182
-    /**
183
-     * Performs basic sanitization on shortcode attributes
184
-     * Since incoming attributes from the shortcode usage in the WP editor will all be strings,
185
-     * most attributes will by default be sanitized using the sanitize_text_field() function.
186
-     * This can be overridden using the customAttributeSanitizationMap() method (see above),
187
-     * all other attributes would be sanitized using the defaults in the switch statement below
188
-     *
189
-     * @param array $attributes
190
-     * @return array
191
-     */
192
-    private function sanitizeAttributes(array $attributes)
193
-    {
194
-        $custom_sanitization = $this->customAttributeSanitizationMap();
195
-        foreach ($attributes as $key => $value) {
196
-            // is a custom sanitization callback specified ?
197
-            if (isset($custom_sanitization[ $key ])) {
198
-                $callback = $custom_sanitization[ $key ];
199
-                if ($callback === 'skip_sanitization') {
200
-                    $attributes[ $key ] = $value;
201
-                    continue;
202
-                }
203
-                if (function_exists($callback)) {
204
-                    $attributes[ $key ] = $callback($value);
205
-                    continue;
206
-                }
207
-            }
208
-            switch (true) {
209
-                case $value === null:
210
-                case is_int($value):
211
-                case is_float($value):
212
-                    // typical booleans
213
-                case in_array($value, array(true, 'true', '1', 'on', 'yes', false, 'false', '0', 'off', 'no'), true):
214
-                    $attributes[ $key ] = $value;
215
-                    break;
216
-                case is_string($value):
217
-                    $attributes[ $key ] = sanitize_text_field($value);
218
-                    break;
219
-                case is_array($value):
220
-                    $attributes[ $key ] = $this->sanitizeAttributes($value);
221
-                    break;
222
-                default:
223
-                    // only remaining data types are Object and Resource
224
-                    // which are not allowed as shortcode attributes
225
-                    $attributes[ $key ] = null;
226
-                    break;
227
-            }
228
-        }
229
-        return $attributes;
230
-    }
231
-
232
-
233
-    /**
234
-     * Returns whether or not this shortcode has been initialized
235
-     *
236
-     * @return boolean
237
-     */
238
-    public function initialized()
239
-    {
240
-        return $this->initialized;
241
-    }
23
+	/**
24
+	 * transient prefix
25
+	 *
26
+	 * @type string
27
+	 */
28
+	const CACHE_TRANSIENT_PREFIX = 'ee_sc_';
29
+
30
+	/**
31
+	 * @var PostRelatedCacheManager $cache_manager
32
+	 */
33
+	private $cache_manager;
34
+
35
+	/**
36
+	 * true if ShortcodeInterface::initializeShortcode() has been called
37
+	 * if false, then that will get called before processing
38
+	 *
39
+	 * @var boolean $initialized
40
+	 */
41
+	private $initialized = false;
42
+
43
+
44
+	/**
45
+	 * EspressoShortcode constructor
46
+	 *
47
+	 * @param PostRelatedCacheManager $cache_manager
48
+	 */
49
+	public function __construct(PostRelatedCacheManager $cache_manager)
50
+	{
51
+		$this->cache_manager = $cache_manager;
52
+	}
53
+
54
+
55
+	/**
56
+	 * @return void
57
+	 */
58
+	public function shortcodeHasBeenInitialized()
59
+	{
60
+		$this->initialized = true;
61
+	}
62
+
63
+
64
+	/**
65
+	 * enqueues scripts then processes the shortcode
66
+	 *
67
+	 * @param array $attributes
68
+	 * @return string
69
+	 * @throws EE_Error
70
+	 * @throws ReflectionException
71
+	 */
72
+	final public function processShortcodeCallback($attributes = array())
73
+	{
74
+		if ($this instanceof EnqueueAssetsInterface) {
75
+			if (is_admin()) {
76
+				$this->enqueueAdminScripts();
77
+			} else {
78
+				$this->enqueueScripts();
79
+			}
80
+		}
81
+		return $this->shortcodeContent(
82
+			$this->sanitizeAttributes((array) $attributes)
83
+		);
84
+	}
85
+
86
+
87
+	/**
88
+	 * If shortcode caching is enabled for the shortcode,
89
+	 * and cached results exist, then that will be returned
90
+	 * else new content will be generated.
91
+	 * If caching is enabled, then the new content will be cached for later.
92
+	 *
93
+	 * @param array $attributes
94
+	 * @return mixed|string
95
+	 * @throws EE_Error
96
+	 * @throws ReflectionException
97
+	 */
98
+	private function shortcodeContent(array $attributes)
99
+	{
100
+		$shortcode = $this;
101
+		$post_ID = $this->currentPostID();
102
+		// something like "SC_EVENTS-123"
103
+		$cache_ID = $this->shortcodeCacheID($post_ID);
104
+		$this->cache_manager->clearPostRelatedCacheOnUpdate($post_ID, $cache_ID);
105
+		return $this->cache_manager->get(
106
+			$cache_ID,
107
+			// serialized attributes
108
+			wp_json_encode($attributes),
109
+			// Closure for generating content if cache is expired
110
+			function () use ($shortcode, $attributes) {
111
+				if ($shortcode->initialized() === false) {
112
+					$shortcode->initializeShortcode();
113
+				}
114
+				return $shortcode->processShortcode($attributes);
115
+			},
116
+			// filterable cache expiration set by each shortcode
117
+			apply_filters(
118
+				'FHEE__EventEspresso_core_services_shortcodes_EspressoShortcode__shortcodeContent__cache_expiration',
119
+				$this->cacheExpiration(),
120
+				$this->getTag(),
121
+				$this
122
+			)
123
+		);
124
+	}
125
+
126
+
127
+	/**
128
+	 * @return int
129
+	 * @throws EE_Error
130
+	 * @throws ReflectionException
131
+	 */
132
+	private function currentPostID()
133
+	{
134
+		// try to get EE_Event any way we can
135
+		$event = EEH_Event_View::get_event();
136
+		// then get some kind of ID
137
+		if ($event instanceof EE_Event) {
138
+			return $event->ID();
139
+		}
140
+		global $post;
141
+		if ($post instanceof WP_Post) {
142
+			return $post->ID;
143
+		}
144
+		return 0;
145
+	}
146
+
147
+
148
+	/**
149
+	 * @param int $post_ID
150
+	 * @return string
151
+	 */
152
+	private function shortcodeCacheID($post_ID)
153
+	{
154
+		$tag = str_replace('ESPRESSO_', '', $this->getTag());
155
+		return "SC_{$tag}-{$post_ID}";
156
+	}
157
+
158
+
159
+	/**
160
+	 * array for defining custom attribute sanitization callbacks,
161
+	 * where keys match keys in your attributes array,
162
+	 * and values represent the sanitization function you wish to be applied to that attribute.
163
+	 * So for example, if you had an integer attribute named "event_id"
164
+	 * that you wanted to be sanitized using absint(),
165
+	 * then you would return the following:
166
+	 *      array('event_id' => 'absint')
167
+	 * Entering 'skip_sanitization' for the callback value
168
+	 * means that no sanitization will be applied
169
+	 * on the assumption that the attribute
170
+	 * will be sanitized at some point... right?
171
+	 * You wouldn't pass around unsanitized attributes would you?
172
+	 * That would be very Tom Foolery of you!!!
173
+	 *
174
+	 * @return array
175
+	 */
176
+	protected function customAttributeSanitizationMap()
177
+	{
178
+		return array();
179
+	}
180
+
181
+
182
+	/**
183
+	 * Performs basic sanitization on shortcode attributes
184
+	 * Since incoming attributes from the shortcode usage in the WP editor will all be strings,
185
+	 * most attributes will by default be sanitized using the sanitize_text_field() function.
186
+	 * This can be overridden using the customAttributeSanitizationMap() method (see above),
187
+	 * all other attributes would be sanitized using the defaults in the switch statement below
188
+	 *
189
+	 * @param array $attributes
190
+	 * @return array
191
+	 */
192
+	private function sanitizeAttributes(array $attributes)
193
+	{
194
+		$custom_sanitization = $this->customAttributeSanitizationMap();
195
+		foreach ($attributes as $key => $value) {
196
+			// is a custom sanitization callback specified ?
197
+			if (isset($custom_sanitization[ $key ])) {
198
+				$callback = $custom_sanitization[ $key ];
199
+				if ($callback === 'skip_sanitization') {
200
+					$attributes[ $key ] = $value;
201
+					continue;
202
+				}
203
+				if (function_exists($callback)) {
204
+					$attributes[ $key ] = $callback($value);
205
+					continue;
206
+				}
207
+			}
208
+			switch (true) {
209
+				case $value === null:
210
+				case is_int($value):
211
+				case is_float($value):
212
+					// typical booleans
213
+				case in_array($value, array(true, 'true', '1', 'on', 'yes', false, 'false', '0', 'off', 'no'), true):
214
+					$attributes[ $key ] = $value;
215
+					break;
216
+				case is_string($value):
217
+					$attributes[ $key ] = sanitize_text_field($value);
218
+					break;
219
+				case is_array($value):
220
+					$attributes[ $key ] = $this->sanitizeAttributes($value);
221
+					break;
222
+				default:
223
+					// only remaining data types are Object and Resource
224
+					// which are not allowed as shortcode attributes
225
+					$attributes[ $key ] = null;
226
+					break;
227
+			}
228
+		}
229
+		return $attributes;
230
+	}
231
+
232
+
233
+	/**
234
+	 * Returns whether or not this shortcode has been initialized
235
+	 *
236
+	 * @return boolean
237
+	 */
238
+	public function initialized()
239
+	{
240
+		return $this->initialized;
241
+	}
242 242
 }
Please login to merge, or discard this patch.
core/services/request/ServerParams.php 2 patches
Indentation   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -7,183 +7,183 @@
 block discarded – undo
7 7
 class ServerParams
8 8
 {
9 9
 
10
-    /**
11
-     * IP address for request
12
-     *
13
-     * @var string
14
-     */
15
-    protected $ip_address;
16
-
17
-
18
-    /**
19
-     * @var ServerSanitizer
20
-     */
21
-    protected $sanitizer;
22
-
23
-    /**
24
-     * sanitized $_SERVER parameters
25
-     *
26
-     * @var array
27
-     */
28
-    protected $server;
29
-
30
-    /**
31
-     * @var string
32
-     */
33
-    protected $request_uri;
34
-
35
-    /**
36
-     * @var string
37
-     */
38
-    protected $user_agent;
39
-
40
-
41
-    /**
42
-     * ServerParams constructor.
43
-     *
44
-     * @param ServerSanitizer $sanitizer
45
-     * @param array           $server
46
-     */
47
-    public function __construct(ServerSanitizer $sanitizer, array $server = [])
48
-    {
49
-        $this->sanitizer  = $sanitizer;
50
-        $this->server     = $this->cleanServerParams($server);
51
-        $this->ip_address = $this->setVisitorIp();
52
-    }
53
-
54
-
55
-    /**
56
-     * @return array
57
-     */
58
-    private function cleanServerParams(array $server)
59
-    {
60
-        $cleaned = [];
61
-        $server  = ! empty($server) ? $server : $_SERVER;
62
-        foreach ($server as $key => $value) {
63
-            $cleaned[ $key ] = $this->sanitizer->clean($key, $value);
64
-            // \EEH_Debug_Tools::printr($cleaned[ $key ], $key, __FILE__, __LINE__);
65
-        }
66
-        return $cleaned;
67
-    }
68
-
69
-
70
-    /**
71
-     * @return array
72
-     */
73
-    public function getAllServerParams()
74
-    {
75
-        return $this->server;
76
-    }
77
-
78
-
79
-    /**
80
-     * @param string $key
81
-     * @return array|int|float|string
82
-     */
83
-    public function getServerParam($key)
84
-    {
85
-        return $this->serverParamIsSet($key) ? $this->server[ $key ] : null;
86
-    }
87
-
88
-
89
-    /**
90
-     * @param string                 $key
91
-     * @param array|int|float|string $value
92
-     * @return void
93
-     */
94
-    public function setServerParam($key, $value)
95
-    {
96
-        $this->server[ $key ] = $this->sanitizer->clean($key, $value);
97
-    }
98
-
99
-
100
-    /**
101
-     * @return bool
102
-     */
103
-    public function serverParamIsSet($key)
104
-    {
105
-        return isset($this->server[ $key ]);
106
-    }
107
-
108
-
109
-    /**
110
-     * @return string
111
-     */
112
-    public function ipAddress()
113
-    {
114
-        return $this->ip_address;
115
-    }
116
-
117
-
118
-    /**
119
-     * attempt to get IP address of current visitor from server
120
-     * plz see: http://stackoverflow.com/a/2031935/1475279
121
-     *
122
-     * @access public
123
-     * @return string
124
-     */
125
-    private function setVisitorIp()
126
-    {
127
-        $visitor_ip  = '0.0.0.0';
128
-        $server_keys = [
129
-            'HTTP_CLIENT_IP',
130
-            'HTTP_FORWARDED',
131
-            'HTTP_FORWARDED_FOR',
132
-            'HTTP_X_CLUSTER_CLIENT_IP',
133
-            'HTTP_X_FORWARDED',
134
-            'HTTP_X_FORWARDED_FOR',
135
-            'REMOTE_ADDR',
136
-        ];
137
-        foreach ($server_keys as $key) {
138
-            if (isset($this->server[ $key ])) {
139
-                foreach (array_map('trim', explode(',', $this->server[ $key ])) as $ip) {
140
-                    if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
141
-                        $visitor_ip = $ip;
142
-                    }
143
-                }
144
-            }
145
-        }
146
-        return $visitor_ip;
147
-    }
148
-
149
-
150
-    /**
151
-     * Gets the request's literal URI. Related to `requestUriAfterSiteHomeUri`, see its description for a comparison.
152
-     *
153
-     * @param boolean $relativeToWpRoot If home_url() is "http://mysite.com/wp/", and a request comes to
154
-     *                                  "http://mysite.com/wp/wp-json", setting $relativeToWpRoot=true will return
155
-     *                                  "/wp-json", whereas $relativeToWpRoot=false will return "/wp/wp-json/".
156
-     * @return string
157
-     */
158
-    public function requestUri($relativeToWpRoot = false)
159
-    {
160
-        if ($relativeToWpRoot) {
161
-            $home_path = untrailingslashit(parse_url(home_url(), PHP_URL_PATH));
162
-            return str_replace($home_path, '', $this->server['REQUEST_URI']);
163
-        }
164
-        return $this->server['REQUEST_URI'];
165
-    }
166
-
167
-
168
-    /**
169
-     * @return string
170
-     */
171
-    public function userAgent()
172
-    {
173
-        if (empty($this->user_agent)) {
174
-            $this->setUserAgent();
175
-        }
176
-        return $this->user_agent;
177
-    }
178
-
179
-
180
-    /**
181
-     * @param string $user_agent
182
-     */
183
-    public function setUserAgent($user_agent = '')
184
-    {
185
-        $this->user_agent = $user_agent === '' || ! is_string($user_agent)
186
-            ? $this->getServerParam('HTTP_USER_AGENT')
187
-            : esc_attr($user_agent);
188
-    }
10
+	/**
11
+	 * IP address for request
12
+	 *
13
+	 * @var string
14
+	 */
15
+	protected $ip_address;
16
+
17
+
18
+	/**
19
+	 * @var ServerSanitizer
20
+	 */
21
+	protected $sanitizer;
22
+
23
+	/**
24
+	 * sanitized $_SERVER parameters
25
+	 *
26
+	 * @var array
27
+	 */
28
+	protected $server;
29
+
30
+	/**
31
+	 * @var string
32
+	 */
33
+	protected $request_uri;
34
+
35
+	/**
36
+	 * @var string
37
+	 */
38
+	protected $user_agent;
39
+
40
+
41
+	/**
42
+	 * ServerParams constructor.
43
+	 *
44
+	 * @param ServerSanitizer $sanitizer
45
+	 * @param array           $server
46
+	 */
47
+	public function __construct(ServerSanitizer $sanitizer, array $server = [])
48
+	{
49
+		$this->sanitizer  = $sanitizer;
50
+		$this->server     = $this->cleanServerParams($server);
51
+		$this->ip_address = $this->setVisitorIp();
52
+	}
53
+
54
+
55
+	/**
56
+	 * @return array
57
+	 */
58
+	private function cleanServerParams(array $server)
59
+	{
60
+		$cleaned = [];
61
+		$server  = ! empty($server) ? $server : $_SERVER;
62
+		foreach ($server as $key => $value) {
63
+			$cleaned[ $key ] = $this->sanitizer->clean($key, $value);
64
+			// \EEH_Debug_Tools::printr($cleaned[ $key ], $key, __FILE__, __LINE__);
65
+		}
66
+		return $cleaned;
67
+	}
68
+
69
+
70
+	/**
71
+	 * @return array
72
+	 */
73
+	public function getAllServerParams()
74
+	{
75
+		return $this->server;
76
+	}
77
+
78
+
79
+	/**
80
+	 * @param string $key
81
+	 * @return array|int|float|string
82
+	 */
83
+	public function getServerParam($key)
84
+	{
85
+		return $this->serverParamIsSet($key) ? $this->server[ $key ] : null;
86
+	}
87
+
88
+
89
+	/**
90
+	 * @param string                 $key
91
+	 * @param array|int|float|string $value
92
+	 * @return void
93
+	 */
94
+	public function setServerParam($key, $value)
95
+	{
96
+		$this->server[ $key ] = $this->sanitizer->clean($key, $value);
97
+	}
98
+
99
+
100
+	/**
101
+	 * @return bool
102
+	 */
103
+	public function serverParamIsSet($key)
104
+	{
105
+		return isset($this->server[ $key ]);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @return string
111
+	 */
112
+	public function ipAddress()
113
+	{
114
+		return $this->ip_address;
115
+	}
116
+
117
+
118
+	/**
119
+	 * attempt to get IP address of current visitor from server
120
+	 * plz see: http://stackoverflow.com/a/2031935/1475279
121
+	 *
122
+	 * @access public
123
+	 * @return string
124
+	 */
125
+	private function setVisitorIp()
126
+	{
127
+		$visitor_ip  = '0.0.0.0';
128
+		$server_keys = [
129
+			'HTTP_CLIENT_IP',
130
+			'HTTP_FORWARDED',
131
+			'HTTP_FORWARDED_FOR',
132
+			'HTTP_X_CLUSTER_CLIENT_IP',
133
+			'HTTP_X_FORWARDED',
134
+			'HTTP_X_FORWARDED_FOR',
135
+			'REMOTE_ADDR',
136
+		];
137
+		foreach ($server_keys as $key) {
138
+			if (isset($this->server[ $key ])) {
139
+				foreach (array_map('trim', explode(',', $this->server[ $key ])) as $ip) {
140
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
141
+						$visitor_ip = $ip;
142
+					}
143
+				}
144
+			}
145
+		}
146
+		return $visitor_ip;
147
+	}
148
+
149
+
150
+	/**
151
+	 * Gets the request's literal URI. Related to `requestUriAfterSiteHomeUri`, see its description for a comparison.
152
+	 *
153
+	 * @param boolean $relativeToWpRoot If home_url() is "http://mysite.com/wp/", and a request comes to
154
+	 *                                  "http://mysite.com/wp/wp-json", setting $relativeToWpRoot=true will return
155
+	 *                                  "/wp-json", whereas $relativeToWpRoot=false will return "/wp/wp-json/".
156
+	 * @return string
157
+	 */
158
+	public function requestUri($relativeToWpRoot = false)
159
+	{
160
+		if ($relativeToWpRoot) {
161
+			$home_path = untrailingslashit(parse_url(home_url(), PHP_URL_PATH));
162
+			return str_replace($home_path, '', $this->server['REQUEST_URI']);
163
+		}
164
+		return $this->server['REQUEST_URI'];
165
+	}
166
+
167
+
168
+	/**
169
+	 * @return string
170
+	 */
171
+	public function userAgent()
172
+	{
173
+		if (empty($this->user_agent)) {
174
+			$this->setUserAgent();
175
+		}
176
+		return $this->user_agent;
177
+	}
178
+
179
+
180
+	/**
181
+	 * @param string $user_agent
182
+	 */
183
+	public function setUserAgent($user_agent = '')
184
+	{
185
+		$this->user_agent = $user_agent === '' || ! is_string($user_agent)
186
+			? $this->getServerParam('HTTP_USER_AGENT')
187
+			: esc_attr($user_agent);
188
+	}
189 189
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
         $cleaned = [];
61 61
         $server  = ! empty($server) ? $server : $_SERVER;
62 62
         foreach ($server as $key => $value) {
63
-            $cleaned[ $key ] = $this->sanitizer->clean($key, $value);
63
+            $cleaned[$key] = $this->sanitizer->clean($key, $value);
64 64
             // \EEH_Debug_Tools::printr($cleaned[ $key ], $key, __FILE__, __LINE__);
65 65
         }
66 66
         return $cleaned;
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
      */
83 83
     public function getServerParam($key)
84 84
     {
85
-        return $this->serverParamIsSet($key) ? $this->server[ $key ] : null;
85
+        return $this->serverParamIsSet($key) ? $this->server[$key] : null;
86 86
     }
87 87
 
88 88
 
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
      */
94 94
     public function setServerParam($key, $value)
95 95
     {
96
-        $this->server[ $key ] = $this->sanitizer->clean($key, $value);
96
+        $this->server[$key] = $this->sanitizer->clean($key, $value);
97 97
     }
98 98
 
99 99
 
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
      */
103 103
     public function serverParamIsSet($key)
104 104
     {
105
-        return isset($this->server[ $key ]);
105
+        return isset($this->server[$key]);
106 106
     }
107 107
 
108 108
 
@@ -135,8 +135,8 @@  discard block
 block discarded – undo
135 135
             'REMOTE_ADDR',
136 136
         ];
137 137
         foreach ($server_keys as $key) {
138
-            if (isset($this->server[ $key ])) {
139
-                foreach (array_map('trim', explode(',', $this->server[ $key ])) as $ip) {
138
+            if (isset($this->server[$key])) {
139
+                foreach (array_map('trim', explode(',', $this->server[$key])) as $ip) {
140 140
                     if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
141 141
                         $visitor_ip = $ip;
142 142
                     }
Please login to merge, or discard this patch.
core/services/request/files/FilesDataHandler.php 2 patches
Indentation   +251 added lines, -251 removed lines patch added patch discarded remove patch
@@ -40,279 +40,279 @@
 block discarded – undo
40 40
  */
41 41
 class FilesDataHandler
42 42
 {
43
-    /**
44
-     * @var Request
45
-     */
46
-    protected $request;
43
+	/**
44
+	 * @var Request
45
+	 */
46
+	protected $request;
47 47
 
48
-    /**
49
-     * @var CollectionInterface | FileSubmissionInterface[]
50
-     */
51
-    protected $file_objects;
48
+	/**
49
+	 * @var CollectionInterface | FileSubmissionInterface[]
50
+	 */
51
+	protected $file_objects;
52 52
 
53
-    /**
54
-     * @var bool
55
-     */
56
-    protected $initialized = false;
53
+	/**
54
+	 * @var bool
55
+	 */
56
+	protected $initialized = false;
57 57
 
58 58
 
59
-    /**
60
-     * FilesDataHandler constructor.
61
-     *
62
-     * @param Request $request
63
-     */
64
-    public function __construct(Request $request)
65
-    {
66
-        $this->request = $request;
67
-    }
59
+	/**
60
+	 * FilesDataHandler constructor.
61
+	 *
62
+	 * @param Request $request
63
+	 */
64
+	public function __construct(Request $request)
65
+	{
66
+		$this->request = $request;
67
+	}
68 68
 
69 69
 
70
-    /**
71
-     * @return CollectionInterface | FileSubmissionInterface[]
72
-     * @throws UnexpectedValueException
73
-     * @throws InvalidArgumentException
74
-     * @since 4.9.80.p
75
-     */
76
-    protected function getFileObjects()
77
-    {
78
-        $this->initialize();
79
-        return $this->file_objects;
80
-    }
70
+	/**
71
+	 * @return CollectionInterface | FileSubmissionInterface[]
72
+	 * @throws UnexpectedValueException
73
+	 * @throws InvalidArgumentException
74
+	 * @since 4.9.80.p
75
+	 */
76
+	protected function getFileObjects()
77
+	{
78
+		$this->initialize();
79
+		return $this->file_objects;
80
+	}
81 81
 
82 82
 
83
-    /**
84
-     * Sets up the file objects from the request's $_FILES data.
85
-     *
86
-     * @throws UnexpectedValueException
87
-     * @throws InvalidArgumentException
88
-     * @throws InvalidInterfaceException
89
-     * @since 4.9.80.p
90
-     */
91
-    protected function initialize()
92
-    {
93
-        if ($this->initialized) {
94
-            return;
95
-        }
96
-        $this->file_objects = new Collection(
97
-        // collection interface
98
-            'EventEspresso\core\services\request\files\FileSubmissionInterface',
99
-            // collection name
100
-            'submitted_files'
101
-        );
102
-        $files_raw_data     = $this->request->filesParams();
103
-        if (empty($files_raw_data)) {
104
-            return;
105
-        }
106
-        if ($this->isStrangeFilesArray($files_raw_data)) {
107
-            $data = $this->fixFilesDataArray($files_raw_data);
108
-        } else {
109
-            $data = $files_raw_data;
110
-        }
111
-        $this->createFileObjects($data);
112
-        $this->initialized = true;
113
-    }
83
+	/**
84
+	 * Sets up the file objects from the request's $_FILES data.
85
+	 *
86
+	 * @throws UnexpectedValueException
87
+	 * @throws InvalidArgumentException
88
+	 * @throws InvalidInterfaceException
89
+	 * @since 4.9.80.p
90
+	 */
91
+	protected function initialize()
92
+	{
93
+		if ($this->initialized) {
94
+			return;
95
+		}
96
+		$this->file_objects = new Collection(
97
+		// collection interface
98
+			'EventEspresso\core\services\request\files\FileSubmissionInterface',
99
+			// collection name
100
+			'submitted_files'
101
+		);
102
+		$files_raw_data     = $this->request->filesParams();
103
+		if (empty($files_raw_data)) {
104
+			return;
105
+		}
106
+		if ($this->isStrangeFilesArray($files_raw_data)) {
107
+			$data = $this->fixFilesDataArray($files_raw_data);
108
+		} else {
109
+			$data = $files_raw_data;
110
+		}
111
+		$this->createFileObjects($data);
112
+		$this->initialized = true;
113
+	}
114 114
 
115 115
 
116
-    /**
117
-     * Detects if $_FILES is a weird multi-dimensional array that needs fixing or not.
118
-     *
119
-     * @param $files_data
120
-     * @return bool
121
-     * @throws UnexpectedValueException
122
-     * @since 4.9.80.p
123
-     */
124
-    protected function isStrangeFilesArray($files_data)
125
-    {
126
-        if (! is_array($files_data)) {
127
-            throw new UnexpectedValueException(
128
-                sprintf(
129
-                    esc_html__(
130
-                        'Unexpected PHP $_FILES data format. "%1$s" was expected to be an array.',
131
-                        'event_espresso'
132
-                    ),
133
-                    (string) $files_data
134
-                )
135
-            );
136
-        }
137
-        $first_value = reset($files_data);
138
-        if (! is_array($first_value)) {
139
-            throw new UnexpectedValueException(
140
-                sprintf(
141
-                    esc_html__(
142
-                        'Unexpected PHP $_FILES data format. "%1$s" was expected to be an array.',
143
-                        'event_espresso'
144
-                    ),
145
-                    (string) $first_value
146
-                )
147
-            );
148
-        }
149
-        $first_sub_array_item = reset($first_value);
150
-        if (is_array($first_sub_array_item)) {
151
-            // not just a 2d array
152
-            return true;
153
-        }
154
-        // yep, just 2d array
155
-        return false;
156
-    }
116
+	/**
117
+	 * Detects if $_FILES is a weird multi-dimensional array that needs fixing or not.
118
+	 *
119
+	 * @param $files_data
120
+	 * @return bool
121
+	 * @throws UnexpectedValueException
122
+	 * @since 4.9.80.p
123
+	 */
124
+	protected function isStrangeFilesArray($files_data)
125
+	{
126
+		if (! is_array($files_data)) {
127
+			throw new UnexpectedValueException(
128
+				sprintf(
129
+					esc_html__(
130
+						'Unexpected PHP $_FILES data format. "%1$s" was expected to be an array.',
131
+						'event_espresso'
132
+					),
133
+					(string) $files_data
134
+				)
135
+			);
136
+		}
137
+		$first_value = reset($files_data);
138
+		if (! is_array($first_value)) {
139
+			throw new UnexpectedValueException(
140
+				sprintf(
141
+					esc_html__(
142
+						'Unexpected PHP $_FILES data format. "%1$s" was expected to be an array.',
143
+						'event_espresso'
144
+					),
145
+					(string) $first_value
146
+				)
147
+			);
148
+		}
149
+		$first_sub_array_item = reset($first_value);
150
+		if (is_array($first_sub_array_item)) {
151
+			// not just a 2d array
152
+			return true;
153
+		}
154
+		// yep, just 2d array
155
+		return false;
156
+	}
157 157
 
158 158
 
159
-    /**
160
-     * Takes into account that $_FILES does a weird thing when you have hierarchical form names (eg `<input type="file"
161
-     * name="my[hierarchical][form]">`): it leaves the top-level form part alone, but replaces the SECOND part with
162
-     * "name", "size", "tmp_name", etc. So that file's data is located at "my[name][hierarchical][form]",
163
-     * "my[size][hierarchical][form]", "my[tmp_name][hierarchical][form]", etc. It's really weird.
164
-     *
165
-     * @param $files_data
166
-     * @return array
167
-     * @since 4.9.80.p
168
-     */
169
-    protected function fixFilesDataArray($files_data)
170
-    {
171
-        $sane_files_array = [];
172
-        foreach ($files_data as $top_level_name => $top_level_children) {
173
-            $sub_array                           = [];
174
-            $sane_files_array[ $top_level_name ] = [];
175
-            foreach ($top_level_children as $file_data_part => $second_level_children) {
176
-                foreach ($second_level_children as $next_level_name => $sub_values) {
177
-                    $sub_array[ $next_level_name ] = $this->organizeFilesData($sub_values, $file_data_part);
178
-                }
179
-                $sane_files_array[ $top_level_name ] = array_replace_recursive(
180
-                    $sub_array,
181
-                    $sane_files_array[ $top_level_name ]
182
-                );
183
-            }
184
-        }
185
-        return $sane_files_array;
186
-    }
159
+	/**
160
+	 * Takes into account that $_FILES does a weird thing when you have hierarchical form names (eg `<input type="file"
161
+	 * name="my[hierarchical][form]">`): it leaves the top-level form part alone, but replaces the SECOND part with
162
+	 * "name", "size", "tmp_name", etc. So that file's data is located at "my[name][hierarchical][form]",
163
+	 * "my[size][hierarchical][form]", "my[tmp_name][hierarchical][form]", etc. It's really weird.
164
+	 *
165
+	 * @param $files_data
166
+	 * @return array
167
+	 * @since 4.9.80.p
168
+	 */
169
+	protected function fixFilesDataArray($files_data)
170
+	{
171
+		$sane_files_array = [];
172
+		foreach ($files_data as $top_level_name => $top_level_children) {
173
+			$sub_array                           = [];
174
+			$sane_files_array[ $top_level_name ] = [];
175
+			foreach ($top_level_children as $file_data_part => $second_level_children) {
176
+				foreach ($second_level_children as $next_level_name => $sub_values) {
177
+					$sub_array[ $next_level_name ] = $this->organizeFilesData($sub_values, $file_data_part);
178
+				}
179
+				$sane_files_array[ $top_level_name ] = array_replace_recursive(
180
+					$sub_array,
181
+					$sane_files_array[ $top_level_name ]
182
+				);
183
+			}
184
+		}
185
+		return $sane_files_array;
186
+	}
187 187
 
188 188
 
189
-    /**
190
-     * Recursively explores the array until it finds a leaf node, and tacks `$type` as a final index in front of it.
191
-     *
192
-     * @param $data array|string
193
-     * @param $type 'name', 'tmp_name', 'size', or 'error'
194
-     * @return array
195
-     * @since 4.9.80.p
196
-     */
197
-    protected function organizeFilesData($data, $type)
198
-    {
199
-        if (! is_array($data)) {
200
-            return [
201
-                $type => $data,
202
-            ];
203
-        }
204
-        $organized_data = [];
205
-        foreach ($data as $input_name_part => $sub_inputs_or_value) {
206
-            if (is_array($sub_inputs_or_value)) {
207
-                $organized_data[ $input_name_part ] = $this->organizeFilesData($sub_inputs_or_value, $type);
208
-            } else {
209
-                $organized_data[ $input_name_part ][ $type ] = $sub_inputs_or_value;
210
-            }
211
-        }
212
-        return $organized_data;
213
-    }
189
+	/**
190
+	 * Recursively explores the array until it finds a leaf node, and tacks `$type` as a final index in front of it.
191
+	 *
192
+	 * @param $data array|string
193
+	 * @param $type 'name', 'tmp_name', 'size', or 'error'
194
+	 * @return array
195
+	 * @since 4.9.80.p
196
+	 */
197
+	protected function organizeFilesData($data, $type)
198
+	{
199
+		if (! is_array($data)) {
200
+			return [
201
+				$type => $data,
202
+			];
203
+		}
204
+		$organized_data = [];
205
+		foreach ($data as $input_name_part => $sub_inputs_or_value) {
206
+			if (is_array($sub_inputs_or_value)) {
207
+				$organized_data[ $input_name_part ] = $this->organizeFilesData($sub_inputs_or_value, $type);
208
+			} else {
209
+				$organized_data[ $input_name_part ][ $type ] = $sub_inputs_or_value;
210
+			}
211
+		}
212
+		return $organized_data;
213
+	}
214 214
 
215 215
 
216
-    /**
217
-     * Takes the organized $_FILES array (where all file info is located at the same spot as you'd expect an input
218
-     * to be in post data, with all the file's data located side-by-side in an array) and creates a
219
-     * multi-dimensional array of FileSubmissionInterface objects. Stores it in `$this->file_objects`.
220
-     *
221
-     * @param array $organized_files   $_FILES but organized like $_POST
222
-     * @param array $name_parts_so_far for multidimensional HTML form names,
223
-     * @throws UnexpectedValueException
224
-     * @throws InvalidArgumentException
225
-     * @since 4.9.80.p
226
-     */
227
-    protected function createFileObjects($organized_files, $name_parts_so_far = [])
228
-    {
229
-        if (! is_array($organized_files)) {
230
-            throw new UnexpectedValueException(
231
-                sprintf(
232
-                    esc_html__(
233
-                        'Unexpected PHP $organized_files data format. "%1$s" was expected to be an array.',
234
-                        'event_espresso'
235
-                    ),
236
-                    (string) $organized_files
237
-                )
238
-            );
239
-        }
240
-        foreach ($organized_files as $key => $value) {
241
-            $this_input_name_parts = $name_parts_so_far;
242
-            array_push(
243
-                $this_input_name_parts,
244
-                $key
245
-            );
246
-            if (isset($value['name'], $value['tmp_name'], $value['size'])) {
247
-                $html_name = $this->inputNameFromParts($this_input_name_parts);
248
-                $this->file_objects->add(
249
-                    new FileSubmission(
250
-                        $value['name'],
251
-                        $value['tmp_name'],
252
-                        $value['size'],
253
-                        $value['error']
254
-                    ),
255
-                    $html_name
256
-                );
257
-            } else {
258
-                $this->createFileObjects($value, $this_input_name_parts);
259
-            }
260
-        }
261
-    }
216
+	/**
217
+	 * Takes the organized $_FILES array (where all file info is located at the same spot as you'd expect an input
218
+	 * to be in post data, with all the file's data located side-by-side in an array) and creates a
219
+	 * multi-dimensional array of FileSubmissionInterface objects. Stores it in `$this->file_objects`.
220
+	 *
221
+	 * @param array $organized_files   $_FILES but organized like $_POST
222
+	 * @param array $name_parts_so_far for multidimensional HTML form names,
223
+	 * @throws UnexpectedValueException
224
+	 * @throws InvalidArgumentException
225
+	 * @since 4.9.80.p
226
+	 */
227
+	protected function createFileObjects($organized_files, $name_parts_so_far = [])
228
+	{
229
+		if (! is_array($organized_files)) {
230
+			throw new UnexpectedValueException(
231
+				sprintf(
232
+					esc_html__(
233
+						'Unexpected PHP $organized_files data format. "%1$s" was expected to be an array.',
234
+						'event_espresso'
235
+					),
236
+					(string) $organized_files
237
+				)
238
+			);
239
+		}
240
+		foreach ($organized_files as $key => $value) {
241
+			$this_input_name_parts = $name_parts_so_far;
242
+			array_push(
243
+				$this_input_name_parts,
244
+				$key
245
+			);
246
+			if (isset($value['name'], $value['tmp_name'], $value['size'])) {
247
+				$html_name = $this->inputNameFromParts($this_input_name_parts);
248
+				$this->file_objects->add(
249
+					new FileSubmission(
250
+						$value['name'],
251
+						$value['tmp_name'],
252
+						$value['size'],
253
+						$value['error']
254
+					),
255
+					$html_name
256
+				);
257
+			} else {
258
+				$this->createFileObjects($value, $this_input_name_parts);
259
+			}
260
+		}
261
+	}
262 262
 
263 263
 
264
-    /**
265
-     * Takes the input name parts, like `['my', 'great', 'file', 'input1']`
266
-     * and returns the HTML name for it, "my[great][file][input1]"
267
-     *
268
-     * @throws UnexpectedValueException
269
-     * @since 4.9.80.p
270
-     */
271
-    protected function inputNameFromParts($parts)
272
-    {
273
-        if (! is_array($parts)) {
274
-            throw new UnexpectedValueException(esc_html__('Name parts should be an array.', 'event_espresso'));
275
-        }
276
-        $generated_string = '';
277
-        foreach ($parts as $part) {
278
-            $part = (string) $part;
279
-            // wrap all but the first part in []
280
-            $generated_string .= $generated_string === '' ? $part : '[' . $part . ']';
281
-        }
282
-        return $generated_string;
283
-    }
264
+	/**
265
+	 * Takes the input name parts, like `['my', 'great', 'file', 'input1']`
266
+	 * and returns the HTML name for it, "my[great][file][input1]"
267
+	 *
268
+	 * @throws UnexpectedValueException
269
+	 * @since 4.9.80.p
270
+	 */
271
+	protected function inputNameFromParts($parts)
272
+	{
273
+		if (! is_array($parts)) {
274
+			throw new UnexpectedValueException(esc_html__('Name parts should be an array.', 'event_espresso'));
275
+		}
276
+		$generated_string = '';
277
+		foreach ($parts as $part) {
278
+			$part = (string) $part;
279
+			// wrap all but the first part in []
280
+			$generated_string .= $generated_string === '' ? $part : '[' . $part . ']';
281
+		}
282
+		return $generated_string;
283
+	}
284 284
 
285 285
 
286
-    /**
287
-     * Gets the input by the indicated $name_parts.
288
-     * Eg if you're looking for an input named "my[great][file][input1]", $name_parts
289
-     * should be `['my', 'great', 'file', 'input1']`.
290
-     * Alternatively, you could use `FileDataHandler::getFileObject('my[great][file][input1]');`
291
-     *
292
-     * @param $name_parts
293
-     * @return FileSubmissionInterface
294
-     * @throws UnexpectedValueException
295
-     * @since 4.9.80.p
296
-     */
297
-    public function getFileObjectFromNameParts($name_parts)
298
-    {
299
-        return $this->getFileObjects()->get($this->inputNameFromParts($name_parts));
300
-    }
286
+	/**
287
+	 * Gets the input by the indicated $name_parts.
288
+	 * Eg if you're looking for an input named "my[great][file][input1]", $name_parts
289
+	 * should be `['my', 'great', 'file', 'input1']`.
290
+	 * Alternatively, you could use `FileDataHandler::getFileObject('my[great][file][input1]');`
291
+	 *
292
+	 * @param $name_parts
293
+	 * @return FileSubmissionInterface
294
+	 * @throws UnexpectedValueException
295
+	 * @since 4.9.80.p
296
+	 */
297
+	public function getFileObjectFromNameParts($name_parts)
298
+	{
299
+		return $this->getFileObjects()->get($this->inputNameFromParts($name_parts));
300
+	}
301 301
 
302 302
 
303
-    /**
304
-     * Gets the FileSubmissionInterface corresponding to the HTML name provided.
305
-     *
306
-     * @param $html_name
307
-     * @return mixed
308
-     * @throws InvalidArgumentException
309
-     * @throws UnexpectedValueException
310
-     * @since 4.9.80.p
311
-     */
312
-    public function getFileObject($html_name)
313
-    {
314
-        return $this->getFileObjects()->get($html_name);
315
-    }
303
+	/**
304
+	 * Gets the FileSubmissionInterface corresponding to the HTML name provided.
305
+	 *
306
+	 * @param $html_name
307
+	 * @return mixed
308
+	 * @throws InvalidArgumentException
309
+	 * @throws UnexpectedValueException
310
+	 * @since 4.9.80.p
311
+	 */
312
+	public function getFileObject($html_name)
313
+	{
314
+		return $this->getFileObjects()->get($html_name);
315
+	}
316 316
 }
317 317
 // End of file FilesDataHandler.php
318 318
 // Location: EventEspresso\core\services\request\files/FilesDataHandler.php
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
             // collection name
100 100
             'submitted_files'
101 101
         );
102
-        $files_raw_data     = $this->request->filesParams();
102
+        $files_raw_data = $this->request->filesParams();
103 103
         if (empty($files_raw_data)) {
104 104
             return;
105 105
         }
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
      */
124 124
     protected function isStrangeFilesArray($files_data)
125 125
     {
126
-        if (! is_array($files_data)) {
126
+        if ( ! is_array($files_data)) {
127 127
             throw new UnexpectedValueException(
128 128
                 sprintf(
129 129
                     esc_html__(
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
             );
136 136
         }
137 137
         $first_value = reset($files_data);
138
-        if (! is_array($first_value)) {
138
+        if ( ! is_array($first_value)) {
139 139
             throw new UnexpectedValueException(
140 140
                 sprintf(
141 141
                     esc_html__(
@@ -171,14 +171,14 @@  discard block
 block discarded – undo
171 171
         $sane_files_array = [];
172 172
         foreach ($files_data as $top_level_name => $top_level_children) {
173 173
             $sub_array                           = [];
174
-            $sane_files_array[ $top_level_name ] = [];
174
+            $sane_files_array[$top_level_name] = [];
175 175
             foreach ($top_level_children as $file_data_part => $second_level_children) {
176 176
                 foreach ($second_level_children as $next_level_name => $sub_values) {
177
-                    $sub_array[ $next_level_name ] = $this->organizeFilesData($sub_values, $file_data_part);
177
+                    $sub_array[$next_level_name] = $this->organizeFilesData($sub_values, $file_data_part);
178 178
                 }
179
-                $sane_files_array[ $top_level_name ] = array_replace_recursive(
179
+                $sane_files_array[$top_level_name] = array_replace_recursive(
180 180
                     $sub_array,
181
-                    $sane_files_array[ $top_level_name ]
181
+                    $sane_files_array[$top_level_name]
182 182
                 );
183 183
             }
184 184
         }
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
      */
197 197
     protected function organizeFilesData($data, $type)
198 198
     {
199
-        if (! is_array($data)) {
199
+        if ( ! is_array($data)) {
200 200
             return [
201 201
                 $type => $data,
202 202
             ];
@@ -204,9 +204,9 @@  discard block
 block discarded – undo
204 204
         $organized_data = [];
205 205
         foreach ($data as $input_name_part => $sub_inputs_or_value) {
206 206
             if (is_array($sub_inputs_or_value)) {
207
-                $organized_data[ $input_name_part ] = $this->organizeFilesData($sub_inputs_or_value, $type);
207
+                $organized_data[$input_name_part] = $this->organizeFilesData($sub_inputs_or_value, $type);
208 208
             } else {
209
-                $organized_data[ $input_name_part ][ $type ] = $sub_inputs_or_value;
209
+                $organized_data[$input_name_part][$type] = $sub_inputs_or_value;
210 210
             }
211 211
         }
212 212
         return $organized_data;
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
      */
227 227
     protected function createFileObjects($organized_files, $name_parts_so_far = [])
228 228
     {
229
-        if (! is_array($organized_files)) {
229
+        if ( ! is_array($organized_files)) {
230 230
             throw new UnexpectedValueException(
231 231
                 sprintf(
232 232
                     esc_html__(
@@ -270,14 +270,14 @@  discard block
 block discarded – undo
270 270
      */
271 271
     protected function inputNameFromParts($parts)
272 272
     {
273
-        if (! is_array($parts)) {
273
+        if ( ! is_array($parts)) {
274 274
             throw new UnexpectedValueException(esc_html__('Name parts should be an array.', 'event_espresso'));
275 275
         }
276 276
         $generated_string = '';
277 277
         foreach ($parts as $part) {
278 278
             $part = (string) $part;
279 279
             // wrap all but the first part in []
280
-            $generated_string .= $generated_string === '' ? $part : '[' . $part . ']';
280
+            $generated_string .= $generated_string === '' ? $part : '['.$part.']';
281 281
         }
282 282
         return $generated_string;
283 283
     }
Please login to merge, or discard this patch.
core/services/request/sanitizers/ServerSanitizer.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -11,59 +11,59 @@
 block discarded – undo
11 11
  */
12 12
 class ServerSanitizer
13 13
 {
14
-    /**
15
-     * @param string $value
16
-     * @return mixed|string
17
-     */
18
-    public function clean($key, $value)
19
-    {
20
-        switch ($key) {
21
-            case 'AUTH_TYPE':
22
-                $valid_types = [
23
-                    'Basic',
24
-                    'Bearer',
25
-                    'Digest',
26
-                    'HOBA',
27
-                    'Mutual',
28
-                    'Negotiate',
29
-                    'OAuth',
30
-                    'SCRAM-SHA-1',
31
-                    'SCRAM-SHA-256',
32
-                    'vapid',
33
-                ];
34
-                return in_array($value, $valid_types, true) ? $value : 'Basic';
35
-            case 'argc':
36
-            case 'HTTP_DNT':
37
-            case 'HTTP_UPGRADE_INSECURE_REQUESTS':
38
-            case 'SERVER_PORT':
39
-            case 'REMOTE_PORT':
40
-            case 'REQUEST_TIME':
41
-                return (int) filter_var($value, FILTER_SANITIZE_NUMBER_INT);
42
-            case 'REQUEST_TIME_FLOAT':
43
-                return (float) filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
44
-            case 'REQUEST_METHOD':
45
-                $valid_types = [
46
-                    'CONNECT',
47
-                    'DELETE',
48
-                    'GET',
49
-                    'HEAD',
50
-                    'OPTIONS',
51
-                    'PATCH',
52
-                    'POST',
53
-                    'PUT',
54
-                    'TRACE',
55
-                ];
56
-                return in_array($value, $valid_types, true) ? $value : 'GET';
57
-            case 'HTTP_HOST':
58
-            case 'QUERY_STRING':
59
-            case 'REQUEST_URI':
60
-            case 'SCRIPT_NAME':
61
-            case 'SERVER_NAME':
62
-                return filter_var($value, FILTER_SANITIZE_URL);
63
-            case 'SERVER_ADMIN':
64
-                return filter_var($value, FILTER_SANITIZE_EMAIL);
65
-            default:
66
-                return filter_var($value, FILTER_SANITIZE_STRING);
67
-        }
68
-    }
14
+	/**
15
+	 * @param string $value
16
+	 * @return mixed|string
17
+	 */
18
+	public function clean($key, $value)
19
+	{
20
+		switch ($key) {
21
+			case 'AUTH_TYPE':
22
+				$valid_types = [
23
+					'Basic',
24
+					'Bearer',
25
+					'Digest',
26
+					'HOBA',
27
+					'Mutual',
28
+					'Negotiate',
29
+					'OAuth',
30
+					'SCRAM-SHA-1',
31
+					'SCRAM-SHA-256',
32
+					'vapid',
33
+				];
34
+				return in_array($value, $valid_types, true) ? $value : 'Basic';
35
+			case 'argc':
36
+			case 'HTTP_DNT':
37
+			case 'HTTP_UPGRADE_INSECURE_REQUESTS':
38
+			case 'SERVER_PORT':
39
+			case 'REMOTE_PORT':
40
+			case 'REQUEST_TIME':
41
+				return (int) filter_var($value, FILTER_SANITIZE_NUMBER_INT);
42
+			case 'REQUEST_TIME_FLOAT':
43
+				return (float) filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
44
+			case 'REQUEST_METHOD':
45
+				$valid_types = [
46
+					'CONNECT',
47
+					'DELETE',
48
+					'GET',
49
+					'HEAD',
50
+					'OPTIONS',
51
+					'PATCH',
52
+					'POST',
53
+					'PUT',
54
+					'TRACE',
55
+				];
56
+				return in_array($value, $valid_types, true) ? $value : 'GET';
57
+			case 'HTTP_HOST':
58
+			case 'QUERY_STRING':
59
+			case 'REQUEST_URI':
60
+			case 'SCRIPT_NAME':
61
+			case 'SERVER_NAME':
62
+				return filter_var($value, FILTER_SANITIZE_URL);
63
+			case 'SERVER_ADMIN':
64
+				return filter_var($value, FILTER_SANITIZE_EMAIL);
65
+			default:
66
+				return filter_var($value, FILTER_SANITIZE_STRING);
67
+		}
68
+	}
69 69
 }
Please login to merge, or discard this patch.
core/services/request/sanitizers/RequestSanitizer.php 2 patches
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -4,46 +4,46 @@
 block discarded – undo
4 4
 
5 5
 class RequestSanitizer
6 6
 {
7
-    /**
8
-     * Will sanitize the supplied request parameter based on the specified data type
9
-     *
10
-     * @param mixed  $param     the supplied request parameter
11
-     * @param string $type      the specified data type (default: "string")
12
-     *                          valid values: "bool", "float", "int", "key", "url", "string", or "arrayOf|*"
13
-     *                          where * is any of the other valid values ex: "arrayOf|int", "arrayOf|string"
14
-     * @param string $delimiter if $param is a CSV like value (ex: 1,2,3,4,5...) then this is the value separator
15
-     *                          (default: ",")
16
-     * @return array|bool|float|int|string
17
-     * @since $VID:$
18
-     */
19
-    public function clean($param, $type = 'string', $delimiter = ',')
20
-    {
21
-        switch ($type) {
22
-            case 'bool':
23
-                return filter_var($param, FILTER_VALIDATE_BOOLEAN);
24
-            case 'float':
25
-                return (float) $param;
26
-            case 'int':
27
-                return (int) $param;
28
-            case 'key':
29
-                return sanitize_key($param);
30
-            case 'url':
31
-                return esc_url_raw($param);
32
-            case 'string':
33
-                return sanitize_text_field($param);
34
-            default:
35
-                if (strpos($type, 'arrayOf|') === 0) {
36
-                    $values        = [];
37
-                    $array_of_type = substr($type, 8);
38
-                    $list          = is_string($param) ? explode($delimiter, $param) : (array) $param;
39
-                    foreach ($list as $key => $item) {
40
-                        $values[ $key ] = is_array($item)
41
-                            ? $this->clean($item, $type, $delimiter)
42
-                            : $this->clean($item, $array_of_type, $delimiter);
43
-                    }
44
-                    return $values;
45
-                }
46
-                return sanitize_text_field($param);
47
-        }
48
-    }
7
+	/**
8
+	 * Will sanitize the supplied request parameter based on the specified data type
9
+	 *
10
+	 * @param mixed  $param     the supplied request parameter
11
+	 * @param string $type      the specified data type (default: "string")
12
+	 *                          valid values: "bool", "float", "int", "key", "url", "string", or "arrayOf|*"
13
+	 *                          where * is any of the other valid values ex: "arrayOf|int", "arrayOf|string"
14
+	 * @param string $delimiter if $param is a CSV like value (ex: 1,2,3,4,5...) then this is the value separator
15
+	 *                          (default: ",")
16
+	 * @return array|bool|float|int|string
17
+	 * @since $VID:$
18
+	 */
19
+	public function clean($param, $type = 'string', $delimiter = ',')
20
+	{
21
+		switch ($type) {
22
+			case 'bool':
23
+				return filter_var($param, FILTER_VALIDATE_BOOLEAN);
24
+			case 'float':
25
+				return (float) $param;
26
+			case 'int':
27
+				return (int) $param;
28
+			case 'key':
29
+				return sanitize_key($param);
30
+			case 'url':
31
+				return esc_url_raw($param);
32
+			case 'string':
33
+				return sanitize_text_field($param);
34
+			default:
35
+				if (strpos($type, 'arrayOf|') === 0) {
36
+					$values        = [];
37
+					$array_of_type = substr($type, 8);
38
+					$list          = is_string($param) ? explode($delimiter, $param) : (array) $param;
39
+					foreach ($list as $key => $item) {
40
+						$values[ $key ] = is_array($item)
41
+							? $this->clean($item, $type, $delimiter)
42
+							: $this->clean($item, $array_of_type, $delimiter);
43
+					}
44
+					return $values;
45
+				}
46
+				return sanitize_text_field($param);
47
+		}
48
+	}
49 49
 }
50 50
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@
 block discarded – undo
37 37
                     $array_of_type = substr($type, 8);
38 38
                     $list          = is_string($param) ? explode($delimiter, $param) : (array) $param;
39 39
                     foreach ($list as $key => $item) {
40
-                        $values[ $key ] = is_array($item)
40
+                        $values[$key] = is_array($item)
41 41
                             ? $this->clean($item, $type, $delimiter)
42 42
                             : $this->clean($item, $array_of_type, $delimiter);
43 43
                     }
Please login to merge, or discard this patch.
core/services/request/RequestParams.php 2 patches
Indentation   +306 added lines, -306 removed lines patch added patch discarded remove patch
@@ -14,310 +14,310 @@
 block discarded – undo
14 14
 class RequestParams
15 15
 {
16 16
 
17
-    /**
18
-     * $_GET parameters
19
-     *
20
-     * @var array
21
-     */
22
-    protected $get;
23
-
24
-    /**
25
-     * $_POST parameters
26
-     *
27
-     * @var array
28
-     */
29
-    protected $post;
30
-
31
-    /**
32
-     * $_REQUEST parameters
33
-     *
34
-     * @var array
35
-     */
36
-    protected $request;
37
-
38
-    /**
39
-     * @var RequestSanitizer
40
-     */
41
-    protected $sanitizer;
42
-
43
-
44
-    /**
45
-     * RequestParams constructor.
46
-     *
47
-     * @param RequestSanitizer $sanitizer
48
-     * @param array            $get
49
-     * @param array            $post
50
-     */
51
-    public function __construct(RequestSanitizer $sanitizer, array $get = [], array $post = [])
52
-    {
53
-        $this->sanitizer = $sanitizer;
54
-        $this->get       = ! empty($get) ? $get : (array) filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
55
-        $this->post      = ! empty($post) ? $post : (array) filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
56
-        $this->request   = array_merge($this->get, $this->post);
57
-    }
58
-
59
-
60
-    /**
61
-     * @return array
62
-     */
63
-    public function getParams()
64
-    {
65
-        return $this->get;
66
-    }
67
-
68
-
69
-    /**
70
-     * @return array
71
-     */
72
-    public function postParams()
73
-    {
74
-        return $this->post;
75
-    }
76
-
77
-
78
-    /**
79
-     * returns contents of $_REQUEST
80
-     *
81
-     * @return array
82
-     */
83
-    public function requestParams()
84
-    {
85
-        return $this->request;
86
-    }
87
-
88
-
89
-    /**
90
-     * @param string     $key
91
-     * @param mixed|null $value
92
-     * @param bool       $override_ee
93
-     * @return    void
94
-     */
95
-    public function setRequestParam($key, $value, $override_ee = false)
96
-    {
97
-        // don't allow "ee" to be overwritten unless explicitly instructed to do so
98
-        if ($override_ee || $key !== 'ee' || empty($this->request['ee'])) {
99
-            $this->request[ $key ] = $value;
100
-        }
101
-    }
102
-
103
-
104
-    /**
105
-     * returns   the value for a request param if the given key exists
106
-     *
107
-     * @param string     $key
108
-     * @param mixed|null $default
109
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
110
-     * @param string     $delimiter for CSV type strings that should be returned as an array
111
-     * @return array|bool|float|int|string
112
-     */
113
-    public function getRequestParam($key, $default = null, $type = 'string', $delimiter = ',')
114
-    {
115
-        return $this->sanitizer->clean(
116
-            $this->parameterDrillDown($key, $default, 'get'),
117
-            $type,
118
-            $delimiter
119
-        );
120
-    }
121
-
122
-
123
-    /**
124
-     * check if param exists
125
-     *
126
-     * @param string $key
127
-     * @return bool
128
-     */
129
-    public function requestParamIsSet($key)
130
-    {
131
-        return (bool) $this->parameterDrillDown($key);
132
-    }
133
-
134
-
135
-    /**
136
-     * check if a request parameter exists whose key that matches the supplied wildcard pattern
137
-     * and return the value for the first match found
138
-     * wildcards can be either of the following:
139
-     *      ? to represent a single character of any type
140
-     *      * to represent one or more characters of any type
141
-     *
142
-     * @param string     $pattern
143
-     * @param mixed|null $default
144
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
145
-     * @param string     $delimiter for CSV type strings that should be returned as an array
146
-     * @return array|bool|float|int|string
147
-     */
148
-    public function getMatch($pattern, $default = null, $type = 'string', $delimiter = ',')
149
-    {
150
-        return $this->sanitizer->clean(
151
-            $this->parameterDrillDown($pattern, $default, 'match'),
152
-            $type,
153
-            $delimiter
154
-        );
155
-    }
156
-
157
-
158
-    /**
159
-     * check if a request parameter exists whose key matches the supplied wildcard pattern
160
-     * wildcards can be either of the following:
161
-     *      ? to represent a single character of any type
162
-     *      * to represent one or more characters of any type
163
-     * returns true if a match is found or false if not
164
-     *
165
-     * @param string $pattern
166
-     * @return bool
167
-     */
168
-    public function matches($pattern)
169
-    {
170
-        return (bool) $this->parameterDrillDown($pattern, false, 'match', 'bool');
171
-    }
172
-
173
-
174
-    /**
175
-     * @see https://stackoverflow.com/questions/6163055/php-string-matching-with-wildcard
176
-     * @param string $pattern               A string including wildcards to be converted to a regex pattern
177
-     *                                      and used to search through the current request's parameter keys
178
-     * @param array  $request_params        The array of request parameters to search through
179
-     * @param mixed  $default               [optional] The value to be returned if no match is found.
180
-     *                                      Default is null
181
-     * @param string $return                [optional] Controls what kind of value is returned.
182
-     *                                      Options are:
183
-     *                                      'bool' will return true or false if match is found or not
184
-     *                                      'key' will return the first key found that matches the supplied pattern
185
-     *                                      'value' will return the value for the first request parameter
186
-     *                                      whose key matches the supplied pattern
187
-     *                                      Default is 'value'
188
-     * @return boolean|string
189
-     */
190
-    private function match($pattern, array $request_params, $default = null, $return = 'value')
191
-    {
192
-        $return = in_array($return, ['bool', 'key', 'value'], true)
193
-            ? $return
194
-            : 'is_set';
195
-        // replace wildcard chars with regex chars
196
-        $pattern = str_replace(
197
-            ['\*', '\?'],
198
-            ['.*', '.'],
199
-            preg_quote($pattern, '/')
200
-        );
201
-        foreach ($request_params as $key => $request_param) {
202
-            if (preg_match('/^' . $pattern . '$/is', $key)) {
203
-                // return value for request param
204
-                if ($return === 'value') {
205
-                    return $request_param;
206
-                }
207
-                // or actual key or true just to indicate it was found
208
-                return $return === 'key' ? $key : true;
209
-            }
210
-        }
211
-        // match not found so return default value or false
212
-        return $return === 'value' ? $default : false;
213
-    }
214
-
215
-
216
-    /**
217
-     * the supplied key can be a simple string to represent a "top-level" request parameter
218
-     * or represent a key for a request parameter that is nested deeper within the request parameter array,
219
-     * by using square brackets to surround keys for deeper array elements.
220
-     * For example :
221
-     * if the supplied $key was: "first[second][third]"
222
-     * then this will attempt to drill down into the request parameter array to find a value.
223
-     * Given the following request parameters:
224
-     *  array(
225
-     *      'first' => array(
226
-     *          'second' => array(
227
-     *              'third' => 'has a value'
228
-     *          )
229
-     *      )
230
-     *  )
231
-     * would return true if default parameters were set
232
-     *
233
-     * @param string $callback
234
-     * @param        $key
235
-     * @param null   $default
236
-     * @param string $return
237
-     * @param array  $request_params
238
-     * @return bool|mixed|null
239
-     */
240
-    private function parameterDrillDown(
241
-        $key,
242
-        $default = null,
243
-        $callback = 'is_set',
244
-        $return = 'value',
245
-        array $request_params = []
246
-    ) {
247
-        $callback       = in_array($callback, ['is_set', 'get', 'match'], true)
248
-            ? $callback
249
-            : 'is_set';
250
-        $request_params = ! empty($request_params)
251
-            ? $request_params
252
-            : $this->request;
253
-        // does incoming key represent an array like 'first[second][third]'  ?
254
-        if (strpos($key, '[') !== false) {
255
-            // turn it into an actual array
256
-            $key  = str_replace(']', '', $key);
257
-            $keys = explode('[', $key);
258
-            $key  = array_shift($keys);
259
-            if ($callback === 'match') {
260
-                $real_key = $this->match($key, $request_params, $default, 'key');
261
-                $key      = $real_key ?: $key;
262
-            }
263
-            // check if top level key exists
264
-            if (isset($request_params[ $key ])) {
265
-                // build a new key to pass along like: 'second[third]'
266
-                // or just 'second' depending on depth of keys
267
-                $key_string = array_shift($keys);
268
-                if (! empty($keys)) {
269
-                    $key_string .= '[' . implode('][', $keys) . ']';
270
-                }
271
-                return $this->parameterDrillDown(
272
-                    $key_string,
273
-                    $default,
274
-                    $callback,
275
-                    $return,
276
-                    $request_params[ $key ]
277
-                );
278
-            }
279
-        }
280
-        if ($callback === 'is_set') {
281
-            return isset($request_params[ $key ]);
282
-        }
283
-        if ($callback === 'match') {
284
-            return $this->match($key, $request_params, $default, $return);
285
-        }
286
-        return isset($request_params[ $key ])
287
-            ? $request_params[ $key ]
288
-            : $default;
289
-    }
290
-
291
-
292
-    /**
293
-     * remove param
294
-     *
295
-     * @param      $key
296
-     * @param bool $unset_from_global_too
297
-     */
298
-    public function unSetRequestParam($key, $unset_from_global_too = false)
299
-    {
300
-        // because unset may not actually remove var
301
-        $this->get[ $key ]     = null;
302
-        $this->post[ $key ]    = null;
303
-        $this->request[ $key ] = null;
304
-        unset($this->get[ $key ], $this->post[ $key ], $this->request[ $key ]);
305
-        if ($unset_from_global_too) {
306
-            unset($_GET[ $key ], $_POST[ $key ], $_REQUEST[ $key ]);
307
-        }
308
-    }
309
-
310
-
311
-    /**
312
-     * remove params
313
-     *
314
-     * @param array $keys
315
-     * @param bool  $unset_from_global_too
316
-     */
317
-    public function unSetRequestParams(array $keys, $unset_from_global_too = false)
318
-    {
319
-        foreach ($keys as $key) {
320
-            $this->unSetRequestParam($key, $unset_from_global_too);
321
-        }
322
-    }
17
+	/**
18
+	 * $_GET parameters
19
+	 *
20
+	 * @var array
21
+	 */
22
+	protected $get;
23
+
24
+	/**
25
+	 * $_POST parameters
26
+	 *
27
+	 * @var array
28
+	 */
29
+	protected $post;
30
+
31
+	/**
32
+	 * $_REQUEST parameters
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $request;
37
+
38
+	/**
39
+	 * @var RequestSanitizer
40
+	 */
41
+	protected $sanitizer;
42
+
43
+
44
+	/**
45
+	 * RequestParams constructor.
46
+	 *
47
+	 * @param RequestSanitizer $sanitizer
48
+	 * @param array            $get
49
+	 * @param array            $post
50
+	 */
51
+	public function __construct(RequestSanitizer $sanitizer, array $get = [], array $post = [])
52
+	{
53
+		$this->sanitizer = $sanitizer;
54
+		$this->get       = ! empty($get) ? $get : (array) filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
55
+		$this->post      = ! empty($post) ? $post : (array) filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
56
+		$this->request   = array_merge($this->get, $this->post);
57
+	}
58
+
59
+
60
+	/**
61
+	 * @return array
62
+	 */
63
+	public function getParams()
64
+	{
65
+		return $this->get;
66
+	}
67
+
68
+
69
+	/**
70
+	 * @return array
71
+	 */
72
+	public function postParams()
73
+	{
74
+		return $this->post;
75
+	}
76
+
77
+
78
+	/**
79
+	 * returns contents of $_REQUEST
80
+	 *
81
+	 * @return array
82
+	 */
83
+	public function requestParams()
84
+	{
85
+		return $this->request;
86
+	}
87
+
88
+
89
+	/**
90
+	 * @param string     $key
91
+	 * @param mixed|null $value
92
+	 * @param bool       $override_ee
93
+	 * @return    void
94
+	 */
95
+	public function setRequestParam($key, $value, $override_ee = false)
96
+	{
97
+		// don't allow "ee" to be overwritten unless explicitly instructed to do so
98
+		if ($override_ee || $key !== 'ee' || empty($this->request['ee'])) {
99
+			$this->request[ $key ] = $value;
100
+		}
101
+	}
102
+
103
+
104
+	/**
105
+	 * returns   the value for a request param if the given key exists
106
+	 *
107
+	 * @param string     $key
108
+	 * @param mixed|null $default
109
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
110
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
111
+	 * @return array|bool|float|int|string
112
+	 */
113
+	public function getRequestParam($key, $default = null, $type = 'string', $delimiter = ',')
114
+	{
115
+		return $this->sanitizer->clean(
116
+			$this->parameterDrillDown($key, $default, 'get'),
117
+			$type,
118
+			$delimiter
119
+		);
120
+	}
121
+
122
+
123
+	/**
124
+	 * check if param exists
125
+	 *
126
+	 * @param string $key
127
+	 * @return bool
128
+	 */
129
+	public function requestParamIsSet($key)
130
+	{
131
+		return (bool) $this->parameterDrillDown($key);
132
+	}
133
+
134
+
135
+	/**
136
+	 * check if a request parameter exists whose key that matches the supplied wildcard pattern
137
+	 * and return the value for the first match found
138
+	 * wildcards can be either of the following:
139
+	 *      ? to represent a single character of any type
140
+	 *      * to represent one or more characters of any type
141
+	 *
142
+	 * @param string     $pattern
143
+	 * @param mixed|null $default
144
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
145
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
146
+	 * @return array|bool|float|int|string
147
+	 */
148
+	public function getMatch($pattern, $default = null, $type = 'string', $delimiter = ',')
149
+	{
150
+		return $this->sanitizer->clean(
151
+			$this->parameterDrillDown($pattern, $default, 'match'),
152
+			$type,
153
+			$delimiter
154
+		);
155
+	}
156
+
157
+
158
+	/**
159
+	 * check if a request parameter exists whose key matches the supplied wildcard pattern
160
+	 * wildcards can be either of the following:
161
+	 *      ? to represent a single character of any type
162
+	 *      * to represent one or more characters of any type
163
+	 * returns true if a match is found or false if not
164
+	 *
165
+	 * @param string $pattern
166
+	 * @return bool
167
+	 */
168
+	public function matches($pattern)
169
+	{
170
+		return (bool) $this->parameterDrillDown($pattern, false, 'match', 'bool');
171
+	}
172
+
173
+
174
+	/**
175
+	 * @see https://stackoverflow.com/questions/6163055/php-string-matching-with-wildcard
176
+	 * @param string $pattern               A string including wildcards to be converted to a regex pattern
177
+	 *                                      and used to search through the current request's parameter keys
178
+	 * @param array  $request_params        The array of request parameters to search through
179
+	 * @param mixed  $default               [optional] The value to be returned if no match is found.
180
+	 *                                      Default is null
181
+	 * @param string $return                [optional] Controls what kind of value is returned.
182
+	 *                                      Options are:
183
+	 *                                      'bool' will return true or false if match is found or not
184
+	 *                                      'key' will return the first key found that matches the supplied pattern
185
+	 *                                      'value' will return the value for the first request parameter
186
+	 *                                      whose key matches the supplied pattern
187
+	 *                                      Default is 'value'
188
+	 * @return boolean|string
189
+	 */
190
+	private function match($pattern, array $request_params, $default = null, $return = 'value')
191
+	{
192
+		$return = in_array($return, ['bool', 'key', 'value'], true)
193
+			? $return
194
+			: 'is_set';
195
+		// replace wildcard chars with regex chars
196
+		$pattern = str_replace(
197
+			['\*', '\?'],
198
+			['.*', '.'],
199
+			preg_quote($pattern, '/')
200
+		);
201
+		foreach ($request_params as $key => $request_param) {
202
+			if (preg_match('/^' . $pattern . '$/is', $key)) {
203
+				// return value for request param
204
+				if ($return === 'value') {
205
+					return $request_param;
206
+				}
207
+				// or actual key or true just to indicate it was found
208
+				return $return === 'key' ? $key : true;
209
+			}
210
+		}
211
+		// match not found so return default value or false
212
+		return $return === 'value' ? $default : false;
213
+	}
214
+
215
+
216
+	/**
217
+	 * the supplied key can be a simple string to represent a "top-level" request parameter
218
+	 * or represent a key for a request parameter that is nested deeper within the request parameter array,
219
+	 * by using square brackets to surround keys for deeper array elements.
220
+	 * For example :
221
+	 * if the supplied $key was: "first[second][third]"
222
+	 * then this will attempt to drill down into the request parameter array to find a value.
223
+	 * Given the following request parameters:
224
+	 *  array(
225
+	 *      'first' => array(
226
+	 *          'second' => array(
227
+	 *              'third' => 'has a value'
228
+	 *          )
229
+	 *      )
230
+	 *  )
231
+	 * would return true if default parameters were set
232
+	 *
233
+	 * @param string $callback
234
+	 * @param        $key
235
+	 * @param null   $default
236
+	 * @param string $return
237
+	 * @param array  $request_params
238
+	 * @return bool|mixed|null
239
+	 */
240
+	private function parameterDrillDown(
241
+		$key,
242
+		$default = null,
243
+		$callback = 'is_set',
244
+		$return = 'value',
245
+		array $request_params = []
246
+	) {
247
+		$callback       = in_array($callback, ['is_set', 'get', 'match'], true)
248
+			? $callback
249
+			: 'is_set';
250
+		$request_params = ! empty($request_params)
251
+			? $request_params
252
+			: $this->request;
253
+		// does incoming key represent an array like 'first[second][third]'  ?
254
+		if (strpos($key, '[') !== false) {
255
+			// turn it into an actual array
256
+			$key  = str_replace(']', '', $key);
257
+			$keys = explode('[', $key);
258
+			$key  = array_shift($keys);
259
+			if ($callback === 'match') {
260
+				$real_key = $this->match($key, $request_params, $default, 'key');
261
+				$key      = $real_key ?: $key;
262
+			}
263
+			// check if top level key exists
264
+			if (isset($request_params[ $key ])) {
265
+				// build a new key to pass along like: 'second[third]'
266
+				// or just 'second' depending on depth of keys
267
+				$key_string = array_shift($keys);
268
+				if (! empty($keys)) {
269
+					$key_string .= '[' . implode('][', $keys) . ']';
270
+				}
271
+				return $this->parameterDrillDown(
272
+					$key_string,
273
+					$default,
274
+					$callback,
275
+					$return,
276
+					$request_params[ $key ]
277
+				);
278
+			}
279
+		}
280
+		if ($callback === 'is_set') {
281
+			return isset($request_params[ $key ]);
282
+		}
283
+		if ($callback === 'match') {
284
+			return $this->match($key, $request_params, $default, $return);
285
+		}
286
+		return isset($request_params[ $key ])
287
+			? $request_params[ $key ]
288
+			: $default;
289
+	}
290
+
291
+
292
+	/**
293
+	 * remove param
294
+	 *
295
+	 * @param      $key
296
+	 * @param bool $unset_from_global_too
297
+	 */
298
+	public function unSetRequestParam($key, $unset_from_global_too = false)
299
+	{
300
+		// because unset may not actually remove var
301
+		$this->get[ $key ]     = null;
302
+		$this->post[ $key ]    = null;
303
+		$this->request[ $key ] = null;
304
+		unset($this->get[ $key ], $this->post[ $key ], $this->request[ $key ]);
305
+		if ($unset_from_global_too) {
306
+			unset($_GET[ $key ], $_POST[ $key ], $_REQUEST[ $key ]);
307
+		}
308
+	}
309
+
310
+
311
+	/**
312
+	 * remove params
313
+	 *
314
+	 * @param array $keys
315
+	 * @param bool  $unset_from_global_too
316
+	 */
317
+	public function unSetRequestParams(array $keys, $unset_from_global_too = false)
318
+	{
319
+		foreach ($keys as $key) {
320
+			$this->unSetRequestParam($key, $unset_from_global_too);
321
+		}
322
+	}
323 323
 }
324 324
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
     {
97 97
         // don't allow "ee" to be overwritten unless explicitly instructed to do so
98 98
         if ($override_ee || $key !== 'ee' || empty($this->request['ee'])) {
99
-            $this->request[ $key ] = $value;
99
+            $this->request[$key] = $value;
100 100
         }
101 101
     }
102 102
 
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
             preg_quote($pattern, '/')
200 200
         );
201 201
         foreach ($request_params as $key => $request_param) {
202
-            if (preg_match('/^' . $pattern . '$/is', $key)) {
202
+            if (preg_match('/^'.$pattern.'$/is', $key)) {
203 203
                 // return value for request param
204 204
                 if ($return === 'value') {
205 205
                     return $request_param;
@@ -261,30 +261,30 @@  discard block
 block discarded – undo
261 261
                 $key      = $real_key ?: $key;
262 262
             }
263 263
             // check if top level key exists
264
-            if (isset($request_params[ $key ])) {
264
+            if (isset($request_params[$key])) {
265 265
                 // build a new key to pass along like: 'second[third]'
266 266
                 // or just 'second' depending on depth of keys
267 267
                 $key_string = array_shift($keys);
268
-                if (! empty($keys)) {
269
-                    $key_string .= '[' . implode('][', $keys) . ']';
268
+                if ( ! empty($keys)) {
269
+                    $key_string .= '['.implode('][', $keys).']';
270 270
                 }
271 271
                 return $this->parameterDrillDown(
272 272
                     $key_string,
273 273
                     $default,
274 274
                     $callback,
275 275
                     $return,
276
-                    $request_params[ $key ]
276
+                    $request_params[$key]
277 277
                 );
278 278
             }
279 279
         }
280 280
         if ($callback === 'is_set') {
281
-            return isset($request_params[ $key ]);
281
+            return isset($request_params[$key]);
282 282
         }
283 283
         if ($callback === 'match') {
284 284
             return $this->match($key, $request_params, $default, $return);
285 285
         }
286
-        return isset($request_params[ $key ])
287
-            ? $request_params[ $key ]
286
+        return isset($request_params[$key])
287
+            ? $request_params[$key]
288 288
             : $default;
289 289
     }
290 290
 
@@ -298,12 +298,12 @@  discard block
 block discarded – undo
298 298
     public function unSetRequestParam($key, $unset_from_global_too = false)
299 299
     {
300 300
         // because unset may not actually remove var
301
-        $this->get[ $key ]     = null;
302
-        $this->post[ $key ]    = null;
303
-        $this->request[ $key ] = null;
304
-        unset($this->get[ $key ], $this->post[ $key ], $this->request[ $key ]);
301
+        $this->get[$key]     = null;
302
+        $this->post[$key]    = null;
303
+        $this->request[$key] = null;
304
+        unset($this->get[$key], $this->post[$key], $this->request[$key]);
305 305
         if ($unset_from_global_too) {
306
-            unset($_GET[ $key ], $_POST[ $key ], $_REQUEST[ $key ]);
306
+            unset($_GET[$key], $_POST[$key], $_REQUEST[$key]);
307 307
         }
308 308
     }
309 309
 
Please login to merge, or discard this patch.
core/services/request/LegacyRequestInterface.php 1 patch
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -12,125 +12,125 @@
 block discarded – undo
12 12
 interface LegacyRequestInterface
13 13
 {
14 14
 
15
-    /**
16
-     * @return array
17
-     */
18
-    public function get_params();
15
+	/**
16
+	 * @return array
17
+	 */
18
+	public function get_params();
19 19
 
20 20
 
21
-    /**
22
-     * @return array
23
-     */
24
-    public function post_params();
21
+	/**
22
+	 * @return array
23
+	 */
24
+	public function post_params();
25 25
 
26 26
 
27
-    /**
28
-     * @return array
29
-     */
30
-    public function cookie_params();
27
+	/**
28
+	 * @return array
29
+	 */
30
+	public function cookie_params();
31 31
 
32 32
 
33
-    /**
34
-     * @return array
35
-     */
36
-    public function server_params();
33
+	/**
34
+	 * @return array
35
+	 */
36
+	public function server_params();
37 37
 
38 38
 
39
-    /**
40
-     * returns sanitized contents of $_REQUEST
41
-     *
42
-     * @return array
43
-     */
44
-    public function params();
39
+	/**
40
+	 * returns sanitized contents of $_REQUEST
41
+	 *
42
+	 * @return array
43
+	 */
44
+	public function params();
45 45
 
46 46
 
47
-    /**
48
-     * @param      $key
49
-     * @param      $value
50
-     * @param bool $override_ee
51
-     * @return    void
52
-     */
53
-    public function set($key, $value, $override_ee = false);
47
+	/**
48
+	 * @param      $key
49
+	 * @param      $value
50
+	 * @param bool $override_ee
51
+	 * @return    void
52
+	 */
53
+	public function set($key, $value, $override_ee = false);
54 54
 
55 55
 
56
-    /**
57
-     * returns   the value for a request param if the given key exists
58
-     *
59
-     * @param       $key
60
-     * @param null  $default
61
-     * @return mixed
62
-     */
63
-    public function get($key, $default = null);
56
+	/**
57
+	 * returns   the value for a request param if the given key exists
58
+	 *
59
+	 * @param       $key
60
+	 * @param null  $default
61
+	 * @return mixed
62
+	 */
63
+	public function get($key, $default = null);
64 64
 
65 65
 
66
-    /**
67
-     * check if param exists
68
-     *
69
-     * @param       $key
70
-     * @return bool
71
-     */
72
-    public function is_set($key);
66
+	/**
67
+	 * check if param exists
68
+	 *
69
+	 * @param       $key
70
+	 * @return bool
71
+	 */
72
+	public function is_set($key);
73 73
 
74 74
 
75
-    /**
76
-     * remove param
77
-     *
78
-     * @param      $key
79
-     * @param bool $unset_from_global_too
80
-     */
81
-    public function un_set($key, $unset_from_global_too = false);
75
+	/**
76
+	 * remove param
77
+	 *
78
+	 * @param      $key
79
+	 * @param bool $unset_from_global_too
80
+	 */
81
+	public function un_set($key, $unset_from_global_too = false);
82 82
 
83 83
 
84
-    /**
85
-     * @return string
86
-     */
87
-    public function ip_address();
84
+	/**
85
+	 * @return string
86
+	 */
87
+	public function ip_address();
88 88
 
89 89
 
90
-    /**
91
-     * @return bool
92
-     */
93
-    public function isAdmin();
90
+	/**
91
+	 * @return bool
92
+	 */
93
+	public function isAdmin();
94 94
 
95 95
 
96
-    /**
97
-     * @return mixed
98
-     */
99
-    public function isAjax();
96
+	/**
97
+	 * @return mixed
98
+	 */
99
+	public function isAjax();
100 100
 
101 101
 
102
-    /**
103
-     * @return mixed
104
-     */
105
-    public function isFrontAjax();
102
+	/**
103
+	 * @return mixed
104
+	 */
105
+	public function isFrontAjax();
106 106
 
107 107
 
108
-    /**
109
-     * @return mixed|string
110
-     */
111
-    public function requestUri();
108
+	/**
109
+	 * @return mixed|string
110
+	 */
111
+	public function requestUri();
112 112
 
113 113
 
114
-    /**
115
-     * @return string
116
-     */
117
-    public function userAgent();
114
+	/**
115
+	 * @return string
116
+	 */
117
+	public function userAgent();
118 118
 
119 119
 
120
-    /**
121
-     * @param string $user_agent
122
-     */
123
-    public function setUserAgent($user_agent = '');
120
+	/**
121
+	 * @param string $user_agent
122
+	 */
123
+	public function setUserAgent($user_agent = '');
124 124
 
125 125
 
126
-    /**
127
-     * @return bool
128
-     */
129
-    public function isBot();
126
+	/**
127
+	 * @return bool
128
+	 */
129
+	public function isBot();
130 130
 
131 131
 
132
-    /**
133
-     * @param bool $is_bot
134
-     */
135
-    public function setIsBot($is_bot);
132
+	/**
133
+	 * @param bool $is_bot
134
+	 */
135
+	public function setIsBot($is_bot);
136 136
 }
Please login to merge, or discard this patch.
core/services/request/Request.php 1 patch
Indentation   +475 added lines, -475 removed lines patch added patch discarded remove patch
@@ -17,479 +17,479 @@
 block discarded – undo
17 17
 class Request implements InterminableInterface, RequestInterface, ReservedInstanceInterface
18 18
 {
19 19
 
20
-    /**
21
-     * $_COOKIE parameters
22
-     *
23
-     * @var array
24
-     */
25
-    protected $cookies;
26
-
27
-    /**
28
-     * $_FILES parameters
29
-     *
30
-     * @var array
31
-     */
32
-    protected $files;
33
-
34
-    /**
35
-     * true if current user appears to be some kind of bot
36
-     *
37
-     * @var bool
38
-     */
39
-    protected $is_bot;
40
-
41
-    /**
42
-     * @var RequestParams
43
-     */
44
-    protected $request_params;
45
-
46
-    /**
47
-     * @var RequestTypeContextCheckerInterface
48
-     */
49
-    protected $request_type;
50
-
51
-    /**
52
-     * @var ServerParams
53
-     */
54
-    protected $server_params;
55
-
56
-
57
-    public function __construct(
58
-        RequestParams $request_params,
59
-        ServerParams $server_params,
60
-        array $cookies = [],
61
-        array $files = []
62
-    ) {
63
-        $this->cookies = ! empty($cookies)
64
-            ? $cookies
65
-            : filter_input_array(INPUT_COOKIE, FILTER_SANITIZE_STRING);
66
-        $this->files          = ! empty($files) ? $files : $_FILES;
67
-        $this->request_params = $request_params;
68
-        $this->server_params  = $server_params;
69
-    }
70
-
71
-
72
-    /**
73
-     * @param RequestTypeContextCheckerInterface $type
74
-     */
75
-    public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type)
76
-    {
77
-        $this->request_type = $type;
78
-    }
79
-
80
-
81
-    /**
82
-     * @return array
83
-     */
84
-    public function getParams()
85
-    {
86
-        return $this->request_params->getParams();
87
-    }
88
-
89
-
90
-    /**
91
-     * @return array
92
-     */
93
-    public function postParams()
94
-    {
95
-        return $this->request_params->postParams();
96
-    }
97
-
98
-
99
-    /**
100
-     * @return array
101
-     */
102
-    public function cookieParams()
103
-    {
104
-        return $this->cookies;
105
-    }
106
-
107
-
108
-    /**
109
-     * @return array
110
-     */
111
-    public function serverParams()
112
-    {
113
-        return $this->server_params->getAllServerParams();
114
-    }
115
-
116
-
117
-    /**
118
-     * @param string $key
119
-     * @return array|int|float|string
120
-     */
121
-    public function getServerParam($key)
122
-    {
123
-        return $this->server_params->getServerParam($key);
124
-    }
125
-
126
-
127
-    /**
128
-     * @param string                 $key
129
-     * @param array|int|float|string $value
130
-     * @return void
131
-     */
132
-    public function setServerParam($key, $value)
133
-    {
134
-        $this->server_params->setServerParam($key, $value);
135
-    }
136
-
137
-
138
-    /**
139
-     * @param string $key
140
-     * @return bool
141
-     */
142
-    public function serverParamIsSet($key)
143
-    {
144
-        return $this->server_params->serverParamIsSet($key);
145
-    }
146
-
147
-
148
-    /**
149
-     * @return array
150
-     */
151
-    public function filesParams()
152
-    {
153
-        return $this->files;
154
-    }
155
-
156
-
157
-    /**
158
-     * returns sanitized contents of $_REQUEST
159
-     *
160
-     * @return array
161
-     */
162
-    public function requestParams()
163
-    {
164
-        return $this->request_params->requestParams();
165
-    }
166
-
167
-
168
-    /**
169
-     * @param string     $key
170
-     * @param mixed|null $value
171
-     * @param bool       $override_ee
172
-     * @return void
173
-     */
174
-    public function setRequestParam($key, $value, $override_ee = false)
175
-    {
176
-        $this->request_params->setRequestParam($key, $value, $override_ee);
177
-    }
178
-
179
-
180
-    /**
181
-     * returns sanitized value for a request param if the given key exists
182
-     *
183
-     * @param string     $key
184
-     * @param mixed|null $default
185
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
186
-     * @param string     $delimiter for CSV type strings that should be returned as an array
187
-     * @return array|bool|float|int|string
188
-     */
189
-    public function getRequestParam($key, $default = null, $type = 'string', $delimiter = ',')
190
-    {
191
-        return $this->request_params->getRequestParam($key, $default, $type, $delimiter);
192
-    }
193
-
194
-
195
-    /**
196
-     * check if param exists
197
-     *
198
-     * @param string $key
199
-     * @return bool
200
-     */
201
-    public function requestParamIsSet($key)
202
-    {
203
-        return $this->request_params->requestParamIsSet($key);
204
-    }
205
-
206
-
207
-    /**
208
-     * check if a request parameter exists whose key that matches the supplied wildcard pattern
209
-     * and return the sanitized value for the first match found
210
-     * wildcards can be either of the following:
211
-     *      ? to represent a single character of any type
212
-     *      * to represent one or more characters of any type
213
-     *
214
-     * @param string     $pattern
215
-     * @param mixed|null $default
216
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
217
-     * @param string     $delimiter for CSV type strings that should be returned as an array
218
-     * @return array|bool|float|int|string
219
-     */
220
-    public function getMatch($pattern, $default = null, $type = 'string', $delimiter = ',')
221
-    {
222
-        return $this->request_params->getMatch($pattern, $default, $type, $delimiter);
223
-    }
224
-
225
-
226
-    /**
227
-     * check if a request parameter exists whose key matches the supplied wildcard pattern
228
-     * wildcards can be either of the following:
229
-     *      ? to represent a single character of any type
230
-     *      * to represent one or more characters of any type
231
-     * returns true if a match is found or false if not
232
-     *
233
-     * @param string $pattern
234
-     * @return bool
235
-     */
236
-    public function matches($pattern)
237
-    {
238
-        return $this->request_params->matches($pattern);
239
-    }
240
-
241
-
242
-    /**
243
-     * remove param
244
-     *
245
-     * @param      $key
246
-     * @param bool $unset_from_global_too
247
-     */
248
-    public function unSetRequestParam($key, $unset_from_global_too = false)
249
-    {
250
-        $this->request_params->unSetRequestParam($key, $unset_from_global_too);
251
-    }
252
-
253
-
254
-    /**
255
-     * remove params
256
-     *
257
-     * @param array $keys
258
-     * @param bool  $unset_from_global_too
259
-     */
260
-    public function unSetRequestParams(array $keys, $unset_from_global_too = false)
261
-    {
262
-        $this->request_params->unSetRequestParams($keys, $unset_from_global_too);
263
-    }
264
-
265
-
266
-    /**
267
-     * @return string
268
-     */
269
-    public function ipAddress()
270
-    {
271
-        return $this->server_params->ipAddress();
272
-    }
273
-
274
-
275
-    /**
276
-     * Gets the request's literal URI. Related to `requestUriAfterSiteHomeUri`, see its description for a comparison.
277
-     *
278
-     * @param boolean $relativeToWpRoot If home_url() is "http://mysite.com/wp/", and a request comes to
279
-     *                                  "http://mysite.com/wp/wp-json", setting $relativeToWpRoot=true will return
280
-     *                                  "/wp-json", whereas $relativeToWpRoot=false will return "/wp/wp-json/".
281
-     * @return string
282
-     */
283
-    public function requestUri($relativeToWpRoot = false)
284
-    {
285
-        return $this->server_params->requestUri();
286
-    }
287
-
288
-
289
-    /**
290
-     * @return string
291
-     */
292
-    public function userAgent()
293
-    {
294
-        return $this->server_params->userAgent();
295
-    }
296
-
297
-
298
-    /**
299
-     * @param string $user_agent
300
-     */
301
-    public function setUserAgent($user_agent = '')
302
-    {
303
-        $this->server_params->setUserAgent($user_agent);
304
-    }
305
-
306
-
307
-    /**
308
-     * @return bool
309
-     */
310
-    public function isBot()
311
-    {
312
-        return $this->is_bot;
313
-    }
314
-
315
-
316
-    /**
317
-     * @param bool $is_bot
318
-     */
319
-    public function setIsBot($is_bot)
320
-    {
321
-        $this->is_bot = filter_var($is_bot, FILTER_VALIDATE_BOOLEAN);
322
-    }
323
-
324
-
325
-    /**
326
-     * @return bool
327
-     */
328
-    public function isActivation()
329
-    {
330
-        return $this->request_type->isActivation();
331
-    }
332
-
333
-
334
-    /**
335
-     * @param $is_activation
336
-     * @return bool
337
-     */
338
-    public function setIsActivation($is_activation)
339
-    {
340
-        return $this->request_type->setIsActivation($is_activation);
341
-    }
342
-
343
-
344
-    /**
345
-     * @return bool
346
-     */
347
-    public function isAdmin()
348
-    {
349
-        return $this->request_type->isAdmin();
350
-    }
351
-
352
-
353
-    /**
354
-     * @return bool
355
-     */
356
-    public function isAdminAjax()
357
-    {
358
-        return $this->request_type->isAdminAjax();
359
-    }
360
-
361
-
362
-    /**
363
-     * @return bool
364
-     */
365
-    public function isAjax()
366
-    {
367
-        return $this->request_type->isAjax();
368
-    }
369
-
370
-
371
-    /**
372
-     * @return bool
373
-     */
374
-    public function isEeAjax()
375
-    {
376
-        return $this->request_type->isEeAjax();
377
-    }
378
-
379
-
380
-    /**
381
-     * @return bool
382
-     */
383
-    public function isOtherAjax()
384
-    {
385
-        return $this->request_type->isOtherAjax();
386
-    }
387
-
388
-
389
-    /**
390
-     * @return bool
391
-     */
392
-    public function isApi()
393
-    {
394
-        return $this->request_type->isApi();
395
-    }
396
-
397
-
398
-    /**
399
-     * @return bool
400
-     */
401
-    public function isCli()
402
-    {
403
-        return $this->request_type->isCli();
404
-    }
405
-
406
-
407
-    /**
408
-     * @return bool
409
-     */
410
-    public function isCron()
411
-    {
412
-        return $this->request_type->isCron();
413
-    }
414
-
415
-
416
-    /**
417
-     * @return bool
418
-     */
419
-    public function isFeed()
420
-    {
421
-        return $this->request_type->isFeed();
422
-    }
423
-
424
-
425
-    /**
426
-     * @return bool
427
-     */
428
-    public function isFrontend()
429
-    {
430
-        return $this->request_type->isFrontend();
431
-    }
432
-
433
-
434
-    /**
435
-     * @return bool
436
-     */
437
-    public function isFrontAjax()
438
-    {
439
-        return $this->request_type->isFrontAjax();
440
-    }
441
-
442
-
443
-    /**
444
-     * @return bool
445
-     */
446
-    public function isIframe()
447
-    {
448
-        return $this->request_type->isIframe();
449
-    }
450
-
451
-
452
-    /**
453
-     * @return bool
454
-     */
455
-    public function isWordPressApi()
456
-    {
457
-        return $this->request_type->isWordPressApi();
458
-    }
459
-
460
-
461
-    /**
462
-     * @return bool
463
-     */
464
-    public function isWordPressHeartbeat()
465
-    {
466
-        return $this->request_type->isWordPressHeartbeat();
467
-    }
468
-
469
-
470
-    /**
471
-     * @return bool
472
-     */
473
-    public function isWordPressScrape()
474
-    {
475
-        return $this->request_type->isWordPressScrape();
476
-    }
477
-
478
-
479
-    /**
480
-     * @return string
481
-     */
482
-    public function slug()
483
-    {
484
-        return $this->request_type->slug();
485
-    }
486
-
487
-
488
-    /**
489
-     * @return RequestTypeContextCheckerInterface
490
-     */
491
-    public function getRequestType()
492
-    {
493
-        return $this->request_type;
494
-    }
20
+	/**
21
+	 * $_COOKIE parameters
22
+	 *
23
+	 * @var array
24
+	 */
25
+	protected $cookies;
26
+
27
+	/**
28
+	 * $_FILES parameters
29
+	 *
30
+	 * @var array
31
+	 */
32
+	protected $files;
33
+
34
+	/**
35
+	 * true if current user appears to be some kind of bot
36
+	 *
37
+	 * @var bool
38
+	 */
39
+	protected $is_bot;
40
+
41
+	/**
42
+	 * @var RequestParams
43
+	 */
44
+	protected $request_params;
45
+
46
+	/**
47
+	 * @var RequestTypeContextCheckerInterface
48
+	 */
49
+	protected $request_type;
50
+
51
+	/**
52
+	 * @var ServerParams
53
+	 */
54
+	protected $server_params;
55
+
56
+
57
+	public function __construct(
58
+		RequestParams $request_params,
59
+		ServerParams $server_params,
60
+		array $cookies = [],
61
+		array $files = []
62
+	) {
63
+		$this->cookies = ! empty($cookies)
64
+			? $cookies
65
+			: filter_input_array(INPUT_COOKIE, FILTER_SANITIZE_STRING);
66
+		$this->files          = ! empty($files) ? $files : $_FILES;
67
+		$this->request_params = $request_params;
68
+		$this->server_params  = $server_params;
69
+	}
70
+
71
+
72
+	/**
73
+	 * @param RequestTypeContextCheckerInterface $type
74
+	 */
75
+	public function setRequestTypeContextChecker(RequestTypeContextCheckerInterface $type)
76
+	{
77
+		$this->request_type = $type;
78
+	}
79
+
80
+
81
+	/**
82
+	 * @return array
83
+	 */
84
+	public function getParams()
85
+	{
86
+		return $this->request_params->getParams();
87
+	}
88
+
89
+
90
+	/**
91
+	 * @return array
92
+	 */
93
+	public function postParams()
94
+	{
95
+		return $this->request_params->postParams();
96
+	}
97
+
98
+
99
+	/**
100
+	 * @return array
101
+	 */
102
+	public function cookieParams()
103
+	{
104
+		return $this->cookies;
105
+	}
106
+
107
+
108
+	/**
109
+	 * @return array
110
+	 */
111
+	public function serverParams()
112
+	{
113
+		return $this->server_params->getAllServerParams();
114
+	}
115
+
116
+
117
+	/**
118
+	 * @param string $key
119
+	 * @return array|int|float|string
120
+	 */
121
+	public function getServerParam($key)
122
+	{
123
+		return $this->server_params->getServerParam($key);
124
+	}
125
+
126
+
127
+	/**
128
+	 * @param string                 $key
129
+	 * @param array|int|float|string $value
130
+	 * @return void
131
+	 */
132
+	public function setServerParam($key, $value)
133
+	{
134
+		$this->server_params->setServerParam($key, $value);
135
+	}
136
+
137
+
138
+	/**
139
+	 * @param string $key
140
+	 * @return bool
141
+	 */
142
+	public function serverParamIsSet($key)
143
+	{
144
+		return $this->server_params->serverParamIsSet($key);
145
+	}
146
+
147
+
148
+	/**
149
+	 * @return array
150
+	 */
151
+	public function filesParams()
152
+	{
153
+		return $this->files;
154
+	}
155
+
156
+
157
+	/**
158
+	 * returns sanitized contents of $_REQUEST
159
+	 *
160
+	 * @return array
161
+	 */
162
+	public function requestParams()
163
+	{
164
+		return $this->request_params->requestParams();
165
+	}
166
+
167
+
168
+	/**
169
+	 * @param string     $key
170
+	 * @param mixed|null $value
171
+	 * @param bool       $override_ee
172
+	 * @return void
173
+	 */
174
+	public function setRequestParam($key, $value, $override_ee = false)
175
+	{
176
+		$this->request_params->setRequestParam($key, $value, $override_ee);
177
+	}
178
+
179
+
180
+	/**
181
+	 * returns sanitized value for a request param if the given key exists
182
+	 *
183
+	 * @param string     $key
184
+	 * @param mixed|null $default
185
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
186
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
187
+	 * @return array|bool|float|int|string
188
+	 */
189
+	public function getRequestParam($key, $default = null, $type = 'string', $delimiter = ',')
190
+	{
191
+		return $this->request_params->getRequestParam($key, $default, $type, $delimiter);
192
+	}
193
+
194
+
195
+	/**
196
+	 * check if param exists
197
+	 *
198
+	 * @param string $key
199
+	 * @return bool
200
+	 */
201
+	public function requestParamIsSet($key)
202
+	{
203
+		return $this->request_params->requestParamIsSet($key);
204
+	}
205
+
206
+
207
+	/**
208
+	 * check if a request parameter exists whose key that matches the supplied wildcard pattern
209
+	 * and return the sanitized value for the first match found
210
+	 * wildcards can be either of the following:
211
+	 *      ? to represent a single character of any type
212
+	 *      * to represent one or more characters of any type
213
+	 *
214
+	 * @param string     $pattern
215
+	 * @param mixed|null $default
216
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
217
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
218
+	 * @return array|bool|float|int|string
219
+	 */
220
+	public function getMatch($pattern, $default = null, $type = 'string', $delimiter = ',')
221
+	{
222
+		return $this->request_params->getMatch($pattern, $default, $type, $delimiter);
223
+	}
224
+
225
+
226
+	/**
227
+	 * check if a request parameter exists whose key matches the supplied wildcard pattern
228
+	 * wildcards can be either of the following:
229
+	 *      ? to represent a single character of any type
230
+	 *      * to represent one or more characters of any type
231
+	 * returns true if a match is found or false if not
232
+	 *
233
+	 * @param string $pattern
234
+	 * @return bool
235
+	 */
236
+	public function matches($pattern)
237
+	{
238
+		return $this->request_params->matches($pattern);
239
+	}
240
+
241
+
242
+	/**
243
+	 * remove param
244
+	 *
245
+	 * @param      $key
246
+	 * @param bool $unset_from_global_too
247
+	 */
248
+	public function unSetRequestParam($key, $unset_from_global_too = false)
249
+	{
250
+		$this->request_params->unSetRequestParam($key, $unset_from_global_too);
251
+	}
252
+
253
+
254
+	/**
255
+	 * remove params
256
+	 *
257
+	 * @param array $keys
258
+	 * @param bool  $unset_from_global_too
259
+	 */
260
+	public function unSetRequestParams(array $keys, $unset_from_global_too = false)
261
+	{
262
+		$this->request_params->unSetRequestParams($keys, $unset_from_global_too);
263
+	}
264
+
265
+
266
+	/**
267
+	 * @return string
268
+	 */
269
+	public function ipAddress()
270
+	{
271
+		return $this->server_params->ipAddress();
272
+	}
273
+
274
+
275
+	/**
276
+	 * Gets the request's literal URI. Related to `requestUriAfterSiteHomeUri`, see its description for a comparison.
277
+	 *
278
+	 * @param boolean $relativeToWpRoot If home_url() is "http://mysite.com/wp/", and a request comes to
279
+	 *                                  "http://mysite.com/wp/wp-json", setting $relativeToWpRoot=true will return
280
+	 *                                  "/wp-json", whereas $relativeToWpRoot=false will return "/wp/wp-json/".
281
+	 * @return string
282
+	 */
283
+	public function requestUri($relativeToWpRoot = false)
284
+	{
285
+		return $this->server_params->requestUri();
286
+	}
287
+
288
+
289
+	/**
290
+	 * @return string
291
+	 */
292
+	public function userAgent()
293
+	{
294
+		return $this->server_params->userAgent();
295
+	}
296
+
297
+
298
+	/**
299
+	 * @param string $user_agent
300
+	 */
301
+	public function setUserAgent($user_agent = '')
302
+	{
303
+		$this->server_params->setUserAgent($user_agent);
304
+	}
305
+
306
+
307
+	/**
308
+	 * @return bool
309
+	 */
310
+	public function isBot()
311
+	{
312
+		return $this->is_bot;
313
+	}
314
+
315
+
316
+	/**
317
+	 * @param bool $is_bot
318
+	 */
319
+	public function setIsBot($is_bot)
320
+	{
321
+		$this->is_bot = filter_var($is_bot, FILTER_VALIDATE_BOOLEAN);
322
+	}
323
+
324
+
325
+	/**
326
+	 * @return bool
327
+	 */
328
+	public function isActivation()
329
+	{
330
+		return $this->request_type->isActivation();
331
+	}
332
+
333
+
334
+	/**
335
+	 * @param $is_activation
336
+	 * @return bool
337
+	 */
338
+	public function setIsActivation($is_activation)
339
+	{
340
+		return $this->request_type->setIsActivation($is_activation);
341
+	}
342
+
343
+
344
+	/**
345
+	 * @return bool
346
+	 */
347
+	public function isAdmin()
348
+	{
349
+		return $this->request_type->isAdmin();
350
+	}
351
+
352
+
353
+	/**
354
+	 * @return bool
355
+	 */
356
+	public function isAdminAjax()
357
+	{
358
+		return $this->request_type->isAdminAjax();
359
+	}
360
+
361
+
362
+	/**
363
+	 * @return bool
364
+	 */
365
+	public function isAjax()
366
+	{
367
+		return $this->request_type->isAjax();
368
+	}
369
+
370
+
371
+	/**
372
+	 * @return bool
373
+	 */
374
+	public function isEeAjax()
375
+	{
376
+		return $this->request_type->isEeAjax();
377
+	}
378
+
379
+
380
+	/**
381
+	 * @return bool
382
+	 */
383
+	public function isOtherAjax()
384
+	{
385
+		return $this->request_type->isOtherAjax();
386
+	}
387
+
388
+
389
+	/**
390
+	 * @return bool
391
+	 */
392
+	public function isApi()
393
+	{
394
+		return $this->request_type->isApi();
395
+	}
396
+
397
+
398
+	/**
399
+	 * @return bool
400
+	 */
401
+	public function isCli()
402
+	{
403
+		return $this->request_type->isCli();
404
+	}
405
+
406
+
407
+	/**
408
+	 * @return bool
409
+	 */
410
+	public function isCron()
411
+	{
412
+		return $this->request_type->isCron();
413
+	}
414
+
415
+
416
+	/**
417
+	 * @return bool
418
+	 */
419
+	public function isFeed()
420
+	{
421
+		return $this->request_type->isFeed();
422
+	}
423
+
424
+
425
+	/**
426
+	 * @return bool
427
+	 */
428
+	public function isFrontend()
429
+	{
430
+		return $this->request_type->isFrontend();
431
+	}
432
+
433
+
434
+	/**
435
+	 * @return bool
436
+	 */
437
+	public function isFrontAjax()
438
+	{
439
+		return $this->request_type->isFrontAjax();
440
+	}
441
+
442
+
443
+	/**
444
+	 * @return bool
445
+	 */
446
+	public function isIframe()
447
+	{
448
+		return $this->request_type->isIframe();
449
+	}
450
+
451
+
452
+	/**
453
+	 * @return bool
454
+	 */
455
+	public function isWordPressApi()
456
+	{
457
+		return $this->request_type->isWordPressApi();
458
+	}
459
+
460
+
461
+	/**
462
+	 * @return bool
463
+	 */
464
+	public function isWordPressHeartbeat()
465
+	{
466
+		return $this->request_type->isWordPressHeartbeat();
467
+	}
468
+
469
+
470
+	/**
471
+	 * @return bool
472
+	 */
473
+	public function isWordPressScrape()
474
+	{
475
+		return $this->request_type->isWordPressScrape();
476
+	}
477
+
478
+
479
+	/**
480
+	 * @return string
481
+	 */
482
+	public function slug()
483
+	{
484
+		return $this->request_type->slug();
485
+	}
486
+
487
+
488
+	/**
489
+	 * @return RequestTypeContextCheckerInterface
490
+	 */
491
+	public function getRequestType()
492
+	{
493
+		return $this->request_type;
494
+	}
495 495
 }
Please login to merge, or discard this patch.
core/services/request/CurrentPage.php 2 patches
Indentation   +289 added lines, -289 removed lines patch added patch discarded remove patch
@@ -7,293 +7,293 @@
 block discarded – undo
7 7
 
8 8
 class CurrentPage
9 9
 {
10
-    /**
11
-     * @var EE_CPT_Strategy
12
-     */
13
-    private $cpt_strategy;
14
-
15
-    /**
16
-     * @var bool
17
-     */
18
-    private $initialized;
19
-
20
-    /**
21
-     * @var bool
22
-     */
23
-    private $is_espresso_page = false;
24
-
25
-    /**
26
-     * @var int
27
-     */
28
-    private $post_id = 0;
29
-
30
-    /**
31
-     * @var string
32
-     */
33
-    private $post_name = '';
34
-
35
-    /**
36
-     * @var array
37
-     */
38
-    private $post_type = [];
39
-
40
-    /**
41
-     * @var RequestInterface $request
42
-     */
43
-    private $request;
44
-
45
-
46
-    /**
47
-     * CurrentPage constructor.
48
-     *
49
-     * @param EE_CPT_Strategy  $cpt_strategy
50
-     * @param RequestInterface $request
51
-     */
52
-    public function __construct(EE_CPT_Strategy $cpt_strategy, RequestInterface $request)
53
-    {
54
-        $this->cpt_strategy = $cpt_strategy;
55
-        $this->request      = $request;
56
-        $this->initialized  = is_admin();
57
-        // analyse the incoming WP request
58
-        add_action('parse_request', [$this, 'parseQueryVars'], 2, 1);
59
-    }
60
-
61
-
62
-    /**
63
-     * @param WP $WP
64
-     * @return void
65
-     */
66
-    public function parseQueryVars(WP $WP = null)
67
-    {
68
-        if ($this->initialized) {
69
-            return;
70
-        }
71
-        // if somebody forgot to provide us with WP, that's ok because its global
72
-        if (! $WP instanceof WP) {
73
-            global $WP;
74
-        }
75
-        $this->post_id   = $this->getPostId($WP);
76
-        $this->post_name = $this->getPostName($WP);
77
-        $this->post_type = $this->getPostType($WP);
78
-        // true or false ? is this page being used by EE ?
79
-        $this->setEspressoPage();
80
-        remove_action('parse_request', [$this, 'parseRequest'], 2);
81
-        $this->initialized   = true;
82
-    }
83
-
84
-
85
-    /**
86
-     * Just a helper method for getting the url for the displayed page.
87
-     *
88
-     * @param WP|null $WP
89
-     * @return string
90
-     */
91
-    public function getPermalink(WP $WP = null)
92
-    {
93
-        $post_id = $this->post_id ?: $this->getPostId($WP);
94
-        if ($post_id) {
95
-            return get_permalink($post_id);
96
-        }
97
-        if (! $WP instanceof WP) {
98
-            global $WP;
99
-        }
100
-        if ($WP instanceof WP && $WP->request) {
101
-            return site_url($WP->request);
102
-        }
103
-        return esc_url_raw(site_url($_SERVER['REQUEST_URI']));
104
-    }
105
-
106
-
107
-    /**
108
-     * @return array
109
-     */
110
-    public function espressoPostType()
111
-    {
112
-        return array_filter(
113
-            $this->post_type,
114
-            function ($post_type) {
115
-                return strpos($post_type, 'espresso_') === 0;
116
-            }
117
-        );
118
-    }
119
-
120
-
121
-    /**
122
-     * @param WP $WP
123
-     * @return int
124
-     */
125
-    private function getPostId(WP $WP = null)
126
-    {
127
-        $post_id = null;
128
-        if ($WP instanceof WP) {
129
-            if (isset($WP->query_vars['p'])) {
130
-                $post_id = $WP->query_vars['p'];
131
-            }
132
-            if (! $post_id && isset($WP->query_vars['page_id'])) {
133
-                $post_id = $WP->query_vars['page_id'];
134
-            }
135
-            if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
136
-                $post_id = basename($WP->request);
137
-            }
138
-        }
139
-        if (! $post_id && $this->request->requestParamIsSet('post_id')) {
140
-            $post_id = $this->request->getRequestParam('post_id');
141
-        }
142
-        return $post_id;
143
-    }
144
-
145
-
146
-    /**
147
-     * @param WP $WP
148
-     * @return string
149
-     */
150
-    private function getPostName(WP $WP = null)
151
-    {
152
-        global $wpdb;
153
-        $post_name = null;
154
-        if ($WP instanceof WP) {
155
-            if (isset($WP->query_vars['name']) && ! empty($WP->query_vars['name'])) {
156
-                $post_name = $WP->query_vars['name'];
157
-            }
158
-            if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
159
-                $post_name = $WP->query_vars['pagename'];
160
-            }
161
-            if (! $post_name && $WP->request !== null && ! empty($WP->request)) {
162
-                $possible_post_name = basename($WP->request);
163
-                if (! is_numeric($possible_post_name)) {
164
-                    $SQL                = "SELECT ID from {$wpdb->posts}";
165
-                    $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
166
-                    $SQL                .= ' AND post_name=%s';
167
-                    $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
168
-                    if ($possible_post_name) {
169
-                        $post_name = $possible_post_name;
170
-                    }
171
-                }
172
-            }
173
-        }
174
-        if (! $post_name && $this->post_id) {
175
-            $SQL                = "SELECT post_name from {$wpdb->posts}";
176
-            $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
177
-            $SQL                .= ' AND ID=%d';
178
-            $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->post_id));
179
-            if ($possible_post_name) {
180
-                $post_name = $possible_post_name;
181
-            }
182
-        }
183
-        if (! $post_name && $this->request->requestParamIsSet('post_name')) {
184
-            $post_name = $this->request->getRequestParam('post_name');
185
-        }
186
-        return $post_name;
187
-    }
188
-
189
-
190
-    /**
191
-     * @param WP $WP
192
-     * @return array
193
-     */
194
-    private function getPostType(WP $WP = null)
195
-    {
196
-        $post_types = [];
197
-        if ($WP instanceof WP) {
198
-            $post_types = isset($WP->query_vars['post_type'])
199
-                ? (array) $WP->query_vars['post_type']
200
-                : [];
201
-        }
202
-        if (empty($post_types) && $this->request->requestParamIsSet('post_type')) {
203
-            $post_types = $this->request->getRequestParam('post_type');
204
-        }
205
-        return (array) $post_types;
206
-    }
207
-
208
-
209
-    /**
210
-     * @return bool
211
-     */
212
-    public function isEspressoPage()
213
-    {
214
-        return $this->is_espresso_page;
215
-    }
216
-
217
-
218
-    /**
219
-     * @return int
220
-     */
221
-    public function postId()
222
-    {
223
-        return $this->post_id;
224
-    }
225
-
226
-
227
-    /**
228
-     * @return string
229
-     */
230
-    public function postName()
231
-    {
232
-        return $this->post_name;
233
-    }
234
-
235
-
236
-    /**
237
-     * @return array
238
-     */
239
-    public function postType()
240
-    {
241
-        return $this->post_type;
242
-    }
243
-
244
-
245
-    /**
246
-     * @param null|bool $value
247
-     * @return void
248
-     */
249
-    public function setEspressoPage($value = null)
250
-    {
251
-        $this->is_espresso_page = $value !== null
252
-            ? filter_var($value, FILTER_VALIDATE_BOOLEAN)
253
-            : $this->testForEspressoPage();
254
-    }
255
-
256
-
257
-    /**
258
-     * @return bool
259
-     */
260
-    private function testForEspressoPage()
261
-    {
262
-        // in case it has already been set
263
-        if ($this->is_espresso_page) {
264
-            return true;
265
-        }
266
-        global $WP;
267
-        $espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
268
-        if (is_array($espresso_CPT_taxonomies)) {
269
-            foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
270
-                if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
271
-                    return true;
272
-                }
273
-            }
274
-        }
275
-        // load espresso CPT endpoints
276
-        $espresso_CPT_endpoints  = $this->cpt_strategy->get_CPT_endpoints();
277
-        $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
278
-        foreach ($this->post_type as $post_type) {
279
-            // was a post name passed ?
280
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
281
-                // kk we know this is an espresso page, but is it a specific post ?
282
-                if (! $this->post_name) {
283
-                    $espresso_post_type = $this->request->getRequestParam('post_type');
284
-                    // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
285
-                    // this essentially sets the post_name to "events" (or whatever EE CPT)
286
-                    $post_name = isset($post_type_CPT_endpoints[ $espresso_post_type ])
287
-                        ? $post_type_CPT_endpoints[ $espresso_post_type ]
288
-                        : '';
289
-                    // if the post type matches one of ours then set the post name to the endpoint
290
-                    if ($post_name) {
291
-                        $this->post_name = $post_name;
292
-                    }
293
-                }
294
-                return true;
295
-            }
296
-        }
297
-        return false;
298
-    }
10
+	/**
11
+	 * @var EE_CPT_Strategy
12
+	 */
13
+	private $cpt_strategy;
14
+
15
+	/**
16
+	 * @var bool
17
+	 */
18
+	private $initialized;
19
+
20
+	/**
21
+	 * @var bool
22
+	 */
23
+	private $is_espresso_page = false;
24
+
25
+	/**
26
+	 * @var int
27
+	 */
28
+	private $post_id = 0;
29
+
30
+	/**
31
+	 * @var string
32
+	 */
33
+	private $post_name = '';
34
+
35
+	/**
36
+	 * @var array
37
+	 */
38
+	private $post_type = [];
39
+
40
+	/**
41
+	 * @var RequestInterface $request
42
+	 */
43
+	private $request;
44
+
45
+
46
+	/**
47
+	 * CurrentPage constructor.
48
+	 *
49
+	 * @param EE_CPT_Strategy  $cpt_strategy
50
+	 * @param RequestInterface $request
51
+	 */
52
+	public function __construct(EE_CPT_Strategy $cpt_strategy, RequestInterface $request)
53
+	{
54
+		$this->cpt_strategy = $cpt_strategy;
55
+		$this->request      = $request;
56
+		$this->initialized  = is_admin();
57
+		// analyse the incoming WP request
58
+		add_action('parse_request', [$this, 'parseQueryVars'], 2, 1);
59
+	}
60
+
61
+
62
+	/**
63
+	 * @param WP $WP
64
+	 * @return void
65
+	 */
66
+	public function parseQueryVars(WP $WP = null)
67
+	{
68
+		if ($this->initialized) {
69
+			return;
70
+		}
71
+		// if somebody forgot to provide us with WP, that's ok because its global
72
+		if (! $WP instanceof WP) {
73
+			global $WP;
74
+		}
75
+		$this->post_id   = $this->getPostId($WP);
76
+		$this->post_name = $this->getPostName($WP);
77
+		$this->post_type = $this->getPostType($WP);
78
+		// true or false ? is this page being used by EE ?
79
+		$this->setEspressoPage();
80
+		remove_action('parse_request', [$this, 'parseRequest'], 2);
81
+		$this->initialized   = true;
82
+	}
83
+
84
+
85
+	/**
86
+	 * Just a helper method for getting the url for the displayed page.
87
+	 *
88
+	 * @param WP|null $WP
89
+	 * @return string
90
+	 */
91
+	public function getPermalink(WP $WP = null)
92
+	{
93
+		$post_id = $this->post_id ?: $this->getPostId($WP);
94
+		if ($post_id) {
95
+			return get_permalink($post_id);
96
+		}
97
+		if (! $WP instanceof WP) {
98
+			global $WP;
99
+		}
100
+		if ($WP instanceof WP && $WP->request) {
101
+			return site_url($WP->request);
102
+		}
103
+		return esc_url_raw(site_url($_SERVER['REQUEST_URI']));
104
+	}
105
+
106
+
107
+	/**
108
+	 * @return array
109
+	 */
110
+	public function espressoPostType()
111
+	{
112
+		return array_filter(
113
+			$this->post_type,
114
+			function ($post_type) {
115
+				return strpos($post_type, 'espresso_') === 0;
116
+			}
117
+		);
118
+	}
119
+
120
+
121
+	/**
122
+	 * @param WP $WP
123
+	 * @return int
124
+	 */
125
+	private function getPostId(WP $WP = null)
126
+	{
127
+		$post_id = null;
128
+		if ($WP instanceof WP) {
129
+			if (isset($WP->query_vars['p'])) {
130
+				$post_id = $WP->query_vars['p'];
131
+			}
132
+			if (! $post_id && isset($WP->query_vars['page_id'])) {
133
+				$post_id = $WP->query_vars['page_id'];
134
+			}
135
+			if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
136
+				$post_id = basename($WP->request);
137
+			}
138
+		}
139
+		if (! $post_id && $this->request->requestParamIsSet('post_id')) {
140
+			$post_id = $this->request->getRequestParam('post_id');
141
+		}
142
+		return $post_id;
143
+	}
144
+
145
+
146
+	/**
147
+	 * @param WP $WP
148
+	 * @return string
149
+	 */
150
+	private function getPostName(WP $WP = null)
151
+	{
152
+		global $wpdb;
153
+		$post_name = null;
154
+		if ($WP instanceof WP) {
155
+			if (isset($WP->query_vars['name']) && ! empty($WP->query_vars['name'])) {
156
+				$post_name = $WP->query_vars['name'];
157
+			}
158
+			if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
159
+				$post_name = $WP->query_vars['pagename'];
160
+			}
161
+			if (! $post_name && $WP->request !== null && ! empty($WP->request)) {
162
+				$possible_post_name = basename($WP->request);
163
+				if (! is_numeric($possible_post_name)) {
164
+					$SQL                = "SELECT ID from {$wpdb->posts}";
165
+					$SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
166
+					$SQL                .= ' AND post_name=%s';
167
+					$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
168
+					if ($possible_post_name) {
169
+						$post_name = $possible_post_name;
170
+					}
171
+				}
172
+			}
173
+		}
174
+		if (! $post_name && $this->post_id) {
175
+			$SQL                = "SELECT post_name from {$wpdb->posts}";
176
+			$SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
177
+			$SQL                .= ' AND ID=%d';
178
+			$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->post_id));
179
+			if ($possible_post_name) {
180
+				$post_name = $possible_post_name;
181
+			}
182
+		}
183
+		if (! $post_name && $this->request->requestParamIsSet('post_name')) {
184
+			$post_name = $this->request->getRequestParam('post_name');
185
+		}
186
+		return $post_name;
187
+	}
188
+
189
+
190
+	/**
191
+	 * @param WP $WP
192
+	 * @return array
193
+	 */
194
+	private function getPostType(WP $WP = null)
195
+	{
196
+		$post_types = [];
197
+		if ($WP instanceof WP) {
198
+			$post_types = isset($WP->query_vars['post_type'])
199
+				? (array) $WP->query_vars['post_type']
200
+				: [];
201
+		}
202
+		if (empty($post_types) && $this->request->requestParamIsSet('post_type')) {
203
+			$post_types = $this->request->getRequestParam('post_type');
204
+		}
205
+		return (array) $post_types;
206
+	}
207
+
208
+
209
+	/**
210
+	 * @return bool
211
+	 */
212
+	public function isEspressoPage()
213
+	{
214
+		return $this->is_espresso_page;
215
+	}
216
+
217
+
218
+	/**
219
+	 * @return int
220
+	 */
221
+	public function postId()
222
+	{
223
+		return $this->post_id;
224
+	}
225
+
226
+
227
+	/**
228
+	 * @return string
229
+	 */
230
+	public function postName()
231
+	{
232
+		return $this->post_name;
233
+	}
234
+
235
+
236
+	/**
237
+	 * @return array
238
+	 */
239
+	public function postType()
240
+	{
241
+		return $this->post_type;
242
+	}
243
+
244
+
245
+	/**
246
+	 * @param null|bool $value
247
+	 * @return void
248
+	 */
249
+	public function setEspressoPage($value = null)
250
+	{
251
+		$this->is_espresso_page = $value !== null
252
+			? filter_var($value, FILTER_VALIDATE_BOOLEAN)
253
+			: $this->testForEspressoPage();
254
+	}
255
+
256
+
257
+	/**
258
+	 * @return bool
259
+	 */
260
+	private function testForEspressoPage()
261
+	{
262
+		// in case it has already been set
263
+		if ($this->is_espresso_page) {
264
+			return true;
265
+		}
266
+		global $WP;
267
+		$espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
268
+		if (is_array($espresso_CPT_taxonomies)) {
269
+			foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
270
+				if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
271
+					return true;
272
+				}
273
+			}
274
+		}
275
+		// load espresso CPT endpoints
276
+		$espresso_CPT_endpoints  = $this->cpt_strategy->get_CPT_endpoints();
277
+		$post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
278
+		foreach ($this->post_type as $post_type) {
279
+			// was a post name passed ?
280
+			if (isset($post_type_CPT_endpoints[ $post_type ])) {
281
+				// kk we know this is an espresso page, but is it a specific post ?
282
+				if (! $this->post_name) {
283
+					$espresso_post_type = $this->request->getRequestParam('post_type');
284
+					// there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
285
+					// this essentially sets the post_name to "events" (or whatever EE CPT)
286
+					$post_name = isset($post_type_CPT_endpoints[ $espresso_post_type ])
287
+						? $post_type_CPT_endpoints[ $espresso_post_type ]
288
+						: '';
289
+					// if the post type matches one of ours then set the post name to the endpoint
290
+					if ($post_name) {
291
+						$this->post_name = $post_name;
292
+					}
293
+				}
294
+				return true;
295
+			}
296
+		}
297
+		return false;
298
+	}
299 299
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
             return;
70 70
         }
71 71
         // if somebody forgot to provide us with WP, that's ok because its global
72
-        if (! $WP instanceof WP) {
72
+        if ( ! $WP instanceof WP) {
73 73
             global $WP;
74 74
         }
75 75
         $this->post_id   = $this->getPostId($WP);
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
         // true or false ? is this page being used by EE ?
79 79
         $this->setEspressoPage();
80 80
         remove_action('parse_request', [$this, 'parseRequest'], 2);
81
-        $this->initialized   = true;
81
+        $this->initialized = true;
82 82
     }
83 83
 
84 84
 
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
         if ($post_id) {
95 95
             return get_permalink($post_id);
96 96
         }
97
-        if (! $WP instanceof WP) {
97
+        if ( ! $WP instanceof WP) {
98 98
             global $WP;
99 99
         }
100 100
         if ($WP instanceof WP && $WP->request) {
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
     {
112 112
         return array_filter(
113 113
             $this->post_type,
114
-            function ($post_type) {
114
+            function($post_type) {
115 115
                 return strpos($post_type, 'espresso_') === 0;
116 116
             }
117 117
         );
@@ -129,14 +129,14 @@  discard block
 block discarded – undo
129 129
             if (isset($WP->query_vars['p'])) {
130 130
                 $post_id = $WP->query_vars['p'];
131 131
             }
132
-            if (! $post_id && isset($WP->query_vars['page_id'])) {
132
+            if ( ! $post_id && isset($WP->query_vars['page_id'])) {
133 133
                 $post_id = $WP->query_vars['page_id'];
134 134
             }
135
-            if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
135
+            if ( ! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
136 136
                 $post_id = basename($WP->request);
137 137
             }
138 138
         }
139
-        if (! $post_id && $this->request->requestParamIsSet('post_id')) {
139
+        if ( ! $post_id && $this->request->requestParamIsSet('post_id')) {
140 140
             $post_id = $this->request->getRequestParam('post_id');
141 141
         }
142 142
         return $post_id;
@@ -155,12 +155,12 @@  discard block
 block discarded – undo
155 155
             if (isset($WP->query_vars['name']) && ! empty($WP->query_vars['name'])) {
156 156
                 $post_name = $WP->query_vars['name'];
157 157
             }
158
-            if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
158
+            if ( ! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
159 159
                 $post_name = $WP->query_vars['pagename'];
160 160
             }
161
-            if (! $post_name && $WP->request !== null && ! empty($WP->request)) {
161
+            if ( ! $post_name && $WP->request !== null && ! empty($WP->request)) {
162 162
                 $possible_post_name = basename($WP->request);
163
-                if (! is_numeric($possible_post_name)) {
163
+                if ( ! is_numeric($possible_post_name)) {
164 164
                     $SQL                = "SELECT ID from {$wpdb->posts}";
165 165
                     $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
166 166
                     $SQL                .= ' AND post_name=%s';
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
                 }
172 172
             }
173 173
         }
174
-        if (! $post_name && $this->post_id) {
174
+        if ( ! $post_name && $this->post_id) {
175 175
             $SQL                = "SELECT post_name from {$wpdb->posts}";
176 176
             $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
177 177
             $SQL                .= ' AND ID=%d';
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
                 $post_name = $possible_post_name;
181 181
             }
182 182
         }
183
-        if (! $post_name && $this->request->requestParamIsSet('post_name')) {
183
+        if ( ! $post_name && $this->request->requestParamIsSet('post_name')) {
184 184
             $post_name = $this->request->getRequestParam('post_name');
185 185
         }
186 186
         return $post_name;
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
         $espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
268 268
         if (is_array($espresso_CPT_taxonomies)) {
269 269
             foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
270
-                if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
270
+                if (isset($WP->query_vars, $WP->query_vars[$espresso_CPT_taxonomy])) {
271 271
                     return true;
272 272
                 }
273 273
             }
@@ -277,14 +277,14 @@  discard block
 block discarded – undo
277 277
         $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
278 278
         foreach ($this->post_type as $post_type) {
279 279
             // was a post name passed ?
280
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
280
+            if (isset($post_type_CPT_endpoints[$post_type])) {
281 281
                 // kk we know this is an espresso page, but is it a specific post ?
282
-                if (! $this->post_name) {
282
+                if ( ! $this->post_name) {
283 283
                     $espresso_post_type = $this->request->getRequestParam('post_type');
284 284
                     // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
285 285
                     // this essentially sets the post_name to "events" (or whatever EE CPT)
286
-                    $post_name = isset($post_type_CPT_endpoints[ $espresso_post_type ])
287
-                        ? $post_type_CPT_endpoints[ $espresso_post_type ]
286
+                    $post_name = isset($post_type_CPT_endpoints[$espresso_post_type])
287
+                        ? $post_type_CPT_endpoints[$espresso_post_type]
288 288
                         : '';
289 289
                     // if the post type matches one of ours then set the post name to the endpoint
290 290
                     if ($post_name) {
Please login to merge, or discard this patch.