Completed
Branch FET-10416-autoload-b4-bootstra... (42a01c)
by
unknown
13:17
created
core/services/shortcodes/LegacyShortcodesManager.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -117,44 +117,44 @@  discard block
 block discarded – undo
117 117
             // remove last segment
118 118
             array_pop($shortcode_path);
119 119
             // glue it back together
120
-            $shortcode_path = implode(DS, $shortcode_path) . DS;
120
+            $shortcode_path = implode(DS, $shortcode_path).DS;
121 121
         } else {
122 122
             // we need to generate the filename based off of the folder name
123 123
             // grab and sanitize shortcode directory name
124 124
             $shortcode = sanitize_key(basename($shortcode_path));
125
-            $shortcode_path = rtrim($shortcode_path, DS) . DS;
125
+            $shortcode_path = rtrim($shortcode_path, DS).DS;
126 126
         }
127 127
         // create classname from shortcode directory or file name
128 128
         $shortcode = str_replace(' ', '_', ucwords(str_replace('_', ' ', $shortcode)));
129 129
         // add class prefix
130
-        $shortcode_class = 'EES_' . $shortcode;
130
+        $shortcode_class = 'EES_'.$shortcode;
131 131
         // does the shortcode exist ?
132
-        if ( ! is_readable($shortcode_path . DS . $shortcode_class . $shortcode_ext)) {
132
+        if ( ! is_readable($shortcode_path.DS.$shortcode_class.$shortcode_ext)) {
133 133
             $msg = sprintf(
134 134
                 esc_html__(
135 135
                     'The requested %s shortcode file could not be found or is not readable due to file permissions. It should be in %s',
136 136
                     'event_espresso'
137 137
                 ),
138 138
                 $shortcode_class,
139
-                $shortcode_path . DS . $shortcode_class . $shortcode_ext
139
+                $shortcode_path.DS.$shortcode_class.$shortcode_ext
140 140
             );
141
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
141
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
142 142
             return false;
143 143
         }
144 144
         // load the shortcode class file
145
-        require_once($shortcode_path . $shortcode_class . $shortcode_ext);
145
+        require_once($shortcode_path.$shortcode_class.$shortcode_ext);
146 146
         // verify that class exists
147 147
         if ( ! class_exists($shortcode_class)) {
148 148
             $msg = sprintf(
149 149
                 esc_html__('The requested %s shortcode class does not exist.', 'event_espresso'),
150 150
                 $shortcode_class
151 151
             );
152
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
152
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
153 153
             return false;
154 154
         }
155 155
         $shortcode = strtoupper($shortcode);
156 156
         // add to array of registered shortcodes
157
-        $this->registry->shortcodes->{$shortcode} = $shortcode_path . $shortcode_class . $shortcode_ext;
157
+        $this->registry->shortcodes->{$shortcode} = $shortcode_path.$shortcode_class.$shortcode_ext;
158 158
         return true;
159 159
     }
160 160
 
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
         // cycle thru shortcode folders
173 173
         foreach ($this->registry->shortcodes as $shortcode => $shortcode_path) {
174 174
             // add class prefix
175
-            $shortcode_class = 'EES_' . $shortcode;
175
+            $shortcode_class = 'EES_'.$shortcode;
176 176
             // fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
177 177
             // which set hooks ?
178 178
             if (is_admin()) {
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
     {
291 291
         $has_shortcode = false;
292 292
         foreach ($this->registry->shortcodes as $shortcode_class => $shortcode) {
293
-            if ($load_all || has_shortcode($content, $shortcode_class) ) {
293
+            if ($load_all || has_shortcode($content, $shortcode_class)) {
294 294
                 // load up the shortcode
295 295
                 $this->initializeShortcode($shortcode_class);
296 296
                 $has_shortcode = true;
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
      */
403 403
     public static function addShortcodeClassPrefix($class_name)
404 404
     {
405
-        return strpos($class_name, 'EES_') === 0 ? $class_name : 'EES_' . $class_name;
405
+        return strpos($class_name, 'EES_') === 0 ? $class_name : 'EES_'.$class_name;
406 406
     }
407 407
 
408 408
 
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
     {
415 415
         static $shortcode_tags = array();
416 416
         if (empty($shortcode_tags)) {
417
-            $shortcode_tags = array_keys((array)$this->registry->shortcodes);
417
+            $shortcode_tags = array_keys((array) $this->registry->shortcodes);
418 418
         }
419 419
         return $shortcode_tags;
420 420
     }
Please login to merge, or discard this patch.
Indentation   +423 added lines, -423 removed lines patch added patch discarded remove patch
@@ -25,429 +25,429 @@
 block discarded – undo
25 25
 class LegacyShortcodesManager
26 26
 {
27 27
 
28
-    /**
29
-     * @var EE_Registry $registry
30
-     */
31
-    private $registry;
32
-
33
-
34
-
35
-
36
-    /**
37
-     * LegacyShortcodesManager constructor.
38
-     *
39
-     * @param \EE_Registry $registry
40
-     */
41
-    public function __construct(EE_Registry $registry)
42
-    {
43
-        $this->registry = $registry;
44
-    }
45
-
46
-
47
-
48
-    /**
49
-     * @return EE_Registry
50
-     */
51
-    public function registry()
52
-    {
53
-        return $this->registry;
54
-    }
55
-
56
-
57
-
58
-    /**
59
-     * registerShortcodes
60
-     *
61
-     * @return void
62
-     */
63
-    public function registerShortcodes()
64
-    {
65
-        $this->registry->shortcodes = $this->getShortcodes();
66
-    }
67
-
68
-
69
-
70
-    /**
71
-     * getShortcodes
72
-     *
73
-     * @return array
74
-     */
75
-    public function getShortcodes()
76
-    {
77
-        // previously this method would glob the shortcodes directory
78
-        // then filter that list of shortcodes to register,
79
-        // but now we are going to just supply an empty array.
80
-        // this allows any shortcodes that have not yet been converted to the new system
81
-        // to still get loaded and processed, albeit using the same legacy logic as before
82
-        $shortcodes_to_register = apply_filters(
83
-            'FHEE__EE_Config__register_shortcodes__shortcodes_to_register',
84
-            array()
85
-        );
86
-        if ( ! empty($shortcodes_to_register)) {
87
-            // cycle thru shortcode folders
88
-            foreach ($shortcodes_to_register as $shortcode_path) {
89
-                // add to list of installed shortcode modules
90
-                $this->registerShortcode($shortcode_path);
91
-            }
92
-        }
93
-        // filter list of installed modules
94
-        return apply_filters(
95
-            'FHEE__EE_Config___register_shortcodes__installed_shortcodes',
96
-            ! empty($this->registry->shortcodes)
97
-                ? $this->registry->shortcodes
98
-                : array()
99
-        );
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     *    register_shortcode - makes core aware of this shortcode
106
-     *
107
-     * @access    public
108
-     * @param    string $shortcode_path - full path up to and including shortcode folder
109
-     * @return    bool
110
-     */
111
-    public function registerShortcode($shortcode_path = null)
112
-    {
113
-        do_action('AHEE__EE_Config__register_shortcode__begin', $shortcode_path);
114
-        $shortcode_ext = '.shortcode.php';
115
-        // make all separators match
116
-        $shortcode_path = str_replace(array('\\', '/'), DS, $shortcode_path);
117
-        // does the file path INCLUDE the actual file name as part of the path ?
118
-        if (strpos($shortcode_path, $shortcode_ext) !== false) {
119
-            // grab shortcode file name from directory name and break apart at dots
120
-            $shortcode_file = explode('.', basename($shortcode_path));
121
-            // take first segment from file name pieces and remove class prefix if it exists
122
-            $shortcode = strpos($shortcode_file[0], 'EES_') === 0
123
-                ? substr($shortcode_file[0], 4)
124
-                : $shortcode_file[0];
125
-            // sanitize shortcode directory name
126
-            $shortcode = sanitize_key($shortcode);
127
-            // now we need to rebuild the shortcode path
128
-            $shortcode_path = explode(DS, $shortcode_path);
129
-            // remove last segment
130
-            array_pop($shortcode_path);
131
-            // glue it back together
132
-            $shortcode_path = implode(DS, $shortcode_path) . DS;
133
-        } else {
134
-            // we need to generate the filename based off of the folder name
135
-            // grab and sanitize shortcode directory name
136
-            $shortcode = sanitize_key(basename($shortcode_path));
137
-            $shortcode_path = rtrim($shortcode_path, DS) . DS;
138
-        }
139
-        // create classname from shortcode directory or file name
140
-        $shortcode = str_replace(' ', '_', ucwords(str_replace('_', ' ', $shortcode)));
141
-        // add class prefix
142
-        $shortcode_class = 'EES_' . $shortcode;
143
-        // does the shortcode exist ?
144
-        if ( ! is_readable($shortcode_path . DS . $shortcode_class . $shortcode_ext)) {
145
-            $msg = sprintf(
146
-                esc_html__(
147
-                    'The requested %s shortcode file could not be found or is not readable due to file permissions. It should be in %s',
148
-                    'event_espresso'
149
-                ),
150
-                $shortcode_class,
151
-                $shortcode_path . DS . $shortcode_class . $shortcode_ext
152
-            );
153
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
154
-            return false;
155
-        }
156
-        // load the shortcode class file
157
-        require_once($shortcode_path . $shortcode_class . $shortcode_ext);
158
-        // verify that class exists
159
-        if ( ! class_exists($shortcode_class)) {
160
-            $msg = sprintf(
161
-                esc_html__('The requested %s shortcode class does not exist.', 'event_espresso'),
162
-                $shortcode_class
163
-            );
164
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
165
-            return false;
166
-        }
167
-        $shortcode = strtoupper($shortcode);
168
-        // add to array of registered shortcodes
169
-        $this->registry->shortcodes->{$shortcode} = $shortcode_path . $shortcode_class . $shortcode_ext;
170
-        return true;
171
-    }
172
-
173
-
174
-
175
-    /**
176
-     *    _initialize_shortcodes
177
-     *    allow shortcodes to set hooks for the rest of the system
178
-     *
179
-     * @access private
180
-     * @return void
181
-     */
182
-    public function addShortcodes()
183
-    {
184
-        // cycle thru shortcode folders
185
-        foreach ($this->registry->shortcodes as $shortcode => $shortcode_path) {
186
-            // add class prefix
187
-            $shortcode_class = 'EES_' . $shortcode;
188
-            // fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
189
-            // which set hooks ?
190
-            if (is_admin()) {
191
-                // fire immediately
192
-                call_user_func(array($shortcode_class, 'set_hooks_admin'));
193
-            } else {
194
-                // delay until other systems are online
195
-                add_action(
196
-                    'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
197
-                    array($shortcode_class, 'set_hooks')
198
-                );
199
-                // convert classname to UPPERCASE and create WP shortcode.
200
-                $shortcode_tag = strtoupper($shortcode);
201
-                // but first check if the shortcode has already
202
-                // been added before assigning 'fallback_shortcode_processor'
203
-                if ( ! shortcode_exists($shortcode_tag)) {
204
-                    // NOTE: this shortcode declaration will get overridden if the shortcode
205
-                    // is successfully detected in the post content in initializeShortcode()
206
-                    add_shortcode($shortcode_tag, array($shortcode_class, 'fallback_shortcode_processor'));
207
-                }
208
-            }
209
-        }
210
-    }
211
-
212
-
213
-
214
-    /**
215
-     * callback for the WP "get_header" hook point
216
-     * checks posts for EE shortcodes, and initializes them,
217
-     * then toggles filter switch that loads core default assets
218
-     *
219
-     * @param \WP_Query $wp_query
220
-     * @return void
221
-     */
222
-    public function initializeShortcodes(WP_Query $wp_query)
223
-    {
224
-        if (empty($this->registry->shortcodes) || ! $wp_query->is_main_query() || is_admin()) {
225
-            return;
226
-        }
227
-        global $wp;
228
-        /** @var EE_Front_controller $Front_Controller */
229
-        $Front_Controller = $this->registry->load_core('Front_Controller', array(), false);
230
-        do_action('AHEE__EE_Front_Controller__initialize_shortcodes__begin', $wp, $Front_Controller);
231
-        $Front_Controller->Request_Handler()->set_request_vars();
232
-        // grab post_name from request
233
-        $current_post = apply_filters(
234
-            'FHEE__EE_Front_Controller__initialize_shortcodes__current_post_name',
235
-            $Front_Controller->Request_Handler()->get('post_name')
236
-        );
237
-        $show_on_front = get_option('show_on_front');
238
-        // if it's not set, then check if frontpage is blog
239
-        if (empty($current_post)) {
240
-            // yup.. this is the posts page, prepare to load all shortcode modules
241
-            $current_post = 'posts';
242
-            // unless..
243
-            if ($show_on_front === 'page') {
244
-                // some other page is set as the homepage
245
-                $page_on_front = get_option('page_on_front');
246
-                if ($page_on_front) {
247
-                    // k now we need to find the post_name for this page
248
-                    global $wpdb;
249
-                    $page_on_front = $wpdb->get_var(
250
-                        $wpdb->prepare(
251
-                            "SELECT post_name from {$wpdb->posts} WHERE post_type='page' AND post_status='publish' AND ID=%d",
252
-                            $page_on_front
253
-                        )
254
-                    );
255
-                    // set the current post slug to what it actually is
256
-                    $current_post = $page_on_front ? $page_on_front : $current_post;
257
-                }
258
-            }
259
-        }
260
-        // in case $current_post is hierarchical like: /parent-page/current-page
261
-        $current_post = basename($current_post);
262
-        if (
263
-            // is current page/post the "blog" page ?
264
-            $current_post === EE_Config::get_page_for_posts()
265
-            // or are we on a category page?
266
-            || (
267
-                is_array(term_exists($current_post, 'category'))
268
-                || array_key_exists('category_name', $wp->query_vars)
269
-            )
270
-        ) {
271
-            // initialize all legacy shortcodes
272
-            $load_assets = $this->parseContentForShortcodes('', true);
273
-        } else {
274
-            global $wpdb;
275
-            $post_content = $wpdb->get_var(
276
-                $wpdb->prepare(
277
-                    "SELECT post_content from {$wpdb->posts} WHERE post_status='publish' AND post_name=%s",
278
-                    $current_post
279
-                )
280
-            );
281
-            $load_assets = $this->parseContentForShortcodes($post_content);
282
-        }
283
-        if ($load_assets) {
284
-            $this->registry->REQ->set_espresso_page(true);
285
-            add_filter('FHEE_load_css', '__return_true');
286
-            add_filter('FHEE_load_js', '__return_true');
287
-        }
288
-        do_action('AHEE__EE_Front_Controller__initialize_shortcodes__end', $Front_Controller);
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * checks supplied content against list of legacy shortcodes,
295
-     * then initializes any found shortcodes, and returns true.
296
-     * returns false if no shortcodes found.
297
-     *
298
-     * @param string $content
299
-     * @param bool   $load_all if true, then ALL active legacy shortcodes will be initialized
300
-     * @return bool
301
-     */
302
-    public function parseContentForShortcodes($content = '', $load_all = false)
303
-    {
304
-        $has_shortcode = false;
305
-        foreach ($this->registry->shortcodes as $shortcode_class => $shortcode) {
306
-            if ($load_all || has_shortcode($content, $shortcode_class) ) {
307
-                // load up the shortcode
308
-                $this->initializeShortcode($shortcode_class);
309
-                $has_shortcode = true;
310
-            }
311
-        }
312
-        return $has_shortcode;
313
-    }
314
-
315
-
316
-
317
-    /**
318
-     * given a shortcode name, will instantiate the shortcode and call it's run() method
319
-     *
320
-     * @param string $shortcode_class
321
-     * @param WP     $wp
322
-     */
323
-    public function initializeShortcode($shortcode_class = '', WP $wp = null)
324
-    {
325
-        // don't do anything if shortcode is already initialized
326
-        if (
327
-            empty($this->registry->shortcodes->{$shortcode_class})
328
-            || ! is_string($this->registry->shortcodes->{$shortcode_class})
329
-        ) {
330
-            return;
331
-        }
332
-        // let's pause to reflect on this...
333
-        $sc_reflector = new ReflectionClass(LegacyShortcodesManager::addShortcodeClassPrefix($shortcode_class));
334
-        // ensure that class is actually a shortcode
335
-        if (
336
-            defined('WP_DEBUG')
337
-            && WP_DEBUG === true
338
-            && ! $sc_reflector->isSubclassOf('EES_Shortcode')
339
-        ) {
340
-            EE_Error::add_error(
341
-                sprintf(
342
-                    esc_html__(
343
-                        'The requested %s shortcode is not of the class "EES_Shortcode". Please check your files.',
344
-                        'event_espresso'
345
-                    ),
346
-                    $shortcode_class
347
-                ),
348
-                __FILE__,
349
-                __FUNCTION__,
350
-                __LINE__
351
-            );
352
-            add_filter('FHEE_run_EE_the_content', '__return_true');
353
-            return;
354
-        }
355
-        global $wp;
356
-        // and pass the request object to the run method
357
-        $this->registry->shortcodes->{$shortcode_class} = $sc_reflector->newInstance();
358
-        // fire the shortcode class's run method, so that it can activate resources
359
-        $this->registry->shortcodes->{$shortcode_class}->run($wp);
360
-    }
361
-
362
-
363
-
364
-    /**
365
-     * get classname, remove EES_prefix, and convert to UPPERCASE
366
-     *
367
-     * @param string $class_name
368
-     * @return string
369
-     */
370
-    public static function generateShortcodeTagFromClassName($class_name)
371
-    {
372
-        return strtoupper(str_replace('EES_', '', $class_name));
373
-    }
374
-
375
-
376
-
377
-    /**
378
-     * add EES_prefix and Capitalize words
379
-     *
380
-     * @param string $tag
381
-     * @return string
382
-     */
383
-    public static function generateShortcodeClassNameFromTag($tag)
384
-    {
385
-        // order of operation runs from inside to out
386
-        // 5) maybe add prefix
387
-        return LegacyShortcodesManager::addShortcodeClassPrefix(
388
-        // 4) find spaces, replace with underscores
389
-            str_replace(
390
-                ' ',
391
-                '_',
392
-                // 3) capitalize first letter of each word
393
-                ucwords(
394
-                // 2) also change to lowercase so ucwords() will work
395
-                    strtolower(
396
-                    // 1) find underscores, replace with spaces so ucwords() will work
397
-                        str_replace(
398
-                            '_',
399
-                            ' ',
400
-                            $tag
401
-                        )
402
-                    )
403
-                )
404
-            )
405
-        );
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * maybe add EES_prefix
412
-     *
413
-     * @param string $class_name
414
-     * @return string
415
-     */
416
-    public static function addShortcodeClassPrefix($class_name)
417
-    {
418
-        return strpos($class_name, 'EES_') === 0 ? $class_name : 'EES_' . $class_name;
419
-    }
420
-
421
-
422
-
423
-    /**
424
-     * @return array
425
-     */
426
-    public function getEspressoShortcodeTags()
427
-    {
428
-        static $shortcode_tags = array();
429
-        if (empty($shortcode_tags)) {
430
-            $shortcode_tags = array_keys((array)$this->registry->shortcodes);
431
-        }
432
-        return $shortcode_tags;
433
-    }
434
-
435
-
436
-
437
-    /**
438
-     * @param string $content
439
-     * @return string
440
-     */
441
-    public function doShortcode($content)
442
-    {
443
-        foreach ($this->getEspressoShortcodeTags() as $shortcode_tag) {
444
-            if (strpos($content, $shortcode_tag) !== false) {
445
-                $shortcode_class = LegacyShortcodesManager::generateShortcodeClassNameFromTag($shortcode_tag);
446
-                $this->initializeShortcode($shortcode_class);
447
-            }
448
-        }
449
-        return do_shortcode($content);
450
-    }
28
+	/**
29
+	 * @var EE_Registry $registry
30
+	 */
31
+	private $registry;
32
+
33
+
34
+
35
+
36
+	/**
37
+	 * LegacyShortcodesManager constructor.
38
+	 *
39
+	 * @param \EE_Registry $registry
40
+	 */
41
+	public function __construct(EE_Registry $registry)
42
+	{
43
+		$this->registry = $registry;
44
+	}
45
+
46
+
47
+
48
+	/**
49
+	 * @return EE_Registry
50
+	 */
51
+	public function registry()
52
+	{
53
+		return $this->registry;
54
+	}
55
+
56
+
57
+
58
+	/**
59
+	 * registerShortcodes
60
+	 *
61
+	 * @return void
62
+	 */
63
+	public function registerShortcodes()
64
+	{
65
+		$this->registry->shortcodes = $this->getShortcodes();
66
+	}
67
+
68
+
69
+
70
+	/**
71
+	 * getShortcodes
72
+	 *
73
+	 * @return array
74
+	 */
75
+	public function getShortcodes()
76
+	{
77
+		// previously this method would glob the shortcodes directory
78
+		// then filter that list of shortcodes to register,
79
+		// but now we are going to just supply an empty array.
80
+		// this allows any shortcodes that have not yet been converted to the new system
81
+		// to still get loaded and processed, albeit using the same legacy logic as before
82
+		$shortcodes_to_register = apply_filters(
83
+			'FHEE__EE_Config__register_shortcodes__shortcodes_to_register',
84
+			array()
85
+		);
86
+		if ( ! empty($shortcodes_to_register)) {
87
+			// cycle thru shortcode folders
88
+			foreach ($shortcodes_to_register as $shortcode_path) {
89
+				// add to list of installed shortcode modules
90
+				$this->registerShortcode($shortcode_path);
91
+			}
92
+		}
93
+		// filter list of installed modules
94
+		return apply_filters(
95
+			'FHEE__EE_Config___register_shortcodes__installed_shortcodes',
96
+			! empty($this->registry->shortcodes)
97
+				? $this->registry->shortcodes
98
+				: array()
99
+		);
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 *    register_shortcode - makes core aware of this shortcode
106
+	 *
107
+	 * @access    public
108
+	 * @param    string $shortcode_path - full path up to and including shortcode folder
109
+	 * @return    bool
110
+	 */
111
+	public function registerShortcode($shortcode_path = null)
112
+	{
113
+		do_action('AHEE__EE_Config__register_shortcode__begin', $shortcode_path);
114
+		$shortcode_ext = '.shortcode.php';
115
+		// make all separators match
116
+		$shortcode_path = str_replace(array('\\', '/'), DS, $shortcode_path);
117
+		// does the file path INCLUDE the actual file name as part of the path ?
118
+		if (strpos($shortcode_path, $shortcode_ext) !== false) {
119
+			// grab shortcode file name from directory name and break apart at dots
120
+			$shortcode_file = explode('.', basename($shortcode_path));
121
+			// take first segment from file name pieces and remove class prefix if it exists
122
+			$shortcode = strpos($shortcode_file[0], 'EES_') === 0
123
+				? substr($shortcode_file[0], 4)
124
+				: $shortcode_file[0];
125
+			// sanitize shortcode directory name
126
+			$shortcode = sanitize_key($shortcode);
127
+			// now we need to rebuild the shortcode path
128
+			$shortcode_path = explode(DS, $shortcode_path);
129
+			// remove last segment
130
+			array_pop($shortcode_path);
131
+			// glue it back together
132
+			$shortcode_path = implode(DS, $shortcode_path) . DS;
133
+		} else {
134
+			// we need to generate the filename based off of the folder name
135
+			// grab and sanitize shortcode directory name
136
+			$shortcode = sanitize_key(basename($shortcode_path));
137
+			$shortcode_path = rtrim($shortcode_path, DS) . DS;
138
+		}
139
+		// create classname from shortcode directory or file name
140
+		$shortcode = str_replace(' ', '_', ucwords(str_replace('_', ' ', $shortcode)));
141
+		// add class prefix
142
+		$shortcode_class = 'EES_' . $shortcode;
143
+		// does the shortcode exist ?
144
+		if ( ! is_readable($shortcode_path . DS . $shortcode_class . $shortcode_ext)) {
145
+			$msg = sprintf(
146
+				esc_html__(
147
+					'The requested %s shortcode file could not be found or is not readable due to file permissions. It should be in %s',
148
+					'event_espresso'
149
+				),
150
+				$shortcode_class,
151
+				$shortcode_path . DS . $shortcode_class . $shortcode_ext
152
+			);
153
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
154
+			return false;
155
+		}
156
+		// load the shortcode class file
157
+		require_once($shortcode_path . $shortcode_class . $shortcode_ext);
158
+		// verify that class exists
159
+		if ( ! class_exists($shortcode_class)) {
160
+			$msg = sprintf(
161
+				esc_html__('The requested %s shortcode class does not exist.', 'event_espresso'),
162
+				$shortcode_class
163
+			);
164
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
165
+			return false;
166
+		}
167
+		$shortcode = strtoupper($shortcode);
168
+		// add to array of registered shortcodes
169
+		$this->registry->shortcodes->{$shortcode} = $shortcode_path . $shortcode_class . $shortcode_ext;
170
+		return true;
171
+	}
172
+
173
+
174
+
175
+	/**
176
+	 *    _initialize_shortcodes
177
+	 *    allow shortcodes to set hooks for the rest of the system
178
+	 *
179
+	 * @access private
180
+	 * @return void
181
+	 */
182
+	public function addShortcodes()
183
+	{
184
+		// cycle thru shortcode folders
185
+		foreach ($this->registry->shortcodes as $shortcode => $shortcode_path) {
186
+			// add class prefix
187
+			$shortcode_class = 'EES_' . $shortcode;
188
+			// fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
189
+			// which set hooks ?
190
+			if (is_admin()) {
191
+				// fire immediately
192
+				call_user_func(array($shortcode_class, 'set_hooks_admin'));
193
+			} else {
194
+				// delay until other systems are online
195
+				add_action(
196
+					'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
197
+					array($shortcode_class, 'set_hooks')
198
+				);
199
+				// convert classname to UPPERCASE and create WP shortcode.
200
+				$shortcode_tag = strtoupper($shortcode);
201
+				// but first check if the shortcode has already
202
+				// been added before assigning 'fallback_shortcode_processor'
203
+				if ( ! shortcode_exists($shortcode_tag)) {
204
+					// NOTE: this shortcode declaration will get overridden if the shortcode
205
+					// is successfully detected in the post content in initializeShortcode()
206
+					add_shortcode($shortcode_tag, array($shortcode_class, 'fallback_shortcode_processor'));
207
+				}
208
+			}
209
+		}
210
+	}
211
+
212
+
213
+
214
+	/**
215
+	 * callback for the WP "get_header" hook point
216
+	 * checks posts for EE shortcodes, and initializes them,
217
+	 * then toggles filter switch that loads core default assets
218
+	 *
219
+	 * @param \WP_Query $wp_query
220
+	 * @return void
221
+	 */
222
+	public function initializeShortcodes(WP_Query $wp_query)
223
+	{
224
+		if (empty($this->registry->shortcodes) || ! $wp_query->is_main_query() || is_admin()) {
225
+			return;
226
+		}
227
+		global $wp;
228
+		/** @var EE_Front_controller $Front_Controller */
229
+		$Front_Controller = $this->registry->load_core('Front_Controller', array(), false);
230
+		do_action('AHEE__EE_Front_Controller__initialize_shortcodes__begin', $wp, $Front_Controller);
231
+		$Front_Controller->Request_Handler()->set_request_vars();
232
+		// grab post_name from request
233
+		$current_post = apply_filters(
234
+			'FHEE__EE_Front_Controller__initialize_shortcodes__current_post_name',
235
+			$Front_Controller->Request_Handler()->get('post_name')
236
+		);
237
+		$show_on_front = get_option('show_on_front');
238
+		// if it's not set, then check if frontpage is blog
239
+		if (empty($current_post)) {
240
+			// yup.. this is the posts page, prepare to load all shortcode modules
241
+			$current_post = 'posts';
242
+			// unless..
243
+			if ($show_on_front === 'page') {
244
+				// some other page is set as the homepage
245
+				$page_on_front = get_option('page_on_front');
246
+				if ($page_on_front) {
247
+					// k now we need to find the post_name for this page
248
+					global $wpdb;
249
+					$page_on_front = $wpdb->get_var(
250
+						$wpdb->prepare(
251
+							"SELECT post_name from {$wpdb->posts} WHERE post_type='page' AND post_status='publish' AND ID=%d",
252
+							$page_on_front
253
+						)
254
+					);
255
+					// set the current post slug to what it actually is
256
+					$current_post = $page_on_front ? $page_on_front : $current_post;
257
+				}
258
+			}
259
+		}
260
+		// in case $current_post is hierarchical like: /parent-page/current-page
261
+		$current_post = basename($current_post);
262
+		if (
263
+			// is current page/post the "blog" page ?
264
+			$current_post === EE_Config::get_page_for_posts()
265
+			// or are we on a category page?
266
+			|| (
267
+				is_array(term_exists($current_post, 'category'))
268
+				|| array_key_exists('category_name', $wp->query_vars)
269
+			)
270
+		) {
271
+			// initialize all legacy shortcodes
272
+			$load_assets = $this->parseContentForShortcodes('', true);
273
+		} else {
274
+			global $wpdb;
275
+			$post_content = $wpdb->get_var(
276
+				$wpdb->prepare(
277
+					"SELECT post_content from {$wpdb->posts} WHERE post_status='publish' AND post_name=%s",
278
+					$current_post
279
+				)
280
+			);
281
+			$load_assets = $this->parseContentForShortcodes($post_content);
282
+		}
283
+		if ($load_assets) {
284
+			$this->registry->REQ->set_espresso_page(true);
285
+			add_filter('FHEE_load_css', '__return_true');
286
+			add_filter('FHEE_load_js', '__return_true');
287
+		}
288
+		do_action('AHEE__EE_Front_Controller__initialize_shortcodes__end', $Front_Controller);
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * checks supplied content against list of legacy shortcodes,
295
+	 * then initializes any found shortcodes, and returns true.
296
+	 * returns false if no shortcodes found.
297
+	 *
298
+	 * @param string $content
299
+	 * @param bool   $load_all if true, then ALL active legacy shortcodes will be initialized
300
+	 * @return bool
301
+	 */
302
+	public function parseContentForShortcodes($content = '', $load_all = false)
303
+	{
304
+		$has_shortcode = false;
305
+		foreach ($this->registry->shortcodes as $shortcode_class => $shortcode) {
306
+			if ($load_all || has_shortcode($content, $shortcode_class) ) {
307
+				// load up the shortcode
308
+				$this->initializeShortcode($shortcode_class);
309
+				$has_shortcode = true;
310
+			}
311
+		}
312
+		return $has_shortcode;
313
+	}
314
+
315
+
316
+
317
+	/**
318
+	 * given a shortcode name, will instantiate the shortcode and call it's run() method
319
+	 *
320
+	 * @param string $shortcode_class
321
+	 * @param WP     $wp
322
+	 */
323
+	public function initializeShortcode($shortcode_class = '', WP $wp = null)
324
+	{
325
+		// don't do anything if shortcode is already initialized
326
+		if (
327
+			empty($this->registry->shortcodes->{$shortcode_class})
328
+			|| ! is_string($this->registry->shortcodes->{$shortcode_class})
329
+		) {
330
+			return;
331
+		}
332
+		// let's pause to reflect on this...
333
+		$sc_reflector = new ReflectionClass(LegacyShortcodesManager::addShortcodeClassPrefix($shortcode_class));
334
+		// ensure that class is actually a shortcode
335
+		if (
336
+			defined('WP_DEBUG')
337
+			&& WP_DEBUG === true
338
+			&& ! $sc_reflector->isSubclassOf('EES_Shortcode')
339
+		) {
340
+			EE_Error::add_error(
341
+				sprintf(
342
+					esc_html__(
343
+						'The requested %s shortcode is not of the class "EES_Shortcode". Please check your files.',
344
+						'event_espresso'
345
+					),
346
+					$shortcode_class
347
+				),
348
+				__FILE__,
349
+				__FUNCTION__,
350
+				__LINE__
351
+			);
352
+			add_filter('FHEE_run_EE_the_content', '__return_true');
353
+			return;
354
+		}
355
+		global $wp;
356
+		// and pass the request object to the run method
357
+		$this->registry->shortcodes->{$shortcode_class} = $sc_reflector->newInstance();
358
+		// fire the shortcode class's run method, so that it can activate resources
359
+		$this->registry->shortcodes->{$shortcode_class}->run($wp);
360
+	}
361
+
362
+
363
+
364
+	/**
365
+	 * get classname, remove EES_prefix, and convert to UPPERCASE
366
+	 *
367
+	 * @param string $class_name
368
+	 * @return string
369
+	 */
370
+	public static function generateShortcodeTagFromClassName($class_name)
371
+	{
372
+		return strtoupper(str_replace('EES_', '', $class_name));
373
+	}
374
+
375
+
376
+
377
+	/**
378
+	 * add EES_prefix and Capitalize words
379
+	 *
380
+	 * @param string $tag
381
+	 * @return string
382
+	 */
383
+	public static function generateShortcodeClassNameFromTag($tag)
384
+	{
385
+		// order of operation runs from inside to out
386
+		// 5) maybe add prefix
387
+		return LegacyShortcodesManager::addShortcodeClassPrefix(
388
+		// 4) find spaces, replace with underscores
389
+			str_replace(
390
+				' ',
391
+				'_',
392
+				// 3) capitalize first letter of each word
393
+				ucwords(
394
+				// 2) also change to lowercase so ucwords() will work
395
+					strtolower(
396
+					// 1) find underscores, replace with spaces so ucwords() will work
397
+						str_replace(
398
+							'_',
399
+							' ',
400
+							$tag
401
+						)
402
+					)
403
+				)
404
+			)
405
+		);
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * maybe add EES_prefix
412
+	 *
413
+	 * @param string $class_name
414
+	 * @return string
415
+	 */
416
+	public static function addShortcodeClassPrefix($class_name)
417
+	{
418
+		return strpos($class_name, 'EES_') === 0 ? $class_name : 'EES_' . $class_name;
419
+	}
420
+
421
+
422
+
423
+	/**
424
+	 * @return array
425
+	 */
426
+	public function getEspressoShortcodeTags()
427
+	{
428
+		static $shortcode_tags = array();
429
+		if (empty($shortcode_tags)) {
430
+			$shortcode_tags = array_keys((array)$this->registry->shortcodes);
431
+		}
432
+		return $shortcode_tags;
433
+	}
434
+
435
+
436
+
437
+	/**
438
+	 * @param string $content
439
+	 * @return string
440
+	 */
441
+	public function doShortcode($content)
442
+	{
443
+		foreach ($this->getEspressoShortcodeTags() as $shortcode_tag) {
444
+			if (strpos($content, $shortcode_tag) !== false) {
445
+				$shortcode_class = LegacyShortcodesManager::generateShortcodeClassNameFromTag($shortcode_tag);
446
+				$this->initializeShortcode($shortcode_class);
447
+			}
448
+		}
449
+		return do_shortcode($content);
450
+	}
451 451
 
452 452
 
453 453
 
Please login to merge, or discard this patch.
core/EES_Shortcode.shortcode.php 2 patches
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -20,17 +20,17 @@  discard block
 block discarded – undo
20 20
 
21 21
 
22 22
 
23
-    /**
24
-     * class constructor - should ONLY be instantiated by EE_Front_Controller
25
-     */
26
-    final public function __construct()
27
-    {
28
-        $shortcode = LegacyShortcodesManager::generateShortcodeTagFromClassName(get_class($this));
29
-        // assign shortcode to the preferred callback, which overwrites the "fallback shortcode processor" assigned earlier
30
-        add_shortcode($shortcode, array($this, 'process_shortcode'));
31
-        // make sure system knows this is an EE page
32
-        EE_Registry::instance()->REQ->set_espresso_page(true);
33
-    }
23
+	/**
24
+	 * class constructor - should ONLY be instantiated by EE_Front_Controller
25
+	 */
26
+	final public function __construct()
27
+	{
28
+		$shortcode = LegacyShortcodesManager::generateShortcodeTagFromClassName(get_class($this));
29
+		// assign shortcode to the preferred callback, which overwrites the "fallback shortcode processor" assigned earlier
30
+		add_shortcode($shortcode, array($this, 'process_shortcode'));
31
+		// make sure system knows this is an EE page
32
+		EE_Registry::instance()->REQ->set_espresso_page(true);
33
+	}
34 34
 
35 35
 
36 36
 
@@ -77,11 +77,11 @@  discard block
 block discarded – undo
77 77
 		}
78 78
 		$shortcode = str_replace( 'EES_', '', strtoupper( $shortcode_class ));
79 79
 		$shortcode_obj = isset( EE_Registry::instance()->shortcodes->{$shortcode} )
80
-            ? EE_Registry::instance()->shortcodes->{$shortcode}
81
-            : null;
80
+			? EE_Registry::instance()->shortcodes->{$shortcode}
81
+			: null;
82 82
 		return $shortcode_obj instanceof $shortcode_class || $shortcode_class === 'self'
83
-            ? $shortcode_obj
84
-            : new $shortcode_class();
83
+			? $shortcode_obj
84
+			: new $shortcode_class();
85 85
 	}
86 86
 
87 87
 
@@ -135,59 +135,59 @@  discard block
 block discarded – undo
135 135
 
136 136
 
137 137
 
138
-    /**
139
-     * Performs basic sanitization on shortcode attributes
140
-     * Since incoming attributes from the shortcode usage in the WP editor will all be strings,
141
-     * most attributes will by default be sanitized using the sanitize_text_field() function.
142
-     * This can be overridden by supplying an array for the $custom_sanitization param,
143
-     * where keys match keys in your attributes array,
144
-     * and values represent the sanitization function you wish to be applied to that attribute.
145
-     * So for example, if you had an integer attribute named "event_id"
146
-     * that you wanted to be sanitized using absint(),
147
-     * then you would pass the following for your $custom_sanitization array:
148
-     *      array('event_id' => 'absint')
149
-     * all other attributes would be sanitized using the defaults in the switch statement below
150
-     *
151
-     * @param array $attributes
152
-     * @param array $custom_sanitization
153
-     * @return array
154
-     */
155
-    public static function sanitize_attributes(array $attributes, $custom_sanitization = array())
156
-    {
157
-        foreach ($attributes as $key => $value) {
158
-            // is a custom sanitization callback specified ?
159
-            if ( isset($custom_sanitization[$key])) {
160
-                $callback = $custom_sanitization[$key];
161
-                if ($callback === 'skip_sanitization') {
162
-                    $attributes[$key] = $value;
163
-                    continue;
164
-                } else if (function_exists($callback)){
165
-                    $attributes[$key] = $callback($value);
166
-                    continue;
167
-                }
168
-            }
169
-            switch (true) {
170
-                case $value === null :
171
-                case is_int($value) :
172
-                case is_float($value) :
173
-                    // typical booleans
174
-                case in_array($value, array(true, 'true', '1', 'on', 'yes', false, 'false', '0', 'off', 'no'), true) :
175
-                    $attributes[$key] = $value;
176
-                    break;
177
-                case is_string($value) :
178
-                    $attributes[$key] = sanitize_text_field($value);
179
-                    break;
180
-                case is_array($value) :
181
-                    $attributes[$key] = \EES_Shortcode::sanitize_attributes($value);
182
-                    break;
183
-                default :
184
-                    // only remaining data types are Object and Resource
185
-                    // which are not allowed as shortcode attributes
186
-                    $attributes[$key] = null;
187
-                    break;
188
-            }
189
-        }
190
-        return $attributes;
138
+	/**
139
+	 * Performs basic sanitization on shortcode attributes
140
+	 * Since incoming attributes from the shortcode usage in the WP editor will all be strings,
141
+	 * most attributes will by default be sanitized using the sanitize_text_field() function.
142
+	 * This can be overridden by supplying an array for the $custom_sanitization param,
143
+	 * where keys match keys in your attributes array,
144
+	 * and values represent the sanitization function you wish to be applied to that attribute.
145
+	 * So for example, if you had an integer attribute named "event_id"
146
+	 * that you wanted to be sanitized using absint(),
147
+	 * then you would pass the following for your $custom_sanitization array:
148
+	 *      array('event_id' => 'absint')
149
+	 * all other attributes would be sanitized using the defaults in the switch statement below
150
+	 *
151
+	 * @param array $attributes
152
+	 * @param array $custom_sanitization
153
+	 * @return array
154
+	 */
155
+	public static function sanitize_attributes(array $attributes, $custom_sanitization = array())
156
+	{
157
+		foreach ($attributes as $key => $value) {
158
+			// is a custom sanitization callback specified ?
159
+			if ( isset($custom_sanitization[$key])) {
160
+				$callback = $custom_sanitization[$key];
161
+				if ($callback === 'skip_sanitization') {
162
+					$attributes[$key] = $value;
163
+					continue;
164
+				} else if (function_exists($callback)){
165
+					$attributes[$key] = $callback($value);
166
+					continue;
167
+				}
168
+			}
169
+			switch (true) {
170
+				case $value === null :
171
+				case is_int($value) :
172
+				case is_float($value) :
173
+					// typical booleans
174
+				case in_array($value, array(true, 'true', '1', 'on', 'yes', false, 'false', '0', 'off', 'no'), true) :
175
+					$attributes[$key] = $value;
176
+					break;
177
+				case is_string($value) :
178
+					$attributes[$key] = sanitize_text_field($value);
179
+					break;
180
+				case is_array($value) :
181
+					$attributes[$key] = \EES_Shortcode::sanitize_attributes($value);
182
+					break;
183
+				default :
184
+					// only remaining data types are Object and Resource
185
+					// which are not allowed as shortcode attributes
186
+					$attributes[$key] = null;
187
+					break;
188
+			}
189
+		}
190
+		return $attributes;
191 191
 	}
192 192
 
193 193
 
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
 	 * @param WP $WP
48 48
 	 * @return    void
49 49
 	 */
50
-	public abstract function run( WP $WP );
50
+	public abstract function run(WP $WP);
51 51
 
52 52
 
53 53
 
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 	 *  @param		array 	$attributes
60 60
 	 *  @return 	mixed
61 61
 	 */
62
-	public abstract function process_shortcode( $attributes = array() );
62
+	public abstract function process_shortcode($attributes = array());
63 63
 
64 64
 
65 65
 
@@ -70,13 +70,13 @@  discard block
 block discarded – undo
70 70
 	 * @param 	string $shortcode_class
71 71
 	 * @return 	\EES_Shortcode
72 72
 	 */
73
-	final public static function instance( $shortcode_class = null ) {
74
-		$shortcode_class = ! empty( $shortcode_class ) ? $shortcode_class : get_called_class();
75
-		if ( $shortcode_class === 'EES_Shortcode' || empty( $shortcode_class )) {
73
+	final public static function instance($shortcode_class = null) {
74
+		$shortcode_class = ! empty($shortcode_class) ? $shortcode_class : get_called_class();
75
+		if ($shortcode_class === 'EES_Shortcode' || empty($shortcode_class)) {
76 76
 			return null;
77 77
 		}
78
-		$shortcode = str_replace( 'EES_', '', strtoupper( $shortcode_class ));
79
-		$shortcode_obj = isset( EE_Registry::instance()->shortcodes->{$shortcode} )
78
+		$shortcode = str_replace('EES_', '', strtoupper($shortcode_class));
79
+		$shortcode_obj = isset(EE_Registry::instance()->shortcodes->{$shortcode} )
80 80
             ? EE_Registry::instance()->shortcodes->{$shortcode}
81 81
             : null;
82 82
 		return $shortcode_obj instanceof $shortcode_class || $shortcode_class === 'self'
@@ -95,23 +95,23 @@  discard block
 block discarded – undo
95 95
 	 * @param 	$attributes
96 96
 	 * @return 	mixed
97 97
 	 */
98
-	final public static function fallback_shortcode_processor( $attributes ) {
99
-		if ( EE_Maintenance_Mode::disable_frontend_for_maintenance() ) {
98
+	final public static function fallback_shortcode_processor($attributes) {
99
+		if (EE_Maintenance_Mode::disable_frontend_for_maintenance()) {
100 100
 			return null;
101 101
 		}
102 102
 		// what shortcode was actually parsed ?
103 103
 		$shortcode_class = get_called_class();
104 104
 		// notify rest of system that fallback processor was triggered
105
-		add_filter( 'FHEE__fallback_shortcode_processor__' . $shortcode_class, '__return_true' );
105
+		add_filter('FHEE__fallback_shortcode_processor__'.$shortcode_class, '__return_true');
106 106
 		// get instance of actual shortcode
107
-		$shortcode_obj = self::instance( $shortcode_class );
107
+		$shortcode_obj = self::instance($shortcode_class);
108 108
 		// verify class
109
-		if ( $shortcode_obj instanceof EES_Shortcode ) {
109
+		if ($shortcode_obj instanceof EES_Shortcode) {
110 110
 			global $wp;
111
-			$shortcode_obj->run( $wp );
111
+			$shortcode_obj->run($wp);
112 112
 			// set attributes and run the shortcode
113
-			$shortcode_obj->_attributes = (array)$attributes;
114
-			return $shortcode_obj->process_shortcode( $shortcode_obj->_attributes );
113
+			$shortcode_obj->_attributes = (array) $attributes;
114
+			return $shortcode_obj->process_shortcode($shortcode_obj->_attributes);
115 115
 		} else {
116 116
 			return null;
117 117
 		}
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 	 * @param 	$attributes
128 128
 	 * @return 	string
129 129
 	 */
130
-	final public static function invalid_shortcode_processor( $attributes ) {
130
+	final public static function invalid_shortcode_processor($attributes) {
131 131
 		return '';
132 132
 	}
133 133
 
@@ -156,12 +156,12 @@  discard block
 block discarded – undo
156 156
     {
157 157
         foreach ($attributes as $key => $value) {
158 158
             // is a custom sanitization callback specified ?
159
-            if ( isset($custom_sanitization[$key])) {
159
+            if (isset($custom_sanitization[$key])) {
160 160
                 $callback = $custom_sanitization[$key];
161 161
                 if ($callback === 'skip_sanitization') {
162 162
                     $attributes[$key] = $value;
163 163
                     continue;
164
-                } else if (function_exists($callback)){
164
+                } else if (function_exists($callback)) {
165 165
                     $attributes[$key] = $callback($value);
166 166
                     continue;
167 167
                 }
Please login to merge, or discard this patch.
core/domain/entities/shortcodes/EspressoEvents.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -108,7 +108,7 @@
 block discarded – undo
108 108
     private function getAttributes(array $attributes)
109 109
     {
110 110
         return array_merge(
111
-            (array)apply_filters(
111
+            (array) apply_filters(
112 112
                 'EES_Espresso_Events__process_shortcode__default_espresso_events_shortcode_atts',
113 113
                 array(
114 114
                     'title'         => '',
Please login to merge, or discard this patch.
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -34,139 +34,139 @@
 block discarded – undo
34 34
 
35 35
 
36 36
 
37
-    /**
38
-     * the actual shortcode tag that gets registered with WordPress
39
-     *
40
-     * @return string
41
-     */
42
-    public function getTag()
43
-    {
44
-        return 'ESPRESSO_EVENTS';
45
-    }
46
-
47
-
48
-
49
-    /**
50
-     * the time in seconds to cache the results of the processShortcode() method
51
-     * 0 means the processShortcode() results will NOT be cached at all
52
-     *
53
-     * @return int
54
-     */
55
-    public function cacheExpiration()
56
-    {
57
-        return 0;
58
-    }
59
-
60
-
61
-
62
-    /**
63
-     * a place for adding any initialization code that needs to run prior to wp_header().
64
-     * this may be required for shortcodes that utilize a corresponding module,
65
-     * and need to enqueue assets for that module
66
-     *
67
-     * @return void
68
-     */
69
-    public function initializeShortcode()
70
-    {
71
-        EED_Events_Archive::instance()->event_list();
72
-        $this->shortcodeHasBeenInitialized();
73
-    }
74
-
75
-
76
-
77
-    /**
78
-     * callback that runs when the shortcode is encountered in post content.
79
-     * IMPORTANT !!!
80
-     * remember that shortcode content should be RETURNED and NOT echoed out
81
-     *
82
-     * @param array $attributes
83
-     * @return string
84
-     */
85
-    public function processShortcode($attributes = array())
86
-    {
87
-        // grab attributes and merge with defaults
88
-        $attributes = $this->getAttributes($attributes);
89
-        // make sure we use the_excerpt()
90
-        add_filter('FHEE__EES_Espresso_Events__process_shortcode__true', '__return_true');
91
-        // apply query filters
92
-        add_filter('FHEE__EEH_Event_Query__apply_query_filters', '__return_true');
93
-        // run the query
94
-        global $wp_query;
95
-        // yes we have to overwrite the main wp query, but it's ok...
96
-        // we're going to reset it again below, so everything will be Hunky Dory (amazing album)
97
-        $wp_query = new EventListQuery($attributes);
98
-        // check what template is loaded and load filters accordingly
99
-        EED_Events_Archive::instance()->template_include('loop-espresso_events.php');
100
-        // load our template
101
-        $event_list = EEH_Template::locate_template(
102
-            'loop-espresso_events.php',
103
-            array(),
104
-            true,
105
-            true
106
-        );
107
-        // now reset the query and post data
108
-        wp_reset_query();
109
-        wp_reset_postdata();
110
-        EED_Events_Archive::remove_all_events_archive_filters();
111
-        // remove query filters
112
-        remove_filter('FHEE__EEH_Event_Query__apply_query_filters', '__return_true');
113
-        // pull our content from the output buffer and return it
114
-        return $event_list;
115
-    }
116
-
117
-
118
-
119
-    /**
120
-     * merge incoming attributes with filtered defaults
121
-     *
122
-     * @param array $attributes
123
-     * @return array
124
-     */
125
-    private function getAttributes(array $attributes)
126
-    {
127
-        return array_merge(
128
-            (array)apply_filters(
129
-                'EES_Espresso_Events__process_shortcode__default_espresso_events_shortcode_atts',
130
-                array(
131
-                    'title'         => '',
132
-                    'limit'         => 10,
133
-                    'css_class'     => '',
134
-                    'show_expired'  => false,
135
-                    'month'         => '',
136
-                    'category_slug' => '',
137
-                    'order_by'      => 'start_date',
138
-                    'sort'          => 'ASC',
139
-                    'show_title'    => true,
140
-                )
141
-            ),
142
-            $attributes
143
-        );
144
-    }
145
-
146
-
147
-
148
-    /**
149
-     * array for defining custom attribute sanitization callbacks,
150
-     * where keys match keys in your attributes array,
151
-     * and values represent the sanitization function you wish to be applied to that attribute.
152
-     * So for example, if you had an integer attribute named "event_id"
153
-     * that you wanted to be sanitized using absint(),
154
-     * then you would pass the following for your $custom_sanitization array:
155
-     *      array('event_id' => 'absint')
156
-     *
157
-     * @return array
158
-     */
159
-    protected function customAttributeSanitizationMap()
160
-    {
161
-        // the following get sanitized/whitelisted in EEH_Event_Query
162
-        return array(
163
-            'category_slug' => 'skip_sanitization',
164
-            'show_expired'  => 'skip_sanitization',
165
-            'order_by'      => 'skip_sanitization',
166
-            'month'         => 'skip_sanitization',
167
-            'sort'          => 'skip_sanitization',
168
-        );
169
-    }
37
+	/**
38
+	 * the actual shortcode tag that gets registered with WordPress
39
+	 *
40
+	 * @return string
41
+	 */
42
+	public function getTag()
43
+	{
44
+		return 'ESPRESSO_EVENTS';
45
+	}
46
+
47
+
48
+
49
+	/**
50
+	 * the time in seconds to cache the results of the processShortcode() method
51
+	 * 0 means the processShortcode() results will NOT be cached at all
52
+	 *
53
+	 * @return int
54
+	 */
55
+	public function cacheExpiration()
56
+	{
57
+		return 0;
58
+	}
59
+
60
+
61
+
62
+	/**
63
+	 * a place for adding any initialization code that needs to run prior to wp_header().
64
+	 * this may be required for shortcodes that utilize a corresponding module,
65
+	 * and need to enqueue assets for that module
66
+	 *
67
+	 * @return void
68
+	 */
69
+	public function initializeShortcode()
70
+	{
71
+		EED_Events_Archive::instance()->event_list();
72
+		$this->shortcodeHasBeenInitialized();
73
+	}
74
+
75
+
76
+
77
+	/**
78
+	 * callback that runs when the shortcode is encountered in post content.
79
+	 * IMPORTANT !!!
80
+	 * remember that shortcode content should be RETURNED and NOT echoed out
81
+	 *
82
+	 * @param array $attributes
83
+	 * @return string
84
+	 */
85
+	public function processShortcode($attributes = array())
86
+	{
87
+		// grab attributes and merge with defaults
88
+		$attributes = $this->getAttributes($attributes);
89
+		// make sure we use the_excerpt()
90
+		add_filter('FHEE__EES_Espresso_Events__process_shortcode__true', '__return_true');
91
+		// apply query filters
92
+		add_filter('FHEE__EEH_Event_Query__apply_query_filters', '__return_true');
93
+		// run the query
94
+		global $wp_query;
95
+		// yes we have to overwrite the main wp query, but it's ok...
96
+		// we're going to reset it again below, so everything will be Hunky Dory (amazing album)
97
+		$wp_query = new EventListQuery($attributes);
98
+		// check what template is loaded and load filters accordingly
99
+		EED_Events_Archive::instance()->template_include('loop-espresso_events.php');
100
+		// load our template
101
+		$event_list = EEH_Template::locate_template(
102
+			'loop-espresso_events.php',
103
+			array(),
104
+			true,
105
+			true
106
+		);
107
+		// now reset the query and post data
108
+		wp_reset_query();
109
+		wp_reset_postdata();
110
+		EED_Events_Archive::remove_all_events_archive_filters();
111
+		// remove query filters
112
+		remove_filter('FHEE__EEH_Event_Query__apply_query_filters', '__return_true');
113
+		// pull our content from the output buffer and return it
114
+		return $event_list;
115
+	}
116
+
117
+
118
+
119
+	/**
120
+	 * merge incoming attributes with filtered defaults
121
+	 *
122
+	 * @param array $attributes
123
+	 * @return array
124
+	 */
125
+	private function getAttributes(array $attributes)
126
+	{
127
+		return array_merge(
128
+			(array)apply_filters(
129
+				'EES_Espresso_Events__process_shortcode__default_espresso_events_shortcode_atts',
130
+				array(
131
+					'title'         => '',
132
+					'limit'         => 10,
133
+					'css_class'     => '',
134
+					'show_expired'  => false,
135
+					'month'         => '',
136
+					'category_slug' => '',
137
+					'order_by'      => 'start_date',
138
+					'sort'          => 'ASC',
139
+					'show_title'    => true,
140
+				)
141
+			),
142
+			$attributes
143
+		);
144
+	}
145
+
146
+
147
+
148
+	/**
149
+	 * array for defining custom attribute sanitization callbacks,
150
+	 * where keys match keys in your attributes array,
151
+	 * and values represent the sanitization function you wish to be applied to that attribute.
152
+	 * So for example, if you had an integer attribute named "event_id"
153
+	 * that you wanted to be sanitized using absint(),
154
+	 * then you would pass the following for your $custom_sanitization array:
155
+	 *      array('event_id' => 'absint')
156
+	 *
157
+	 * @return array
158
+	 */
159
+	protected function customAttributeSanitizationMap()
160
+	{
161
+		// the following get sanitized/whitelisted in EEH_Event_Query
162
+		return array(
163
+			'category_slug' => 'skip_sanitization',
164
+			'show_expired'  => 'skip_sanitization',
165
+			'order_by'      => 'skip_sanitization',
166
+			'month'         => 'skip_sanitization',
167
+			'sort'          => 'skip_sanitization',
168
+		);
169
+	}
170 170
 
171 171
 
172 172
 
Please login to merge, or discard this patch.
core/EE_Session.core.php 3 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 	  * set session data
434 434
 	  * @access 	public
435 435
 	  * @param 	array $data
436
-	  * @return 	TRUE on success, FALSE on fail
436
+	  * @return 	boolean on success, FALSE on fail
437 437
 	  */
438 438
 	public function set_session_data( $data ) {
439 439
 
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 	 /**
462 462
 	  * @initiate session
463 463
 	  * @access   private
464
-	  * @return TRUE on success, FALSE on fail
464
+	  * @return boolean on success, FALSE on fail
465 465
 	  * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
466 466
 	  * @throws \EE_Error
467 467
 	  */
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
       * @update session data  prior to saving to the db
682 682
       * @access public
683 683
       * @param bool $new_session
684
-      * @return TRUE on success, FALSE on fail
684
+      * @return boolean on success, FALSE on fail
685 685
       * @throws \EE_Error
686 686
       */
687 687
 	public function update( $new_session = FALSE ) {
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
 	  * _save_session_to_db
788 788
 	  *
789 789
 	  * @access public
790
-	  * @return string
790
+	  * @return boolean
791 791
 	  * @throws \EE_Error
792 792
 	  */
793 793
 	private function _save_session_to_db() {
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
 	  * @access public
960 960
 	  * @param array $data_to_reset
961 961
 	  * @param bool  $show_all_notices
962
-	  * @return TRUE on success, FALSE on fail
962
+	  * @return boolean on success, FALSE on fail
963 963
 	  */
964 964
 	public function reset_data( $data_to_reset = array(), $show_all_notices = FALSE ) {
965 965
 		// if $data_to_reset is not in an array, then put it in one
Please login to merge, or discard this patch.
Indentation   +293 added lines, -293 removed lines patch added patch discarded remove patch
@@ -22,19 +22,19 @@  discard block
 block discarded – undo
22 22
 	  */
23 23
 	 private static $_instance;
24 24
 
25
-     /**
26
-      * @var CacheStorageInterface $cache_storage
27
-      */
28
-     protected $cache_storage;
29
-
30
-     /**
31
-      * EE_Encryption object
32
-      *
33
-      * @var EE_Encryption
34
-      */
35
-     protected $encryption;
36
-
37
-     /**
25
+	 /**
26
+	  * @var CacheStorageInterface $cache_storage
27
+	  */
28
+	 protected $cache_storage;
29
+
30
+	 /**
31
+	  * EE_Encryption object
32
+	  *
33
+	  * @var EE_Encryption
34
+	  */
35
+	 protected $encryption;
36
+
37
+	 /**
38 38
 	  * the session id
39 39
 	  * @var string
40 40
 	  */
@@ -65,12 +65,12 @@  discard block
 block discarded – undo
65 65
 	  */
66 66
 	 private $_expiration;
67 67
 
68
-    /**
69
-     * whether or not session has expired at some point
70
-     *
71
-     * @var boolean
72
-     */
73
-    private $_expired = false;
68
+	/**
69
+	 * whether or not session has expired at some point
70
+	 *
71
+	 * @var boolean
72
+	 */
73
+	private $_expired = false;
74 74
 
75 75
 	 /**
76 76
 	  * current time as Unix timestamp in GMT
@@ -107,30 +107,30 @@  discard block
 block discarded – undo
107 107
 	  * @var array
108 108
 	  */
109 109
 	 private $_default_session_vars = array (
110
-        'id'            => null,
111
-        'user_id'       => null,
112
-        'ip_address'    => null,
113
-        'user_agent'    => null,
114
-        'init_access'   => null,
115
-        'last_access'   => null,
116
-        'expiration'    => null,
117
-        'pages_visited' => array(),
110
+		'id'            => null,
111
+		'user_id'       => null,
112
+		'ip_address'    => null,
113
+		'user_agent'    => null,
114
+		'init_access'   => null,
115
+		'last_access'   => null,
116
+		'expiration'    => null,
117
+		'pages_visited' => array(),
118 118
 	);
119 119
 
120 120
 
121 121
 
122 122
 	 /**
123 123
 	  * @singleton method used to instantiate class object
124
-      * @param CacheStorageInterface $cache_storage
125
-      * @param \EE_Encryption        $encryption
124
+	  * @param CacheStorageInterface $cache_storage
125
+	  * @param \EE_Encryption        $encryption
126 126
 	  * @return EE_Session
127 127
 	  * @throws InvalidSessionDataException
128 128
 	  * @throws \EE_Error
129 129
 	  */
130 130
 	public static function instance(
131
-        CacheStorageInterface $cache_storage = null,
132
-        EE_Encryption $encryption = null
133
-    ) {
131
+		CacheStorageInterface $cache_storage = null,
132
+		EE_Encryption $encryption = null
133
+	) {
134 134
 		// check if class object is instantiated
135 135
 		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
136 136
 		// add_filter( 'FHEE_load_EE_Session', '__return_false' );
@@ -143,10 +143,10 @@  discard block
 block discarded – undo
143 143
 
144 144
 
145 145
 	 /**
146
-      * protected constructor to prevent direct creation
147
-      *
148
-      * @param CacheStorageInterface $cache_storage
149
-      * @param \EE_Encryption $encryption
146
+	  * protected constructor to prevent direct creation
147
+	  *
148
+	  * @param CacheStorageInterface $cache_storage
149
+	  * @param \EE_Encryption $encryption
150 150
 	  * @throws \EE_Error
151 151
 	  * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
152 152
 	  */
@@ -181,59 +181,59 @@  discard block
 block discarded – undo
181 181
 				$this->{$var_name} = $session_setting;
182 182
 			}
183 183
 		}
184
-         $this->cache_storage = $cache_storage;
185
-         // are we using encryption?
186
-         $this->_use_encryption = $encryption instanceof EE_Encryption && EE_Registry::instance()->CFG->admin->encode_session_data();
187
-         // \EEH_Debug_Tools::printr($this->_use_encryption, '$this->_use_encryption', __FILE__, __LINE__);
188
-        // encrypt data via: $this->encryption->encrypt();
189
-        $this->encryption = $encryption;
184
+		 $this->cache_storage = $cache_storage;
185
+		 // are we using encryption?
186
+		 $this->_use_encryption = $encryption instanceof EE_Encryption && EE_Registry::instance()->CFG->admin->encode_session_data();
187
+		 // \EEH_Debug_Tools::printr($this->_use_encryption, '$this->_use_encryption', __FILE__, __LINE__);
188
+		// encrypt data via: $this->encryption->encrypt();
189
+		$this->encryption = $encryption;
190 190
 		// filter hook allows outside functions/classes/plugins to change default empty cart
191 191
 		$extra_default_session_vars = apply_filters( 'FHEE__EE_Session__construct__extra_default_session_vars', array() );
192 192
 		array_merge( $this->_default_session_vars, $extra_default_session_vars );
193 193
 		// apply default session vars
194 194
 		$this->_set_defaults();
195
-         add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
196
-         // check request for 'clear_session' param
195
+		 add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
196
+		 // check request for 'clear_session' param
197 197
 		add_action( 'AHEE__EE_Request_Handler__construct__complete', array( $this, 'wp_loaded' ));
198 198
 		// once everything is all said and done,
199 199
 		add_action( 'shutdown', array( $this, 'update' ), 100 );
200
-         $this->configure_garbage_collection_filters();
200
+		 $this->configure_garbage_collection_filters();
201 201
 	}
202 202
 
203 203
 
204 204
 
205
-     /**
206
-      * @return void
207
-      * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
208
-      * @throws \EE_Error
209
-      */
205
+	 /**
206
+	  * @return void
207
+	  * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
208
+	  * @throws \EE_Error
209
+	  */
210 210
 	 public function open_session() {
211
-         // check for existing session and retrieve it from db
212
-         if ( ! $this->_espresso_session()) {
213
-             // or just start a new one
214
-             $this->_create_espresso_session();
215
-         }
216
-     }
211
+		 // check for existing session and retrieve it from db
212
+		 if ( ! $this->_espresso_session()) {
213
+			 // or just start a new one
214
+			 $this->_create_espresso_session();
215
+		 }
216
+	 }
217 217
 
218 218
 
219 219
 
220
-    /**
221
-     * @return bool
222
-     */
223
-    public function expired()
224
-    {
225
-        return $this->_expired;
226
-    }
220
+	/**
221
+	 * @return bool
222
+	 */
223
+	public function expired()
224
+	{
225
+		return $this->_expired;
226
+	}
227 227
 
228 228
 
229 229
 
230
-    /**
231
-     * @return void
232
-     */
233
-    public function reset_expired()
234
-    {
235
-        $this->_expired = false;
236
-    }
230
+	/**
231
+	 * @return void
232
+	 */
233
+	public function reset_expired()
234
+	{
235
+		$this->_expired = false;
236
+	}
237 237
 
238 238
 
239 239
 	 /**
@@ -245,24 +245,24 @@  discard block
 block discarded – undo
245 245
 
246 246
 
247 247
 
248
-    /**
249
-     * @return int
250
-     */
251
-    public function extension()
252
-    {
253
-        return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', (10 * MINUTE_IN_SECONDS));
254
-    }
248
+	/**
249
+	 * @return int
250
+	 */
251
+	public function extension()
252
+	{
253
+		return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', (10 * MINUTE_IN_SECONDS));
254
+	}
255 255
 
256 256
 
257 257
 
258
-    /**
259
-     * @param int $time number of seconds to add to session expiration
260
-     */
261
-    public function extend_expiration($time = 0)
262
-    {
263
-        $time = $time ? $time : $this->extension();
264
-        $this->_expiration += absint($time);
265
-    }
258
+	/**
259
+	 * @param int $time number of seconds to add to session expiration
260
+	 */
261
+	public function extend_expiration($time = 0)
262
+	{
263
+		$time = $time ? $time : $this->extension();
264
+		$this->_expiration += absint($time);
265
+	}
266 266
 
267 267
 
268 268
 
@@ -306,15 +306,15 @@  discard block
 block discarded – undo
306 306
 
307 307
 
308 308
 
309
-    /**
310
-     * @param \EE_Cart $cart
311
-     * @return bool
312
-     */
313
-    public function set_cart(EE_Cart $cart)
314
-    {
315
-        $this->_session_data['cart'] = $cart;
316
-        return true;
317
-    }
309
+	/**
310
+	 * @param \EE_Cart $cart
311
+	 * @return bool
312
+	 */
313
+	public function set_cart(EE_Cart $cart)
314
+	{
315
+		$this->_session_data['cart'] = $cart;
316
+		return true;
317
+	}
318 318
 
319 319
 
320 320
 
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
 	  * reset_cart
323 323
 	  */
324 324
 	 public function reset_cart() {
325
-        do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
325
+		do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
326 326
 		 $this->_session_data['cart'] = NULL;
327 327
 	 }
328 328
 
@@ -332,9 +332,9 @@  discard block
 block discarded – undo
332 332
 	  * @return \EE_Cart
333 333
 	  */
334 334
 	 public function cart() {
335
-        return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
336
-            ? $this->_session_data['cart']
337
-            : null;
335
+		return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
336
+			? $this->_session_data['cart']
337
+			: null;
338 338
 	 }
339 339
 
340 340
 
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
 	  * reset_checkout
355 355
 	  */
356 356
 	 public function reset_checkout() {
357
-        do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
357
+		do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
358 358
 		 $this->_session_data['checkout'] = NULL;
359 359
 	 }
360 360
 
@@ -364,9 +364,9 @@  discard block
 block discarded – undo
364 364
 	  * @return \EE_Checkout
365 365
 	  */
366 366
 	 public function checkout() {
367
-        return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
368
-            ? $this->_session_data['checkout']
369
-            : null;
367
+		return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
368
+			? $this->_session_data['checkout']
369
+			: null;
370 370
 	 }
371 371
 
372 372
 
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
 	  * reset_transaction
390 390
 	  */
391 391
 	 public function reset_transaction() {
392
-        do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
392
+		do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
393 393
 		 $this->_session_data['transaction'] = NULL;
394 394
 	 }
395 395
 
@@ -399,10 +399,10 @@  discard block
 block discarded – undo
399 399
 	  * @return \EE_Transaction
400 400
 	  */
401 401
 	 public function transaction() {
402
-        return isset($this->_session_data['transaction'])
403
-               && $this->_session_data['transaction'] instanceof EE_Transaction
404
-           ? $this->_session_data['transaction']
405
-           : null;
402
+		return isset($this->_session_data['transaction'])
403
+			   && $this->_session_data['transaction'] instanceof EE_Transaction
404
+		   ? $this->_session_data['transaction']
405
+		   : null;
406 406
 	 }
407 407
 
408 408
 
@@ -479,16 +479,16 @@  discard block
 block discarded – undo
479 479
 		// set the "user agent"
480 480
 		$this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr( $_SERVER['HTTP_USER_AGENT'] ) : FALSE;
481 481
 		// now let's retrieve what's in the db
482
-        $session_data = $this->_retrieve_session_data();
483
-        if (! empty($session_data)) {
484
-            // get the current time in UTC
482
+		$session_data = $this->_retrieve_session_data();
483
+		if (! empty($session_data)) {
484
+			// get the current time in UTC
485 485
 			$this->_time = isset( $this->_time ) ? $this->_time : time();
486 486
 			// and reset the session expiration
487 487
 			$this->_expiration = isset( $session_data['expiration'] )
488 488
 				? $session_data['expiration']
489 489
 				: $this->_time + $this->_lifespan;
490 490
 		} else {
491
-            // set initial site access time and the session expiration
491
+			// set initial site access time and the session expiration
492 492
 			$this->_set_init_access_and_expiration();
493 493
 			// set referer
494 494
 			$this->_session_data[ 'pages_visited' ][ $this->_session_data['init_access'] ] = isset( $_SERVER['HTTP_REFERER'] )
@@ -497,14 +497,14 @@  discard block
 block discarded – undo
497 497
 			// no previous session = go back and create one (on top of the data above)
498 498
 			return FALSE;
499 499
 		}
500
-        // now the user agent
500
+		// now the user agent
501 501
 		if ( $session_data['user_agent'] !== $this->_user_agent ) {
502 502
 			return FALSE;
503 503
 		}
504 504
 		// wait a minute... how old are you?
505 505
 		if ( $this->_time > $this->_expiration ) {
506 506
 			// yer too old fer me!
507
-            $this->_expired = true;
507
+			$this->_expired = true;
508 508
 			// wipe out everything that isn't a default session datum
509 509
 			$this->clear_session( __CLASS__, __FUNCTION__ );
510 510
 		}
@@ -516,101 +516,101 @@  discard block
 block discarded – undo
516 516
 
517 517
 
518 518
 
519
-     /**
520
-      * _get_session_data
521
-      * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup databases
522
-      *
523
-      * @return array
524
-      * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
525
-      */
526
-     protected function _retrieve_session_data()
527
-     {
528
-         $ssn_key = EE_Session::session_id_prefix . $this->_sid;
529
-         try {
530
-             // we're using WP's Transient API to store session data using the PHP session ID as the option name
531
-             $session_data = $this->cache_storage->get($ssn_key, false);
532
-	         if (empty($session_data)) {
533
-		         return array();
534
-             }
535
-             if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
536
-                 $hash_check = $this->cache_storage->get(
537
-                     EE_Session::hash_check_prefix . $this->_sid,
538
-                     false
539
-                 );
540
-                 if ($hash_check && $hash_check !== md5($session_data)) {
541
-	                 EE_Error::add_error(
542
-                         sprintf(
543
-                             __(
544
-                                 'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
545
-                                 'event_espresso'
546
-                             ),
547
-                             EE_Session::session_id_prefix . $this->_sid
548
-                         ),
549
-                         __FILE__, __FUNCTION__, __LINE__
550
-                     );
551
-                 }
552
-             }
553
-         } catch (Exception $e) {
554
-             // let's just eat that error for now and attempt to correct any corrupted data
555
-             global $wpdb;
556
-             $row = $wpdb->get_row(
557
-                 $wpdb->prepare(
558
-                     "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
559
-                     '_transient_' . $ssn_key
560
-                 )
561
-             );
562
-             $session_data = is_object($row) ? $row->option_value : null;
563
-             if ($session_data) {
564
-                 $session_data = preg_replace_callback(
565
-                     '!s:(d+):"(.*?)";!',
566
-                     function ($match) {
567
-                         return $match[1] === strlen($match[2])
568
-                             ? $match[0]
569
-                             : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
570
-                     },
571
-                     $session_data
572
-                 );
573
-             }
574
-	         $session_data = maybe_unserialize($session_data);
575
-         }
576
-	     // in case the data is encoded... try to decode it
577
-         $session_data = $this->encryption instanceof EE_Encryption
578
-             ? $this->encryption->base64_string_decode($session_data)
579
-             : $session_data;
580
-
581
-         if ( ! is_array($session_data)) {
582
-             try {
583
-	             $session_data = maybe_unserialize($session_data);
584
-             } catch (Exception $e) {
585
-                 $msg = esc_html__(
586
-                     'An error occurred while attempting to unserialize the session data.',
587
-                     'event_espresso'
588
-                 );
589
-                 $msg .= WP_DEBUG
590
-                     ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
591
-                     : '';
592
-                 throw new InvalidSessionDataException($msg, 0, $e);
593
-             }
594
-         }
595
-         // just a check to make sure the session array is indeed an array
596
-         if ( ! is_array($session_data)) {
597
-             // no?!?! then something is wrong
598
-             $msg = esc_html__(
599
-                 'The session data is missing, invalid, or corrupted.',
600
-                 'event_espresso'
601
-             );
602
-             $msg .= WP_DEBUG
603
-                 ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
604
-                 : '';
605
-	         throw new InvalidSessionDataException($msg);
606
-         }
607
-	     if ( isset($session_data['transaction'] ) && absint($session_data['transaction'] ) !== 0 ) {
608
-             $session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
609
-                 $session_data['transaction']
610
-	         );
611
-	     }
612
-         return $session_data;
613
-     }
519
+	 /**
520
+	  * _get_session_data
521
+	  * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup databases
522
+	  *
523
+	  * @return array
524
+	  * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
525
+	  */
526
+	 protected function _retrieve_session_data()
527
+	 {
528
+		 $ssn_key = EE_Session::session_id_prefix . $this->_sid;
529
+		 try {
530
+			 // we're using WP's Transient API to store session data using the PHP session ID as the option name
531
+			 $session_data = $this->cache_storage->get($ssn_key, false);
532
+			 if (empty($session_data)) {
533
+				 return array();
534
+			 }
535
+			 if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
536
+				 $hash_check = $this->cache_storage->get(
537
+					 EE_Session::hash_check_prefix . $this->_sid,
538
+					 false
539
+				 );
540
+				 if ($hash_check && $hash_check !== md5($session_data)) {
541
+					 EE_Error::add_error(
542
+						 sprintf(
543
+							 __(
544
+								 'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
545
+								 'event_espresso'
546
+							 ),
547
+							 EE_Session::session_id_prefix . $this->_sid
548
+						 ),
549
+						 __FILE__, __FUNCTION__, __LINE__
550
+					 );
551
+				 }
552
+			 }
553
+		 } catch (Exception $e) {
554
+			 // let's just eat that error for now and attempt to correct any corrupted data
555
+			 global $wpdb;
556
+			 $row = $wpdb->get_row(
557
+				 $wpdb->prepare(
558
+					 "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
559
+					 '_transient_' . $ssn_key
560
+				 )
561
+			 );
562
+			 $session_data = is_object($row) ? $row->option_value : null;
563
+			 if ($session_data) {
564
+				 $session_data = preg_replace_callback(
565
+					 '!s:(d+):"(.*?)";!',
566
+					 function ($match) {
567
+						 return $match[1] === strlen($match[2])
568
+							 ? $match[0]
569
+							 : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
570
+					 },
571
+					 $session_data
572
+				 );
573
+			 }
574
+			 $session_data = maybe_unserialize($session_data);
575
+		 }
576
+		 // in case the data is encoded... try to decode it
577
+		 $session_data = $this->encryption instanceof EE_Encryption
578
+			 ? $this->encryption->base64_string_decode($session_data)
579
+			 : $session_data;
580
+
581
+		 if ( ! is_array($session_data)) {
582
+			 try {
583
+				 $session_data = maybe_unserialize($session_data);
584
+			 } catch (Exception $e) {
585
+				 $msg = esc_html__(
586
+					 'An error occurred while attempting to unserialize the session data.',
587
+					 'event_espresso'
588
+				 );
589
+				 $msg .= WP_DEBUG
590
+					 ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
591
+					 : '';
592
+				 throw new InvalidSessionDataException($msg, 0, $e);
593
+			 }
594
+		 }
595
+		 // just a check to make sure the session array is indeed an array
596
+		 if ( ! is_array($session_data)) {
597
+			 // no?!?! then something is wrong
598
+			 $msg = esc_html__(
599
+				 'The session data is missing, invalid, or corrupted.',
600
+				 'event_espresso'
601
+			 );
602
+			 $msg .= WP_DEBUG
603
+				 ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
604
+				 : '';
605
+			 throw new InvalidSessionDataException($msg);
606
+		 }
607
+		 if ( isset($session_data['transaction'] ) && absint($session_data['transaction'] ) !== 0 ) {
608
+			 $session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
609
+				 $session_data['transaction']
610
+			 );
611
+		 }
612
+		 return $session_data;
613
+	 }
614 614
 
615 615
 
616 616
 
@@ -677,13 +677,13 @@  discard block
 block discarded – undo
677 677
 
678 678
 
679 679
 
680
-     /**
681
-      * @update session data  prior to saving to the db
682
-      * @access public
683
-      * @param bool $new_session
684
-      * @return TRUE on success, FALSE on fail
685
-      * @throws \EE_Error
686
-      */
680
+	 /**
681
+	  * @update session data  prior to saving to the db
682
+	  * @access public
683
+	  * @param bool $new_session
684
+	  * @return TRUE on success, FALSE on fail
685
+	  * @throws \EE_Error
686
+	  */
687 687
 	public function update( $new_session = FALSE ) {
688 688
 		$this->_session_data = isset( $this->_session_data )
689 689
 			&& is_array( $this->_session_data )
@@ -769,12 +769,12 @@  discard block
 block discarded – undo
769 769
 
770 770
 
771 771
 
772
-     /**
773
-      * @create session data array
774
-      * @access public
775
-      * @return bool
776
-      * @throws \EE_Error
777
-      */
772
+	 /**
773
+	  * @create session data array
774
+	  * @access public
775
+	  * @return bool
776
+	  * @throws \EE_Error
777
+	  */
778 778
 	private function _create_espresso_session( ) {
779 779
 		do_action( 'AHEE_log', __CLASS__, __FUNCTION__, '' );
780 780
 		// use the update function for now with $new_session arg set to TRUE
@@ -794,19 +794,19 @@  discard block
 block discarded – undo
794 794
 		if (
795 795
 			// if the current request is NOT one of the following
796 796
 			! (
797
-                // an an AJAX request from the frontend
798
-                EE_Registry::instance()->REQ->front_ajax
799
-                || (
800
-                    // OR an admin request that is NOT AJAX
797
+				// an an AJAX request from the frontend
798
+				EE_Registry::instance()->REQ->front_ajax
799
+				|| (
800
+					// OR an admin request that is NOT AJAX
801 801
 					! ( defined( 'DOING_AJAX' ) && DOING_AJAX )
802
-                    && is_admin()
802
+					&& is_admin()
803 803
 				)
804
-                || (
805
-                    // OR an espresso page
806
-                    EE_Registry::instance()->REQ instanceof EE_Request_Handler
807
-                    && EE_Registry::instance()->REQ->is_espresso_page()
808
-                )
809
-            )
804
+				|| (
805
+					// OR an espresso page
806
+					EE_Registry::instance()->REQ instanceof EE_Request_Handler
807
+					&& EE_Registry::instance()->REQ->is_espresso_page()
808
+				)
809
+			)
810 810
 		) {
811 811
 			return false;
812 812
 		}
@@ -817,27 +817,27 @@  discard block
 block discarded – undo
817 817
 			}
818 818
 			$this->_session_data['transaction'] = $transaction->ID();
819 819
 		}
820
-        // then serialize all of our session data
820
+		// then serialize all of our session data
821 821
 		$session_data = serialize($this->_session_data);
822 822
 		// do we need to also encode it to avoid corrupted data when saved to the db?
823 823
 		$session_data = $this->_use_encryption
824
-            ? $this->encryption->base64_string_encode( $session_data )
825
-            : $session_data;
824
+			? $this->encryption->base64_string_encode( $session_data )
825
+			: $session_data;
826 826
 		// maybe save hash check
827 827
 		if ( apply_filters( 'FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG ) ) {
828
-            $this->cache_storage->add(
829
-                EE_Session::hash_check_prefix . $this->_sid,
830
-                md5($session_data),
831
-                $this->_lifespan
832
-            );
833
-        }
834
-        // we're using the Transient API for storing session data,
835
-        return $this->cache_storage->add(
836
-            EE_Session::session_id_prefix . $this->_sid,
837
-            $session_data,
838
-            $this->_lifespan
839
-        );
840
-    }
828
+			$this->cache_storage->add(
829
+				EE_Session::hash_check_prefix . $this->_sid,
830
+				md5($session_data),
831
+				$this->_lifespan
832
+			);
833
+		}
834
+		// we're using the Transient API for storing session data,
835
+		return $this->cache_storage->add(
836
+			EE_Session::session_id_prefix . $this->_sid,
837
+			$session_data,
838
+			$this->_lifespan
839
+		);
840
+	}
841 841
 
842 842
 
843 843
 
@@ -930,18 +930,18 @@  discard block
 block discarded – undo
930 930
 
931 931
 
932 932
 
933
-     /**
934
-      * Clear EE_Session data
935
-      *
936
-      * @access public
937
-      * @param string $class
938
-      * @param string $function
939
-      * @return void
940
-      * @throws \EE_Error
941
-      */
933
+	 /**
934
+	  * Clear EE_Session data
935
+	  *
936
+	  * @access public
937
+	  * @param string $class
938
+	  * @param string $function
939
+	  * @return void
940
+	  * @throws \EE_Error
941
+	  */
942 942
 	public function clear_session( $class = '', $function = '' ) {
943 943
 		//echo '<h3 style="color:#999;line-height:.9em;"><span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/><span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b></h3>';
944
-        do_action( 'AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' .  $function . '()' );
944
+		do_action( 'AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' .  $function . '()' );
945 945
 		$this->reset_cart();
946 946
 		$this->reset_checkout();
947 947
 		$this->reset_transaction();
@@ -1008,12 +1008,12 @@  discard block
 block discarded – undo
1008 1008
 
1009 1009
 
1010 1010
 
1011
-     /**
1012
-      *   wp_loaded
1013
-      *
1014
-      * @access public
1015
-      * @throws \EE_Error
1016
-      */
1011
+	 /**
1012
+	  *   wp_loaded
1013
+	  *
1014
+	  * @access public
1015
+	  * @throws \EE_Error
1016
+	  */
1017 1017
 	public function wp_loaded() {
1018 1018
 		if ( isset(  EE_Registry::instance()->REQ ) && EE_Registry::instance()->REQ->is_set( 'clear_session' )) {
1019 1019
 			$this->clear_session( __CLASS__, __FUNCTION__ );
@@ -1022,12 +1022,12 @@  discard block
 block discarded – undo
1022 1022
 
1023 1023
 
1024 1024
 
1025
-     /**
1026
-      * Used to reset the entire object (for tests).
1027
-      *
1028
-      * @since 4.3.0
1029
-      * @throws \EE_Error
1030
-      */
1025
+	 /**
1026
+	  * Used to reset the entire object (for tests).
1027
+	  *
1028
+	  * @since 4.3.0
1029
+	  * @throws \EE_Error
1030
+	  */
1031 1031
 	public function reset_instance() {
1032 1032
 		$this->clear_session();
1033 1033
 		self::$_instance = NULL;
@@ -1035,29 +1035,29 @@  discard block
 block discarded – undo
1035 1035
 
1036 1036
 
1037 1037
 
1038
-     public function configure_garbage_collection_filters()
1039
-     {
1040
-         // run old filter we had for controlling session cleanup
1041
-         $expired_session_transient_delete_query_limit = absint(
1042
-             apply_filters(
1043
-                 'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1044
-                 50
1045
-             )
1046
-         );
1047
-         // is there a value? or one that is different than the default 50 records?
1048
-         if ($expired_session_transient_delete_query_limit === 0) {
1049
-             // hook into TransientCacheStorage in case Session cleanup was turned off
1050
-             add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1051
-         } else if ($expired_session_transient_delete_query_limit !== 50) {
1052
-             // or use that for the new transient cleanup query limit
1053
-             add_filter(
1054
-                 'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1055
-                 function () use ($expired_session_transient_delete_query_limit) {
1056
-                     return $expired_session_transient_delete_query_limit;
1057
-                 }
1058
-             );
1059
-         }
1060
-     }
1038
+	 public function configure_garbage_collection_filters()
1039
+	 {
1040
+		 // run old filter we had for controlling session cleanup
1041
+		 $expired_session_transient_delete_query_limit = absint(
1042
+			 apply_filters(
1043
+				 'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1044
+				 50
1045
+			 )
1046
+		 );
1047
+		 // is there a value? or one that is different than the default 50 records?
1048
+		 if ($expired_session_transient_delete_query_limit === 0) {
1049
+			 // hook into TransientCacheStorage in case Session cleanup was turned off
1050
+			 add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1051
+		 } else if ($expired_session_transient_delete_query_limit !== 50) {
1052
+			 // or use that for the new transient cleanup query limit
1053
+			 add_filter(
1054
+				 'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1055
+				 function () use ($expired_session_transient_delete_query_limit) {
1056
+					 return $expired_session_transient_delete_query_limit;
1057
+				 }
1058
+			 );
1059
+		 }
1060
+	 }
1061 1061
 
1062 1062
 
1063 1063
 
Please login to merge, or discard this patch.
Spacing   +148 added lines, -148 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\exceptions\InvalidSessionDataException;
3 3
 use EventEspresso\core\services\cache\CacheStorageInterface;
4 4
 
5
-if (!defined( 'EVENT_ESPRESSO_VERSION')) {exit('No direct script access allowed');}
5
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {exit('No direct script access allowed'); }
6 6
 /**
7 7
  *
8 8
  * EE_Session class
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	  * array for defining default session vars
109 109
 	  * @var array
110 110
 	  */
111
-	 private $_default_session_vars = array (
111
+	 private $_default_session_vars = array(
112 112
         'id'            => null,
113 113
         'user_id'       => null,
114 114
         'ip_address'    => null,
@@ -136,8 +136,8 @@  discard block
 block discarded – undo
136 136
 		// check if class object is instantiated
137 137
 		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
138 138
 		// add_filter( 'FHEE_load_EE_Session', '__return_false' );
139
-		if ( ! self::$_instance instanceof EE_Session && apply_filters( 'FHEE_load_EE_Session', true ) ) {
140
-			self::$_instance = new self($cache_storage, $encryption );
139
+		if ( ! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
140
+			self::$_instance = new self($cache_storage, $encryption);
141 141
 		}
142 142
 		return self::$_instance;
143 143
 	}
@@ -152,15 +152,15 @@  discard block
 block discarded – undo
152 152
 	  * @throws \EE_Error
153 153
 	  * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
154 154
 	  */
155
-	 protected function __construct(CacheStorageInterface $cache_storage, EE_Encryption $encryption = null ) {
155
+	 protected function __construct(CacheStorageInterface $cache_storage, EE_Encryption $encryption = null) {
156 156
 
157 157
 		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
158
-		if ( ! apply_filters( 'FHEE_load_EE_Session', true ) ) {
158
+		if ( ! apply_filters('FHEE_load_EE_Session', true)) {
159 159
 			return;
160 160
 		}
161
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
162
-		if ( ! defined( 'ESPRESSO_SESSION' ) ) {
163
-			define( 'ESPRESSO_SESSION', true );
161
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
162
+		if ( ! defined('ESPRESSO_SESSION')) {
163
+			define('ESPRESSO_SESSION', true);
164 164
 		}
165 165
 		// default session lifespan in seconds
166 166
 		$this->_lifespan = apply_filters(
@@ -174,12 +174,12 @@  discard block
 block discarded – undo
174 174
 		 * 		}
175 175
 		 */
176 176
 		// retrieve session options from db
177
-		$session_settings = (array) get_option( 'ee_session_settings', array() );
178
-		if ( ! empty( $session_settings )) {
177
+		$session_settings = (array) get_option('ee_session_settings', array());
178
+		if ( ! empty($session_settings)) {
179 179
 			// cycle though existing session options
180
-			foreach ( $session_settings as $var_name => $session_setting ) {
180
+			foreach ($session_settings as $var_name => $session_setting) {
181 181
 				// set values for class properties
182
-				$var_name = '_' . $var_name;
182
+				$var_name = '_'.$var_name;
183 183
 				$this->{$var_name} = $session_setting;
184 184
 			}
185 185
 		}
@@ -190,15 +190,15 @@  discard block
 block discarded – undo
190 190
         // encrypt data via: $this->encryption->encrypt();
191 191
         $this->encryption = $encryption;
192 192
 		// filter hook allows outside functions/classes/plugins to change default empty cart
193
-		$extra_default_session_vars = apply_filters( 'FHEE__EE_Session__construct__extra_default_session_vars', array() );
194
-		array_merge( $this->_default_session_vars, $extra_default_session_vars );
193
+		$extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
194
+		array_merge($this->_default_session_vars, $extra_default_session_vars);
195 195
 		// apply default session vars
196 196
 		$this->_set_defaults();
197 197
          add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
198 198
          // check request for 'clear_session' param
199
-		add_action( 'AHEE__EE_Request_Handler__construct__complete', array( $this, 'wp_loaded' ));
199
+		add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
200 200
 		// once everything is all said and done,
201
-		add_action( 'shutdown', array( $this, 'update' ), 100 );
201
+		add_action('shutdown', array($this, 'update'), 100);
202 202
          $this->configure_garbage_collection_filters();
203 203
 	}
204 204
 
@@ -286,11 +286,11 @@  discard block
 block discarded – undo
286 286
 	 */
287 287
 	private function _set_defaults() {
288 288
 		// set some defaults
289
-		foreach ( $this->_default_session_vars as $key => $default_var ) {
290
-			if ( is_array( $default_var )) {
291
-				$this->_session_data[ $key ] = array();
289
+		foreach ($this->_default_session_vars as $key => $default_var) {
290
+			if (is_array($default_var)) {
291
+				$this->_session_data[$key] = array();
292 292
 			} else {
293
-				$this->_session_data[ $key ] = '';
293
+				$this->_session_data[$key] = '';
294 294
 			}
295 295
 		}
296 296
 	}
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 	  * @param \EE_Checkout $checkout
346 346
 	  * @return bool
347 347
 	  */
348
-	 public function set_checkout( EE_Checkout $checkout ) {
348
+	 public function set_checkout(EE_Checkout $checkout) {
349 349
 		 $this->_session_data['checkout'] = $checkout;
350 350
 		 return TRUE;
351 351
 	 }
@@ -378,9 +378,9 @@  discard block
 block discarded – undo
378 378
 	  * @return bool
379 379
 	  * @throws \EE_Error
380 380
 	  */
381
-	 public function set_transaction( EE_Transaction $transaction ) {
381
+	 public function set_transaction(EE_Transaction $transaction) {
382 382
 		 // first remove the session from the transaction before we save the transaction in the session
383
-		 $transaction->set_txn_session_data( NULL );
383
+		 $transaction->set_txn_session_data(NULL);
384 384
 		 $this->_session_data['transaction'] = $transaction;
385 385
 		 return TRUE;
386 386
 	 }
@@ -416,15 +416,15 @@  discard block
 block discarded – undo
416 416
 	  * @param bool $reset_cache
417 417
 	  * @return    array
418 418
 	  */
419
-	public function get_session_data( $key = NULL, $reset_cache = FALSE ) {
420
-		if ( $reset_cache ) {
419
+	public function get_session_data($key = NULL, $reset_cache = FALSE) {
420
+		if ($reset_cache) {
421 421
 			$this->reset_cart();
422 422
 			$this->reset_checkout();
423 423
 			$this->reset_transaction();
424 424
 		}
425
-		 if ( ! empty( $key ))  {
426
-			return  isset( $this->_session_data[ $key ] ) ? $this->_session_data[ $key ] : NULL;
427
-		}  else  {
425
+		 if ( ! empty($key)) {
426
+			return  isset($this->_session_data[$key]) ? $this->_session_data[$key] : NULL;
427
+		} else {
428 428
 			return $this->_session_data;
429 429
 		}
430 430
 	}
@@ -437,20 +437,20 @@  discard block
 block discarded – undo
437 437
 	  * @param 	array $data
438 438
 	  * @return 	TRUE on success, FALSE on fail
439 439
 	  */
440
-	public function set_session_data( $data ) {
440
+	public function set_session_data($data) {
441 441
 
442 442
 		// nothing ??? bad data ??? go home!
443
-		if ( empty( $data ) || ! is_array( $data )) {
444
-			EE_Error::add_error( __( 'No session data or invalid session data was provided.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
443
+		if (empty($data) || ! is_array($data)) {
444
+			EE_Error::add_error(__('No session data or invalid session data was provided.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
445 445
 			return FALSE;
446 446
 		}
447 447
 
448
-		foreach ( $data as $key =>$value ) {
449
-			if ( isset( $this->_default_session_vars[ $key ] )) {
450
-				EE_Error::add_error( sprintf( __( 'Sorry! %s is a default session datum and can not be reset.', 'event_espresso' ), $key ), __FILE__, __FUNCTION__, __LINE__ );
448
+		foreach ($data as $key =>$value) {
449
+			if (isset($this->_default_session_vars[$key])) {
450
+				EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.', 'event_espresso'), $key), __FILE__, __FUNCTION__, __LINE__);
451 451
 				return FALSE;
452 452
 			} else {
453
-				$this->_session_data[ $key ] = $value;
453
+				$this->_session_data[$key] = $value;
454 454
 			}
455 455
 		}
456 456
 
@@ -468,9 +468,9 @@  discard block
 block discarded – undo
468 468
 	  * @throws \EE_Error
469 469
 	  */
470 470
 	private function _espresso_session() {
471
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
471
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
472 472
 		// check that session has started
473
-		if ( session_id() === '' ) {
473
+		if (session_id() === '') {
474 474
 			//starts a new session if one doesn't already exist, or re-initiates an existing one
475 475
 			session_start();
476 476
 		}
@@ -479,39 +479,39 @@  discard block
 block discarded – undo
479 479
 		// and the visitors IP
480 480
 		$this->_ip_address = $this->_visitor_ip();
481 481
 		// set the "user agent"
482
-		$this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr( $_SERVER['HTTP_USER_AGENT'] ) : FALSE;
482
+		$this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr($_SERVER['HTTP_USER_AGENT']) : FALSE;
483 483
 		// now let's retrieve what's in the db
484 484
         $session_data = $this->_retrieve_session_data();
485
-        if (! empty($session_data)) {
485
+        if ( ! empty($session_data)) {
486 486
             // get the current time in UTC
487
-			$this->_time = isset( $this->_time ) ? $this->_time : time();
487
+			$this->_time = isset($this->_time) ? $this->_time : time();
488 488
 			// and reset the session expiration
489
-			$this->_expiration = isset( $session_data['expiration'] )
489
+			$this->_expiration = isset($session_data['expiration'])
490 490
 				? $session_data['expiration']
491 491
 				: $this->_time + $this->_lifespan;
492 492
 		} else {
493 493
             // set initial site access time and the session expiration
494 494
 			$this->_set_init_access_and_expiration();
495 495
 			// set referer
496
-			$this->_session_data[ 'pages_visited' ][ $this->_session_data['init_access'] ] = isset( $_SERVER['HTTP_REFERER'] )
497
-				? esc_attr( $_SERVER['HTTP_REFERER'] )
496
+			$this->_session_data['pages_visited'][$this->_session_data['init_access']] = isset($_SERVER['HTTP_REFERER'])
497
+				? esc_attr($_SERVER['HTTP_REFERER'])
498 498
 				: '';
499 499
 			// no previous session = go back and create one (on top of the data above)
500 500
 			return FALSE;
501 501
 		}
502 502
         // now the user agent
503
-		if ( $session_data['user_agent'] !== $this->_user_agent ) {
503
+		if ($session_data['user_agent'] !== $this->_user_agent) {
504 504
 			return FALSE;
505 505
 		}
506 506
 		// wait a minute... how old are you?
507
-		if ( $this->_time > $this->_expiration ) {
507
+		if ($this->_time > $this->_expiration) {
508 508
 			// yer too old fer me!
509 509
             $this->_expired = true;
510 510
 			// wipe out everything that isn't a default session datum
511
-			$this->clear_session( __CLASS__, __FUNCTION__ );
511
+			$this->clear_session(__CLASS__, __FUNCTION__);
512 512
 		}
513 513
 		// make event espresso session data available to plugin
514
-		$this->_session_data = array_merge( $this->_session_data, $session_data );
514
+		$this->_session_data = array_merge($this->_session_data, $session_data);
515 515
 		return TRUE;
516 516
 
517 517
 	}
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
       */
528 528
      protected function _retrieve_session_data()
529 529
      {
530
-         $ssn_key = EE_Session::session_id_prefix . $this->_sid;
530
+         $ssn_key = EE_Session::session_id_prefix.$this->_sid;
531 531
          try {
532 532
              // we're using WP's Transient API to store session data using the PHP session ID as the option name
533 533
              $session_data = $this->cache_storage->get($ssn_key, false);
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
              }
537 537
              if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
538 538
                  $hash_check = $this->cache_storage->get(
539
-                     EE_Session::hash_check_prefix . $this->_sid,
539
+                     EE_Session::hash_check_prefix.$this->_sid,
540 540
                      false
541 541
                  );
542 542
                  if ($hash_check && $hash_check !== md5($session_data)) {
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
                                  'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
547 547
                                  'event_espresso'
548 548
                              ),
549
-                             EE_Session::session_id_prefix . $this->_sid
549
+                             EE_Session::session_id_prefix.$this->_sid
550 550
                          ),
551 551
                          __FILE__, __FUNCTION__, __LINE__
552 552
                      );
@@ -558,17 +558,17 @@  discard block
 block discarded – undo
558 558
              $row = $wpdb->get_row(
559 559
                  $wpdb->prepare(
560 560
                      "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
561
-                     '_transient_' . $ssn_key
561
+                     '_transient_'.$ssn_key
562 562
                  )
563 563
              );
564 564
              $session_data = is_object($row) ? $row->option_value : null;
565 565
              if ($session_data) {
566 566
                  $session_data = preg_replace_callback(
567 567
                      '!s:(d+):"(.*?)";!',
568
-                     function ($match) {
568
+                     function($match) {
569 569
                          return $match[1] === strlen($match[2])
570 570
                              ? $match[0]
571
-                             : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
571
+                             : 's:'.strlen($match[2]).':"'.$match[2].'";';
572 572
                      },
573 573
                      $session_data
574 574
                  );
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
                      'event_espresso'
590 590
                  );
591 591
                  $msg .= WP_DEBUG
592
-                     ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
592
+                     ? '<br><pre>'.print_r($session_data, true).'</pre><br>'.$this->find_serialize_error($session_data)
593 593
                      : '';
594 594
                  throw new InvalidSessionDataException($msg, 0, $e);
595 595
              }
@@ -602,11 +602,11 @@  discard block
 block discarded – undo
602 602
                  'event_espresso'
603 603
              );
604 604
              $msg .= WP_DEBUG
605
-                 ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
605
+                 ? '<br><pre>'.print_r($session_data, true).'</pre><br>'.$this->find_serialize_error($session_data)
606 606
                  : '';
607 607
 	         throw new InvalidSessionDataException($msg);
608 608
          }
609
-	     if ( isset($session_data['transaction'] ) && absint($session_data['transaction'] ) !== 0 ) {
609
+	     if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
610 610
              $session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
611 611
                  $session_data['transaction']
612 612
 	         );
@@ -627,12 +627,12 @@  discard block
 block discarded – undo
627 627
 	  */
628 628
 	protected function _generate_session_id() {
629 629
 		// check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
630
-		if ( isset( $_REQUEST[ 'EESID' ] ) ) {
631
-			$session_id = sanitize_text_field( $_REQUEST[ 'EESID' ] );
630
+		if (isset($_REQUEST['EESID'])) {
631
+			$session_id = sanitize_text_field($_REQUEST['EESID']);
632 632
 		} else {
633
-			$session_id = md5( session_id() . get_current_blog_id() . $this->_get_sid_salt() );
633
+			$session_id = md5(session_id().get_current_blog_id().$this->_get_sid_salt());
634 634
 		}
635
-		return apply_filters( 'FHEE__EE_Session___generate_session_id__session_id', $session_id );
635
+		return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
636 636
 	}
637 637
 
638 638
 
@@ -644,20 +644,20 @@  discard block
 block discarded – undo
644 644
 	  */
645 645
 	protected function _get_sid_salt() {
646 646
 		// was session id salt already saved to db ?
647
-		if ( empty( $this->_sid_salt ) ) {
647
+		if (empty($this->_sid_salt)) {
648 648
 			// no?  then maybe use WP defined constant
649
-			if ( defined( 'AUTH_SALT' ) ) {
649
+			if (defined('AUTH_SALT')) {
650 650
 				$this->_sid_salt = AUTH_SALT;
651 651
 			}
652 652
 			// if salt doesn't exist or is too short
653
-			if ( strlen( $this->_sid_salt ) < 32 ) {
653
+			if (strlen($this->_sid_salt) < 32) {
654 654
 				// create a new one
655
-				$this->_sid_salt = wp_generate_password( 64 );
655
+				$this->_sid_salt = wp_generate_password(64);
656 656
 			}
657 657
 			// and save it as a permanent session setting
658
-			$session_settings = get_option( 'ee_session_settings' );
659
-			$session_settings[ 'sid_salt' ] = $this->_sid_salt;
660
-			update_option( 'ee_session_settings', $session_settings );
658
+			$session_settings = get_option('ee_session_settings');
659
+			$session_settings['sid_salt'] = $this->_sid_salt;
660
+			update_option('ee_session_settings', $session_settings);
661 661
 		}
662 662
 		return $this->_sid_salt;
663 663
 	}
@@ -686,19 +686,19 @@  discard block
 block discarded – undo
686 686
       * @return TRUE on success, FALSE on fail
687 687
       * @throws \EE_Error
688 688
       */
689
-	public function update( $new_session = FALSE ) {
690
-		$this->_session_data = isset( $this->_session_data )
691
-			&& is_array( $this->_session_data )
692
-			&& isset( $this->_session_data['id'])
689
+	public function update($new_session = FALSE) {
690
+		$this->_session_data = isset($this->_session_data)
691
+			&& is_array($this->_session_data)
692
+			&& isset($this->_session_data['id'])
693 693
 			? $this->_session_data
694 694
 			: array();
695
-		if ( empty( $this->_session_data )) {
695
+		if (empty($this->_session_data)) {
696 696
 			$this->_set_defaults();
697 697
 		}
698 698
 		$session_data = array();
699
-		foreach ( $this->_session_data as $key => $value ) {
699
+		foreach ($this->_session_data as $key => $value) {
700 700
 
701
-			switch( $key ) {
701
+			switch ($key) {
702 702
 
703 703
 				case 'id' :
704 704
 					// session ID
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
 				break;
717 717
 
718 718
 				case 'init_access' :
719
-					$session_data['init_access'] = absint( $value );
719
+					$session_data['init_access'] = absint($value);
720 720
 				break;
721 721
 
722 722
 				case 'last_access' :
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 
727 727
 				case 'expiration' :
728 728
 					// when the session expires
729
-					$session_data['expiration'] = ! empty( $this->_expiration )
729
+					$session_data['expiration'] = ! empty($this->_expiration)
730 730
 						? $this->_expiration
731 731
 						: $session_data['init_access'] + $this->_lifespan;
732 732
 				break;
@@ -738,11 +738,11 @@  discard block
 block discarded – undo
738 738
 
739 739
 				case 'pages_visited' :
740 740
 					$page_visit = $this->_get_page_visit();
741
-					if ( $page_visit ) {
741
+					if ($page_visit) {
742 742
 						// set pages visited where the first will be the http referrer
743
-						$this->_session_data[ 'pages_visited' ][ $this->_time ] = $page_visit;
743
+						$this->_session_data['pages_visited'][$this->_time] = $page_visit;
744 744
 						// we'll only save the last 10 page visits.
745
-						$session_data[ 'pages_visited' ] = array_slice( $this->_session_data['pages_visited'], -10 );
745
+						$session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
746 746
 					}
747 747
 				break;
748 748
 
@@ -756,9 +756,9 @@  discard block
 block discarded – undo
756 756
 
757 757
 		$this->_session_data = $session_data;
758 758
 		// creating a new session does not require saving to the db just yet
759
-		if ( ! $new_session ) {
759
+		if ( ! $new_session) {
760 760
 			// ready? let's save
761
-			if ( $this->_save_session_to_db() ) {
761
+			if ($this->_save_session_to_db()) {
762 762
 				return TRUE;
763 763
 			} else {
764 764
 				return FALSE;
@@ -778,9 +778,9 @@  discard block
 block discarded – undo
778 778
       * @throws \EE_Error
779 779
       */
780 780
 	private function _create_espresso_session( ) {
781
-		do_action( 'AHEE_log', __CLASS__, __FUNCTION__, '' );
781
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
782 782
 		// use the update function for now with $new_session arg set to TRUE
783
-		return  $this->update( TRUE ) ? TRUE : FALSE;
783
+		return  $this->update(TRUE) ? TRUE : FALSE;
784 784
 	}
785 785
 
786 786
 
@@ -800,7 +800,7 @@  discard block
 block discarded – undo
800 800
                 EE_Registry::instance()->REQ->front_ajax
801 801
                 || (
802 802
                     // OR an admin request that is NOT AJAX
803
-					! ( defined( 'DOING_AJAX' ) && DOING_AJAX )
803
+					! (defined('DOING_AJAX') && DOING_AJAX)
804 804
                     && is_admin()
805 805
 				)
806 806
                 || (
@@ -813,8 +813,8 @@  discard block
 block discarded – undo
813 813
 			return false;
814 814
 		}
815 815
 		$transaction = $this->transaction();
816
-		if ( $transaction instanceof EE_Transaction ) {
817
-			if ( ! $transaction->ID() ) {
816
+		if ($transaction instanceof EE_Transaction) {
817
+			if ( ! $transaction->ID()) {
818 818
 				$transaction->save();
819 819
 			}
820 820
 			$this->_session_data['transaction'] = $transaction->ID();
@@ -823,19 +823,19 @@  discard block
 block discarded – undo
823 823
 		$session_data = serialize($this->_session_data);
824 824
 		// do we need to also encode it to avoid corrupted data when saved to the db?
825 825
 		$session_data = $this->_use_encryption
826
-            ? $this->encryption->base64_string_encode( $session_data )
826
+            ? $this->encryption->base64_string_encode($session_data)
827 827
             : $session_data;
828 828
 		// maybe save hash check
829
-		if ( apply_filters( 'FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG ) ) {
829
+		if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
830 830
             $this->cache_storage->add(
831
-                EE_Session::hash_check_prefix . $this->_sid,
831
+                EE_Session::hash_check_prefix.$this->_sid,
832 832
                 md5($session_data),
833 833
                 $this->_lifespan
834 834
             );
835 835
         }
836 836
         // we're using the Transient API for storing session data,
837 837
         return $this->cache_storage->add(
838
-            EE_Session::session_id_prefix . $this->_sid,
838
+            EE_Session::session_id_prefix.$this->_sid,
839 839
             $session_data,
840 840
             $this->_lifespan
841 841
         );
@@ -864,10 +864,10 @@  discard block
 block discarded – undo
864 864
 			'HTTP_FORWARDED',
865 865
 			'REMOTE_ADDR'
866 866
 		);
867
-		foreach ( $server_keys as $key ){
868
-			if ( isset( $_SERVER[ $key ] )) {
869
-				foreach ( array_map( 'trim', explode( ',', $_SERVER[ $key ] )) as $ip ) {
870
-					if ( $ip === '127.0.0.1' || filter_var( $ip, FILTER_VALIDATE_IP ) !== FALSE ) {
867
+		foreach ($server_keys as $key) {
868
+			if (isset($_SERVER[$key])) {
869
+				foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
870
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== FALSE) {
871 871
 						$visitor_ip = $ip;
872 872
 					}
873 873
 				}
@@ -886,32 +886,32 @@  discard block
 block discarded – undo
886 886
 	 *			@return string
887 887
 	 */
888 888
 	public function _get_page_visit() {
889
-		$page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
889
+		$page_visit = home_url('/').'wp-admin/admin-ajax.php';
890 890
 		// check for request url
891
-		if ( isset( $_SERVER['REQUEST_URI'] )) {
891
+		if (isset($_SERVER['REQUEST_URI'])) {
892 892
 			$http_host = '';
893 893
 			$page_id = '?';
894 894
 			$e_reg = '';
895
-			$request_uri = esc_url( $_SERVER['REQUEST_URI'] );
896
-			$ru_bits = explode( '?', $request_uri );
895
+			$request_uri = esc_url($_SERVER['REQUEST_URI']);
896
+			$ru_bits = explode('?', $request_uri);
897 897
 			$request_uri = $ru_bits[0];
898 898
 			// check for and grab host as well
899
-			if ( isset( $_SERVER['HTTP_HOST'] )) {
900
-				$http_host = esc_url( $_SERVER['HTTP_HOST'] );
899
+			if (isset($_SERVER['HTTP_HOST'])) {
900
+				$http_host = esc_url($_SERVER['HTTP_HOST']);
901 901
 			}
902 902
 			// check for page_id in SERVER REQUEST
903
-			if ( isset( $_REQUEST['page_id'] )) {
903
+			if (isset($_REQUEST['page_id'])) {
904 904
 				// rebuild $e_reg without any of the extra parameters
905
-				$page_id = '?page_id=' . esc_attr( $_REQUEST['page_id'] ) . '&amp;';
905
+				$page_id = '?page_id='.esc_attr($_REQUEST['page_id']).'&amp;';
906 906
 			}
907 907
 			// check for $e_reg in SERVER REQUEST
908
-			if ( isset( $_REQUEST['ee'] )) {
908
+			if (isset($_REQUEST['ee'])) {
909 909
 				// rebuild $e_reg without any of the extra parameters
910
-				$e_reg = 'ee=' . esc_attr( $_REQUEST['ee'] );
910
+				$e_reg = 'ee='.esc_attr($_REQUEST['ee']);
911 911
 			}
912
-			$page_visit = rtrim( $http_host . $request_uri . $page_id . $e_reg, '?' );
912
+			$page_visit = rtrim($http_host.$request_uri.$page_id.$e_reg, '?');
913 913
 		}
914
-		return $page_visit !== home_url( '/wp-admin/admin-ajax.php' ) ? $page_visit : '';
914
+		return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
915 915
 
916 916
 	}
917 917
 
@@ -941,14 +941,14 @@  discard block
 block discarded – undo
941 941
       * @return void
942 942
       * @throws \EE_Error
943 943
       */
944
-	public function clear_session( $class = '', $function = '' ) {
944
+	public function clear_session($class = '', $function = '') {
945 945
 		//echo '<h3 style="color:#999;line-height:.9em;"><span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/><span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b></h3>';
946
-        do_action( 'AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' .  $function . '()' );
946
+        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : '.$class.'::'.$function.'()');
947 947
 		$this->reset_cart();
948 948
 		$this->reset_checkout();
949 949
 		$this->reset_transaction();
950 950
 		// wipe out everything that isn't a default session datum
951
-		$this->reset_data( array_keys( $this->_session_data ));
951
+		$this->reset_data(array_keys($this->_session_data));
952 952
 		// reset initial site access time and the session expiration
953 953
 		$this->_set_init_access_and_expiration();
954 954
 		$this->_save_session_to_db();
@@ -963,42 +963,42 @@  discard block
 block discarded – undo
963 963
 	  * @param bool  $show_all_notices
964 964
 	  * @return TRUE on success, FALSE on fail
965 965
 	  */
966
-	public function reset_data( $data_to_reset = array(), $show_all_notices = FALSE ) {
966
+	public function reset_data($data_to_reset = array(), $show_all_notices = FALSE) {
967 967
 		// if $data_to_reset is not in an array, then put it in one
968
-		if ( ! is_array( $data_to_reset ) ) {
969
-			$data_to_reset = array ( $data_to_reset );
968
+		if ( ! is_array($data_to_reset)) {
969
+			$data_to_reset = array($data_to_reset);
970 970
 		}
971 971
 		// nothing ??? go home!
972
-		if ( empty( $data_to_reset )) {
973
-			EE_Error::add_error( __( 'No session data could be reset, because no session var name was provided.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
972
+		if (empty($data_to_reset)) {
973
+			EE_Error::add_error(__('No session data could be reset, because no session var name was provided.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
974 974
 			return FALSE;
975 975
 		}
976 976
 		$return_value = TRUE;
977 977
 		// since $data_to_reset is an array, cycle through the values
978
-		foreach ( $data_to_reset as $reset ) {
978
+		foreach ($data_to_reset as $reset) {
979 979
 
980 980
 			// first check to make sure it is a valid session var
981
-			if ( isset( $this->_session_data[ $reset ] )) {
981
+			if (isset($this->_session_data[$reset])) {
982 982
 				// then check to make sure it is not a default var
983
-				if ( ! array_key_exists( $reset, $this->_default_session_vars )) {
983
+				if ( ! array_key_exists($reset, $this->_default_session_vars)) {
984 984
 					// remove session var
985
-					unset( $this->_session_data[ $reset ] );
986
-					if ( $show_all_notices ) {
987
-						EE_Error::add_success( sprintf( __( 'The session variable %s was removed.', 'event_espresso' ), $reset ), __FILE__, __FUNCTION__, __LINE__ );
985
+					unset($this->_session_data[$reset]);
986
+					if ($show_all_notices) {
987
+						EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
988 988
 					}
989
-					$return_value = !isset($return_value) ? TRUE : $return_value;
989
+					$return_value = ! isset($return_value) ? TRUE : $return_value;
990 990
 
991 991
 				} else {
992 992
 					// yeeeeeeeeerrrrrrrrrrr OUT !!!!
993
-					if ( $show_all_notices ) {
994
-						EE_Error::add_error( sprintf( __( 'Sorry! %s is a default session datum and can not be reset.', 'event_espresso' ), $reset ), __FILE__, __FUNCTION__, __LINE__ );
993
+					if ($show_all_notices) {
994
+						EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.', 'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
995 995
 					}
996 996
 					$return_value = FALSE;
997 997
 				}
998 998
 
999
-			} else if ( $show_all_notices ) {
999
+			} else if ($show_all_notices) {
1000 1000
 				// oops! that session var does not exist!
1001
-				EE_Error::add_error( sprintf( __( 'The session item provided, %s, is invalid or does not exist.', 'event_espresso' ), $reset ), __FILE__, __FUNCTION__, __LINE__ );
1001
+				EE_Error::add_error(sprintf(__('The session item provided, %s, is invalid or does not exist.', 'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1002 1002
 				$return_value = FALSE;
1003 1003
 			}
1004 1004
 
@@ -1017,8 +1017,8 @@  discard block
 block discarded – undo
1017 1017
       * @throws \EE_Error
1018 1018
       */
1019 1019
 	public function wp_loaded() {
1020
-		if ( isset(  EE_Registry::instance()->REQ ) && EE_Registry::instance()->REQ->is_set( 'clear_session' )) {
1021
-			$this->clear_session( __CLASS__, __FUNCTION__ );
1020
+		if (isset(EE_Registry::instance()->REQ) && EE_Registry::instance()->REQ->is_set('clear_session')) {
1021
+			$this->clear_session(__CLASS__, __FUNCTION__);
1022 1022
 		}
1023 1023
 	}
1024 1024
 
@@ -1054,7 +1054,7 @@  discard block
 block discarded – undo
1054 1054
              // or use that for the new transient cleanup query limit
1055 1055
              add_filter(
1056 1056
                  'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1057
-                 function () use ($expired_session_transient_delete_query_limit) {
1057
+                 function() use ($expired_session_transient_delete_query_limit) {
1058 1058
                      return $expired_session_transient_delete_query_limit;
1059 1059
                  }
1060 1060
              );
@@ -1068,34 +1068,34 @@  discard block
 block discarded – undo
1068 1068
 	  * @param $data1
1069 1069
 	  * @return string
1070 1070
 	  */
1071
-	 private function find_serialize_error( $data1 ) {
1071
+	 private function find_serialize_error($data1) {
1072 1072
 		$error = '<pre>';
1073 1073
 		 $data2 = preg_replace_callback(
1074 1074
 			 '!s:(\d+):"(.*?)";!',
1075
-			 function ( $match ) {
1076
-				 return ( $match[1] === strlen( $match[2] ) )
1075
+			 function($match) {
1076
+				 return ($match[1] === strlen($match[2]))
1077 1077
 					 ? $match[0]
1078 1078
 					 : 's:'
1079
-					   . strlen( $match[2] )
1079
+					   . strlen($match[2])
1080 1080
 					   . ':"'
1081 1081
 					   . $match[2]
1082 1082
 					   . '";';
1083 1083
 			 },
1084 1084
 			 $data1
1085 1085
 		 );
1086
-		$max = ( strlen( $data1 ) > strlen( $data2 ) ) ? strlen( $data1 ) : strlen( $data2 );
1087
-		$error .= $data1 . PHP_EOL;
1088
-		$error .= $data2 . PHP_EOL;
1089
-		for ( $i = 0; $i < $max; $i++ ) {
1090
-			if ( @$data1[ $i ] !== @$data2[ $i ] ) {
1091
-				$error .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1092
-				$error .= "\t-> ORD number " . ord( @$data1[ $i ] ) . ' != ' . ord( @$data2[ $i ] ) . PHP_EOL;
1093
-				$error .= "\t-> Line Number = $i" . PHP_EOL;
1094
-				$start = ( $i - 20 );
1095
-				$start = ( $start < 0 ) ? 0 : $start;
1086
+		$max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1087
+		$error .= $data1.PHP_EOL;
1088
+		$error .= $data2.PHP_EOL;
1089
+		for ($i = 0; $i < $max; $i++) {
1090
+			if (@$data1[$i] !== @$data2[$i]) {
1091
+				$error .= 'Difference '.@$data1[$i].' != '.@$data2[$i].PHP_EOL;
1092
+				$error .= "\t-> ORD number ".ord(@$data1[$i]).' != '.ord(@$data2[$i]).PHP_EOL;
1093
+				$error .= "\t-> Line Number = $i".PHP_EOL;
1094
+				$start = ($i - 20);
1095
+				$start = ($start < 0) ? 0 : $start;
1096 1096
 				$length = 40;
1097 1097
 				$point = $max - $i;
1098
-				if ( $point < 20 ) {
1098
+				if ($point < 20) {
1099 1099
 					$rlength = 1;
1100 1100
 					$rpoint = -$point;
1101 1101
 				} else {
@@ -1104,16 +1104,16 @@  discard block
 block discarded – undo
1104 1104
 				}
1105 1105
 				$error .= "\t-> Section Data1  = ";
1106 1106
 				$error .= substr_replace(
1107
-					substr( $data1, $start, $length ),
1108
-					"<b style=\"color:green\">{$data1[ $i ]}</b>",
1107
+					substr($data1, $start, $length),
1108
+					"<b style=\"color:green\">{$data1[$i]}</b>",
1109 1109
 					$rpoint,
1110 1110
 					$rlength
1111 1111
 				);
1112 1112
 				$error .= PHP_EOL;
1113 1113
 				$error .= "\t-> Section Data2  = ";
1114 1114
 				$error .= substr_replace(
1115
-					substr( $data2, $start, $length ),
1116
-					"<b style=\"color:red\">{$data2[ $i ]}</b>",
1115
+					substr($data2, $start, $length),
1116
+					"<b style=\"color:red\">{$data2[$i]}</b>",
1117 1117
 					$rpoint,
1118 1118
 					$rlength
1119 1119
 				);
Please login to merge, or discard this patch.
core/services/cache/TransientCacheStorage.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -234,7 +234,7 @@
 block discarded – undo
234 234
     /**
235 235
      * delete multiple transients and remove tracking
236 236
      *
237
-     * @param array $transient_keys [required] array of full or partial transient keys to be deleted
237
+     * @param string[] $transient_keys [required] array of full or partial transient keys to be deleted
238 238
      */
239 239
     public function deleteMany(array $transient_keys)
240 240
     {
Please login to merge, or discard this patch.
Unused Use Statements   -4 removed lines patch added patch discarded remove patch
@@ -1,10 +1,6 @@
 block discarded – undo
1 1
 <?php
2 2
 namespace EventEspresso\core\services\cache;
3 3
 
4
-use EE_Error;
5
-use WP_Error;
6
-use wpdb;
7
-
8 4
 defined('EVENT_ESPRESSO_VERSION') || exit;
9 5
 
10 6
 
Please login to merge, or discard this patch.
Indentation   +355 added lines, -355 removed lines patch added patch discarded remove patch
@@ -23,361 +23,361 @@
 block discarded – undo
23 23
 class TransientCacheStorage implements CacheStorageInterface
24 24
 {
25 25
 
26
-    /**
27
-     * wp-option option_name for tracking transients
28
-     *
29
-     * @type string
30
-     */
31
-    const TRANSIENT_SCHEDULE_OPTIONS_KEY = 'ee_transient_schedule';
32
-
33
-    /**
34
-     * @var int $current_time
35
-     */
36
-    private $current_time = 0;
37
-
38
-    /**
39
-     * how often to perform transient cleanup
40
-     *
41
-     * @var string $transient_cleanup_frequency
42
-     */
43
-    private $transient_cleanup_frequency = 'hour';
44
-
45
-    /**
46
-     * options for how often to perform transient cleanup
47
-     *
48
-     * @var array $transient_cleanup_frequency_options
49
-     */
50
-    private $transient_cleanup_frequency_options = array();
51
-
52
-    /**
53
-     * @var array $transients
54
-     */
55
-    private $transients = array();
56
-
57
-
58
-
59
-    /**
60
-     * TransientCacheStorage constructor.
61
-     */
62
-    public function __construct()
63
-    {
64
-        $this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
65
-        // round current time down to closest 5 minutes to simplify scheduling
66
-        $this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
67
-        $this->transients = (array)get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
68
-        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
69
-            add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
70
-        }
71
-    }
72
-
73
-
74
-
75
-    /**
76
-     * Sets how often transient cleanup occurs
77
-     *
78
-     * @return int
79
-     */
80
-    private function setTransientCleanupFrequency()
81
-    {
82
-        // sets how often transients are cleaned up
83
-        $this->transient_cleanup_frequency_options = apply_filters(
84
-            'FHEE__TransientCacheStorage__transient_cleanup_schedule_options',
85
-            array(
86
-                'off',
87
-                '15-minutes',
88
-                'hour',
89
-                '12-hours',
90
-                'day',
91
-            )
92
-        );
93
-        $transient_cleanup_frequency = apply_filters(
94
-            'FHEE__TransientCacheStorage__transient_cleanup_schedule',
95
-            'hour'
96
-        );
97
-        return in_array(
98
-            $transient_cleanup_frequency,
99
-            $this->transient_cleanup_frequency_options,
100
-            true
101
-        )
102
-            ? $transient_cleanup_frequency
103
-            : 'hour';
104
-    }
105
-
106
-
107
-
108
-    /**
109
-     * we need to be able to round timestamps off to match the set transient cleanup frequency
110
-     * so if a transient is set to expire at 1:17 pm for example, and our cleanup schedule is every hour,
111
-     * then that timestamp needs to be rounded up to 2:00 pm so that it is removed
112
-     * during the next scheduled cleanup after its expiration.
113
-     * We also round off the current time timestamp to the closest 5 minutes
114
-     * just to make the timestamps a little easier to round which helps with debugging.
115
-     *
116
-     * @param int    $timestamp [required]
117
-     * @param string $cleanup_frequency
118
-     * @param bool   $round_up
119
-     * @return false|int
120
-     */
121
-    private function roundTimestamp($timestamp, $cleanup_frequency = 'hour', $round_up = true)
122
-    {
123
-        $cleanup_frequency = $cleanup_frequency ? $cleanup_frequency : $this->transient_cleanup_frequency;
124
-        // in order to round the time to the closest xx minutes (or hours),
125
-        // we take the minutes (or hours) portion of the timestamp and divide it by xx,
126
-        // round down to a whole number, then multiply by xx to bring us almost back up to where we were
127
-        // why round down ? so the minutes (or hours) don't go over 60 (or 24)
128
-        // and bump the hour, which could bump the day, which could bump the month, etc,
129
-        // which would be bad because we don't always want to round up,
130
-        // but when we do we can easily achieve that by simply adding the desired offset,
131
-        $minutes = '00';
132
-        $hours = 'H';
133
-        switch ($cleanup_frequency) {
134
-            case '5-minutes' :
135
-                $minutes = floor((int)date('i', $timestamp) / 5) * 5;
136
-                $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
137
-                $offset = MINUTE_IN_SECONDS * 5;
138
-                break;
139
-            case '15-minutes' :
140
-                $minutes = floor((int)date('i', $timestamp) / 15) * 15;
141
-                $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
142
-                $offset = MINUTE_IN_SECONDS * 15;
143
-                break;
144
-            case '12-hours' :
145
-                $hours = floor((int)date('H', $timestamp) / 12) * 12;
146
-                $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
147
-                $offset = HOUR_IN_SECONDS * 12;
148
-                break;
149
-            case 'day' :
150
-                $hours = '03'; // run cleanup at 3:00 am (or first site hit after that)
151
-                $offset = DAY_IN_SECONDS;
152
-                break;
153
-            case 'hour' :
154
-            default :
155
-                $offset = HOUR_IN_SECONDS;
156
-                break;
157
-        }
158
-        $rounded_timestamp = strtotime(date("Y-m-d {$hours}:{$minutes}:00", $timestamp));
159
-        $rounded_timestamp += $round_up ? $offset : 0;
160
-        return apply_filters(
161
-            'FHEE__TransientCacheStorage__roundTimestamp__timestamp',
162
-            $rounded_timestamp,
163
-            $timestamp,
164
-            $cleanup_frequency,
165
-            $round_up
166
-        );
167
-    }
168
-
169
-
170
-
171
-    /**
172
-     * Saves supplied data to a transient
173
-     * if an expiration is set, then it automatically schedules the transient for cleanup
174
-     *
175
-     * @param string $transient_key [required]
176
-     * @param string $data          [required]
177
-     * @param int    $expiration    number of seconds until the cache expires
178
-     * @return bool
179
-     */
180
-    public function add($transient_key, $data, $expiration = 0)
181
-    {
182
-        $expiration = (int)abs($expiration);
183
-        $saved = set_transient($transient_key, $data, $expiration);
184
-        if ($saved && $expiration) {
185
-            $this->scheduleTransientCleanup($transient_key, $expiration);
186
-        }
187
-        return $saved;
188
-    }
189
-
190
-
191
-
192
-    /**
193
-     * retrieves transient data
194
-     * automatically triggers early cache refresh for standard cache items
195
-     * in order to avoid cache stampedes on busy sites.
196
-     * For non-standard cache items like PHP Session data where early refreshing is not wanted,
197
-     * the $standard_cache parameter should be set to false when retrieving data
198
-     *
199
-     * @param string $transient_key [required]
200
-     * @param bool   $standard_cache
201
-     * @return mixed|null
202
-     */
203
-    public function get($transient_key, $standard_cache = true)
204
-    {
205
-        // to avoid cache stampedes (AKA:dogpiles) for standard cache items,
206
-        // check if known cache expires within the next minute,
207
-        // and if so, remove it from our tracking and and return nothing.
208
-        // this should trigger the cache content to be regenerated during this request,
209
-        // while allowing any following requests to still access the existing cache
210
-        // until it gets replaced with the refreshed content
211
-        if (
212
-            $standard_cache
213
-            && isset($this->transients[$transient_key])
214
-            && $this->transients[$transient_key] - time() <= MINUTE_IN_SECONDS
215
-        ) {
216
-            unset($this->transients[$transient_key]);
217
-            $this->updateTransients();
218
-            return null;
219
-        }
220
-        $content = get_transient($transient_key);
221
-        return $content !== false ? $content : null;
222
-    }
223
-
224
-
225
-
226
-    /**
227
-     * delete a single transient and remove tracking
228
-     *
229
-     * @param string $transient_key [required] full or partial transient key to be deleted
230
-     */
231
-    public function delete($transient_key)
232
-    {
233
-        $this->deleteMany(array($transient_key));
234
-    }
235
-
236
-
237
-
238
-    /**
239
-     * delete multiple transients and remove tracking
240
-     *
241
-     * @param array $transient_keys [required] array of full or partial transient keys to be deleted
242
-     */
243
-    public function deleteMany(array $transient_keys)
244
-    {
245
-        $full_transient_keys = array();
246
-        foreach ($this->transients as $transient_key => $expiration) {
247
-            foreach ($transient_keys as $transient_key_to_delete) {
248
-                if (strpos($transient_key, $transient_key_to_delete) !== false) {
249
-                    $full_transient_keys[] = $transient_key;
250
-                }
251
-            }
252
-        }
253
-        if ($this->deleteTransientKeys($full_transient_keys)) {
254
-            $this->updateTransients();
255
-        }
256
-    }
257
-
258
-
259
-
260
-    /**
261
-     * sorts transients numerically by timestamp
262
-     * then saves the transient schedule to a WP option
263
-     */
264
-    private function updateTransients()
265
-    {
266
-        asort($this->transients, SORT_NUMERIC);
267
-        update_option(
268
-            TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY,
269
-            $this->transients
270
-        );
271
-    }
272
-
273
-
274
-
275
-    /**
276
-     * schedules a transient for cleanup by adding it to the transient tracking
277
-     *
278
-     * @param string $transient_key [required]
279
-     * @param int    $expiration    [required]
280
-     */
281
-    private function scheduleTransientCleanup($transient_key, $expiration)
282
-    {
283
-        // make sure a valid future timestamp is set
284
-        $expiration += $expiration < time() ? time() : 0;
285
-        // and round to the closest 15 minutes
286
-        $expiration = $this->roundTimestamp($expiration);
287
-        // save transients to clear using their ID as the key to avoid duplicates
288
-        $this->transients[$transient_key] = $expiration;
289
-        $this->updateTransients();
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     * Since our tracked transients are sorted by their timestamps
296
-     * we can grab the first transient and see when it is scheduled for cleanup.
297
-     * If that timestamp is less than or equal to the current time,
298
-     * then cleanup is triggered
299
-     */
300
-    public function checkTransientCleanupSchedule()
301
-    {
302
-        if (empty($this->transients)) {
303
-            return;
304
-        }
305
-        // when do we run the next cleanup job?
306
-        reset($this->transients);
307
-        $next_scheduled_cleanup = current($this->transients);
308
-        // if the next cleanup job is scheduled for the current hour
309
-        if ($next_scheduled_cleanup <= $this->current_time) {
310
-            if ($this->cleanupExpiredTransients()) {
311
-                $this->updateTransients();
312
-            }
313
-        }
314
-    }
315
-
316
-
317
-
318
-    /**
319
-     * loops through the array of tracked transients,
320
-     * compiles a list of those that have expired, and sends that list off for deletion.
321
-     * Also removes any bad records from the transients array
322
-     *
323
-     * @return bool
324
-     */
325
-    private function cleanupExpiredTransients()
326
-    {
327
-        $update = false;
328
-        // filter the query limit. Set to 0 to turn off garbage collection
329
-        $limit = (int)abs(
330
-            apply_filters(
331
-                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
332
-                50
333
-            )
334
-        );
335
-        // non-zero LIMIT means take out the trash
336
-        if ($limit) {
337
-            $transient_keys = array();
338
-            foreach ($this->transients as $transient_key => $expiration) {
339
-                if ($expiration > $this->current_time) {
340
-                    continue;
341
-                }
342
-                if ( ! $expiration || ! $transient_key) {
343
-                    unset($this->transients[$transient_key]);
344
-                    $update = true;
345
-                    continue;
346
-                }
347
-                $transient_keys[] = $transient_key;
348
-            }
349
-            // delete expired keys, but maintain value of $update if nothing is deleted
350
-            $update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
351
-            do_action( 'FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
352
-        }
353
-        return $update;
354
-    }
355
-
356
-
357
-
358
-    /**
359
-     * calls delete_transient() on each transient key provided, up to the specified limit
360
-     *
361
-     * @param array $transient_keys [required]
362
-     * @param int   $limit
363
-     * @return bool
364
-     */
365
-    private function deleteTransientKeys(array $transient_keys, $limit = 50)
366
-    {
367
-        if (empty($transient_keys)) {
368
-            return false;
369
-        }
370
-        $counter = 0;
371
-        foreach ($transient_keys as $transient_key) {
372
-            if($counter === $limit){
373
-                break;
374
-            }
375
-            delete_transient($transient_key);
376
-            unset($this->transients[$transient_key]);
377
-            $counter++;
378
-        }
379
-        return $counter > 0;
380
-    }
26
+	/**
27
+	 * wp-option option_name for tracking transients
28
+	 *
29
+	 * @type string
30
+	 */
31
+	const TRANSIENT_SCHEDULE_OPTIONS_KEY = 'ee_transient_schedule';
32
+
33
+	/**
34
+	 * @var int $current_time
35
+	 */
36
+	private $current_time = 0;
37
+
38
+	/**
39
+	 * how often to perform transient cleanup
40
+	 *
41
+	 * @var string $transient_cleanup_frequency
42
+	 */
43
+	private $transient_cleanup_frequency = 'hour';
44
+
45
+	/**
46
+	 * options for how often to perform transient cleanup
47
+	 *
48
+	 * @var array $transient_cleanup_frequency_options
49
+	 */
50
+	private $transient_cleanup_frequency_options = array();
51
+
52
+	/**
53
+	 * @var array $transients
54
+	 */
55
+	private $transients = array();
56
+
57
+
58
+
59
+	/**
60
+	 * TransientCacheStorage constructor.
61
+	 */
62
+	public function __construct()
63
+	{
64
+		$this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
65
+		// round current time down to closest 5 minutes to simplify scheduling
66
+		$this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
67
+		$this->transients = (array)get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
68
+		if ( ! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
69
+			add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
70
+		}
71
+	}
72
+
73
+
74
+
75
+	/**
76
+	 * Sets how often transient cleanup occurs
77
+	 *
78
+	 * @return int
79
+	 */
80
+	private function setTransientCleanupFrequency()
81
+	{
82
+		// sets how often transients are cleaned up
83
+		$this->transient_cleanup_frequency_options = apply_filters(
84
+			'FHEE__TransientCacheStorage__transient_cleanup_schedule_options',
85
+			array(
86
+				'off',
87
+				'15-minutes',
88
+				'hour',
89
+				'12-hours',
90
+				'day',
91
+			)
92
+		);
93
+		$transient_cleanup_frequency = apply_filters(
94
+			'FHEE__TransientCacheStorage__transient_cleanup_schedule',
95
+			'hour'
96
+		);
97
+		return in_array(
98
+			$transient_cleanup_frequency,
99
+			$this->transient_cleanup_frequency_options,
100
+			true
101
+		)
102
+			? $transient_cleanup_frequency
103
+			: 'hour';
104
+	}
105
+
106
+
107
+
108
+	/**
109
+	 * we need to be able to round timestamps off to match the set transient cleanup frequency
110
+	 * so if a transient is set to expire at 1:17 pm for example, and our cleanup schedule is every hour,
111
+	 * then that timestamp needs to be rounded up to 2:00 pm so that it is removed
112
+	 * during the next scheduled cleanup after its expiration.
113
+	 * We also round off the current time timestamp to the closest 5 minutes
114
+	 * just to make the timestamps a little easier to round which helps with debugging.
115
+	 *
116
+	 * @param int    $timestamp [required]
117
+	 * @param string $cleanup_frequency
118
+	 * @param bool   $round_up
119
+	 * @return false|int
120
+	 */
121
+	private function roundTimestamp($timestamp, $cleanup_frequency = 'hour', $round_up = true)
122
+	{
123
+		$cleanup_frequency = $cleanup_frequency ? $cleanup_frequency : $this->transient_cleanup_frequency;
124
+		// in order to round the time to the closest xx minutes (or hours),
125
+		// we take the minutes (or hours) portion of the timestamp and divide it by xx,
126
+		// round down to a whole number, then multiply by xx to bring us almost back up to where we were
127
+		// why round down ? so the minutes (or hours) don't go over 60 (or 24)
128
+		// and bump the hour, which could bump the day, which could bump the month, etc,
129
+		// which would be bad because we don't always want to round up,
130
+		// but when we do we can easily achieve that by simply adding the desired offset,
131
+		$minutes = '00';
132
+		$hours = 'H';
133
+		switch ($cleanup_frequency) {
134
+			case '5-minutes' :
135
+				$minutes = floor((int)date('i', $timestamp) / 5) * 5;
136
+				$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
137
+				$offset = MINUTE_IN_SECONDS * 5;
138
+				break;
139
+			case '15-minutes' :
140
+				$minutes = floor((int)date('i', $timestamp) / 15) * 15;
141
+				$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
142
+				$offset = MINUTE_IN_SECONDS * 15;
143
+				break;
144
+			case '12-hours' :
145
+				$hours = floor((int)date('H', $timestamp) / 12) * 12;
146
+				$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
147
+				$offset = HOUR_IN_SECONDS * 12;
148
+				break;
149
+			case 'day' :
150
+				$hours = '03'; // run cleanup at 3:00 am (or first site hit after that)
151
+				$offset = DAY_IN_SECONDS;
152
+				break;
153
+			case 'hour' :
154
+			default :
155
+				$offset = HOUR_IN_SECONDS;
156
+				break;
157
+		}
158
+		$rounded_timestamp = strtotime(date("Y-m-d {$hours}:{$minutes}:00", $timestamp));
159
+		$rounded_timestamp += $round_up ? $offset : 0;
160
+		return apply_filters(
161
+			'FHEE__TransientCacheStorage__roundTimestamp__timestamp',
162
+			$rounded_timestamp,
163
+			$timestamp,
164
+			$cleanup_frequency,
165
+			$round_up
166
+		);
167
+	}
168
+
169
+
170
+
171
+	/**
172
+	 * Saves supplied data to a transient
173
+	 * if an expiration is set, then it automatically schedules the transient for cleanup
174
+	 *
175
+	 * @param string $transient_key [required]
176
+	 * @param string $data          [required]
177
+	 * @param int    $expiration    number of seconds until the cache expires
178
+	 * @return bool
179
+	 */
180
+	public function add($transient_key, $data, $expiration = 0)
181
+	{
182
+		$expiration = (int)abs($expiration);
183
+		$saved = set_transient($transient_key, $data, $expiration);
184
+		if ($saved && $expiration) {
185
+			$this->scheduleTransientCleanup($transient_key, $expiration);
186
+		}
187
+		return $saved;
188
+	}
189
+
190
+
191
+
192
+	/**
193
+	 * retrieves transient data
194
+	 * automatically triggers early cache refresh for standard cache items
195
+	 * in order to avoid cache stampedes on busy sites.
196
+	 * For non-standard cache items like PHP Session data where early refreshing is not wanted,
197
+	 * the $standard_cache parameter should be set to false when retrieving data
198
+	 *
199
+	 * @param string $transient_key [required]
200
+	 * @param bool   $standard_cache
201
+	 * @return mixed|null
202
+	 */
203
+	public function get($transient_key, $standard_cache = true)
204
+	{
205
+		// to avoid cache stampedes (AKA:dogpiles) for standard cache items,
206
+		// check if known cache expires within the next minute,
207
+		// and if so, remove it from our tracking and and return nothing.
208
+		// this should trigger the cache content to be regenerated during this request,
209
+		// while allowing any following requests to still access the existing cache
210
+		// until it gets replaced with the refreshed content
211
+		if (
212
+			$standard_cache
213
+			&& isset($this->transients[$transient_key])
214
+			&& $this->transients[$transient_key] - time() <= MINUTE_IN_SECONDS
215
+		) {
216
+			unset($this->transients[$transient_key]);
217
+			$this->updateTransients();
218
+			return null;
219
+		}
220
+		$content = get_transient($transient_key);
221
+		return $content !== false ? $content : null;
222
+	}
223
+
224
+
225
+
226
+	/**
227
+	 * delete a single transient and remove tracking
228
+	 *
229
+	 * @param string $transient_key [required] full or partial transient key to be deleted
230
+	 */
231
+	public function delete($transient_key)
232
+	{
233
+		$this->deleteMany(array($transient_key));
234
+	}
235
+
236
+
237
+
238
+	/**
239
+	 * delete multiple transients and remove tracking
240
+	 *
241
+	 * @param array $transient_keys [required] array of full or partial transient keys to be deleted
242
+	 */
243
+	public function deleteMany(array $transient_keys)
244
+	{
245
+		$full_transient_keys = array();
246
+		foreach ($this->transients as $transient_key => $expiration) {
247
+			foreach ($transient_keys as $transient_key_to_delete) {
248
+				if (strpos($transient_key, $transient_key_to_delete) !== false) {
249
+					$full_transient_keys[] = $transient_key;
250
+				}
251
+			}
252
+		}
253
+		if ($this->deleteTransientKeys($full_transient_keys)) {
254
+			$this->updateTransients();
255
+		}
256
+	}
257
+
258
+
259
+
260
+	/**
261
+	 * sorts transients numerically by timestamp
262
+	 * then saves the transient schedule to a WP option
263
+	 */
264
+	private function updateTransients()
265
+	{
266
+		asort($this->transients, SORT_NUMERIC);
267
+		update_option(
268
+			TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY,
269
+			$this->transients
270
+		);
271
+	}
272
+
273
+
274
+
275
+	/**
276
+	 * schedules a transient for cleanup by adding it to the transient tracking
277
+	 *
278
+	 * @param string $transient_key [required]
279
+	 * @param int    $expiration    [required]
280
+	 */
281
+	private function scheduleTransientCleanup($transient_key, $expiration)
282
+	{
283
+		// make sure a valid future timestamp is set
284
+		$expiration += $expiration < time() ? time() : 0;
285
+		// and round to the closest 15 minutes
286
+		$expiration = $this->roundTimestamp($expiration);
287
+		// save transients to clear using their ID as the key to avoid duplicates
288
+		$this->transients[$transient_key] = $expiration;
289
+		$this->updateTransients();
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 * Since our tracked transients are sorted by their timestamps
296
+	 * we can grab the first transient and see when it is scheduled for cleanup.
297
+	 * If that timestamp is less than or equal to the current time,
298
+	 * then cleanup is triggered
299
+	 */
300
+	public function checkTransientCleanupSchedule()
301
+	{
302
+		if (empty($this->transients)) {
303
+			return;
304
+		}
305
+		// when do we run the next cleanup job?
306
+		reset($this->transients);
307
+		$next_scheduled_cleanup = current($this->transients);
308
+		// if the next cleanup job is scheduled for the current hour
309
+		if ($next_scheduled_cleanup <= $this->current_time) {
310
+			if ($this->cleanupExpiredTransients()) {
311
+				$this->updateTransients();
312
+			}
313
+		}
314
+	}
315
+
316
+
317
+
318
+	/**
319
+	 * loops through the array of tracked transients,
320
+	 * compiles a list of those that have expired, and sends that list off for deletion.
321
+	 * Also removes any bad records from the transients array
322
+	 *
323
+	 * @return bool
324
+	 */
325
+	private function cleanupExpiredTransients()
326
+	{
327
+		$update = false;
328
+		// filter the query limit. Set to 0 to turn off garbage collection
329
+		$limit = (int)abs(
330
+			apply_filters(
331
+				'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
332
+				50
333
+			)
334
+		);
335
+		// non-zero LIMIT means take out the trash
336
+		if ($limit) {
337
+			$transient_keys = array();
338
+			foreach ($this->transients as $transient_key => $expiration) {
339
+				if ($expiration > $this->current_time) {
340
+					continue;
341
+				}
342
+				if ( ! $expiration || ! $transient_key) {
343
+					unset($this->transients[$transient_key]);
344
+					$update = true;
345
+					continue;
346
+				}
347
+				$transient_keys[] = $transient_key;
348
+			}
349
+			// delete expired keys, but maintain value of $update if nothing is deleted
350
+			$update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
351
+			do_action( 'FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
352
+		}
353
+		return $update;
354
+	}
355
+
356
+
357
+
358
+	/**
359
+	 * calls delete_transient() on each transient key provided, up to the specified limit
360
+	 *
361
+	 * @param array $transient_keys [required]
362
+	 * @param int   $limit
363
+	 * @return bool
364
+	 */
365
+	private function deleteTransientKeys(array $transient_keys, $limit = 50)
366
+	{
367
+		if (empty($transient_keys)) {
368
+			return false;
369
+		}
370
+		$counter = 0;
371
+		foreach ($transient_keys as $transient_key) {
372
+			if($counter === $limit){
373
+				break;
374
+			}
375
+			delete_transient($transient_key);
376
+			unset($this->transients[$transient_key]);
377
+			$counter++;
378
+		}
379
+		return $counter > 0;
380
+	}
381 381
 
382 382
 
383 383
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
         $this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
65 65
         // round current time down to closest 5 minutes to simplify scheduling
66 66
         $this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
67
-        $this->transients = (array)get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
67
+        $this->transients = (array) get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
68 68
         if ( ! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
69 69
             add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
70 70
         }
@@ -132,17 +132,17 @@  discard block
 block discarded – undo
132 132
         $hours = 'H';
133 133
         switch ($cleanup_frequency) {
134 134
             case '5-minutes' :
135
-                $minutes = floor((int)date('i', $timestamp) / 5) * 5;
135
+                $minutes = floor((int) date('i', $timestamp) / 5) * 5;
136 136
                 $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
137 137
                 $offset = MINUTE_IN_SECONDS * 5;
138 138
                 break;
139 139
             case '15-minutes' :
140
-                $minutes = floor((int)date('i', $timestamp) / 15) * 15;
140
+                $minutes = floor((int) date('i', $timestamp) / 15) * 15;
141 141
                 $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
142 142
                 $offset = MINUTE_IN_SECONDS * 15;
143 143
                 break;
144 144
             case '12-hours' :
145
-                $hours = floor((int)date('H', $timestamp) / 12) * 12;
145
+                $hours = floor((int) date('H', $timestamp) / 12) * 12;
146 146
                 $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
147 147
                 $offset = HOUR_IN_SECONDS * 12;
148 148
                 break;
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
      */
180 180
     public function add($transient_key, $data, $expiration = 0)
181 181
     {
182
-        $expiration = (int)abs($expiration);
182
+        $expiration = (int) abs($expiration);
183 183
         $saved = set_transient($transient_key, $data, $expiration);
184 184
         if ($saved && $expiration) {
185 185
             $this->scheduleTransientCleanup($transient_key, $expiration);
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
     {
327 327
         $update = false;
328 328
         // filter the query limit. Set to 0 to turn off garbage collection
329
-        $limit = (int)abs(
329
+        $limit = (int) abs(
330 330
             apply_filters(
331 331
                 'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
332 332
                 50
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
             }
349 349
             // delete expired keys, but maintain value of $update if nothing is deleted
350 350
             $update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
351
-            do_action( 'FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
351
+            do_action('FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
352 352
         }
353 353
         return $update;
354 354
     }
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
         }
370 370
         $counter = 0;
371 371
         foreach ($transient_keys as $transient_key) {
372
-            if($counter === $limit){
372
+            if ($counter === $limit) {
373 373
                 break;
374 374
             }
375 375
             delete_transient($transient_key);
Please login to merge, or discard this patch.
modules/events_archive/EventsArchiveIframe.php 2 patches
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\libraries\iframe_display\Iframe;
5 5
 
6 6
 if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
7
-    exit( 'No direct script access allowed' );
7
+	exit( 'No direct script access allowed' );
8 8
 }
9 9
 
10 10
 
@@ -21,57 +21,57 @@  discard block
 block discarded – undo
21 21
 
22 22
 
23 23
 
24
-    /**
25
-     * EventsArchiveIframe constructor.
26
-     *
27
-     * @param \EED_Events_Archive $EED_Events_Archive
28
-     * @throws \DomainException
29
-     */
30
-    public function __construct( $EED_Events_Archive )
31
-    {
32
-        \EE_Registry::instance()->REQ->set_espresso_page( true );
33
-        add_filter('FHEE__EED_Events_Archive__event_list_iframe', '__return_true');
34
-        $EED_Events_Archive->event_list();
35
-        /** @var \EventEspresso\core\domain\entities\shortcodes\EspressoEvents $event_list */
36
-        $event_list = \EE_Registry::instance()->create('EventEspresso\core\domain\entities\shortcodes\EspressoEvents');
37
-        parent::__construct(
38
-            esc_html__( 'Event List', 'event_espresso' ),
39
-            $event_list->processShortcode()
40
-        );
41
-        $this->addStylesheets(
42
-            apply_filters(
43
-                'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__css',
44
-                array(
45
-                    'espresso_default'           => is_readable( EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css' )
46
-                        ? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION
47
-                        : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION,
48
-                ),
49
-                $this
50
-            )
51
-        );
52
-        $this->addScripts(
53
-            apply_filters(
54
-                'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__js',
55
-                array(
56
-                    'gmap_api' => sprintf(
57
-                        'https://maps.googleapis.com/maps/api/js?key=%s',
58
-                        apply_filters(
59
-                            'FHEE__EEH_Maps__espresso_google_maps_js__api_key',
60
-                            \EE_Registry::instance()->CFG->map_settings->google_map_api_key
61
-                        )
62
-                    ),
63
-                    'ee_gmap'  => EE_HELPERS_ASSETS . 'ee_gmap.js?ver=1.0',
64
-                ),
65
-                $this
66
-            )
67
-        );
68
-        $this->addLocalizedVars(
69
-            array(
70
-                'ee_gmap' => \EEH_Maps::$gmap_vars,
71
-            ),
72
-            'ee_gmap_vars'
73
-        );
74
-    }
24
+	/**
25
+	 * EventsArchiveIframe constructor.
26
+	 *
27
+	 * @param \EED_Events_Archive $EED_Events_Archive
28
+	 * @throws \DomainException
29
+	 */
30
+	public function __construct( $EED_Events_Archive )
31
+	{
32
+		\EE_Registry::instance()->REQ->set_espresso_page( true );
33
+		add_filter('FHEE__EED_Events_Archive__event_list_iframe', '__return_true');
34
+		$EED_Events_Archive->event_list();
35
+		/** @var \EventEspresso\core\domain\entities\shortcodes\EspressoEvents $event_list */
36
+		$event_list = \EE_Registry::instance()->create('EventEspresso\core\domain\entities\shortcodes\EspressoEvents');
37
+		parent::__construct(
38
+			esc_html__( 'Event List', 'event_espresso' ),
39
+			$event_list->processShortcode()
40
+		);
41
+		$this->addStylesheets(
42
+			apply_filters(
43
+				'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__css',
44
+				array(
45
+					'espresso_default'           => is_readable( EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css' )
46
+						? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION
47
+						: EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION,
48
+				),
49
+				$this
50
+			)
51
+		);
52
+		$this->addScripts(
53
+			apply_filters(
54
+				'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__js',
55
+				array(
56
+					'gmap_api' => sprintf(
57
+						'https://maps.googleapis.com/maps/api/js?key=%s',
58
+						apply_filters(
59
+							'FHEE__EEH_Maps__espresso_google_maps_js__api_key',
60
+							\EE_Registry::instance()->CFG->map_settings->google_map_api_key
61
+						)
62
+					),
63
+					'ee_gmap'  => EE_HELPERS_ASSETS . 'ee_gmap.js?ver=1.0',
64
+				),
65
+				$this
66
+			)
67
+		);
68
+		$this->addLocalizedVars(
69
+			array(
70
+				'ee_gmap' => \EEH_Maps::$gmap_vars,
71
+			),
72
+			'ee_gmap_vars'
73
+		);
74
+	}
75 75
 
76 76
 
77 77
 
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -3,8 +3,8 @@  discard block
 block discarded – undo
3 3
 
4 4
 use EventEspresso\core\libraries\iframe_display\Iframe;
5 5
 
6
-if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
7
-    exit( 'No direct script access allowed' );
6
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
7
+    exit('No direct script access allowed');
8 8
 }
9 9
 
10 10
 
@@ -27,24 +27,24 @@  discard block
 block discarded – undo
27 27
      * @param \EED_Events_Archive $EED_Events_Archive
28 28
      * @throws \DomainException
29 29
      */
30
-    public function __construct( $EED_Events_Archive )
30
+    public function __construct($EED_Events_Archive)
31 31
     {
32
-        \EE_Registry::instance()->REQ->set_espresso_page( true );
32
+        \EE_Registry::instance()->REQ->set_espresso_page(true);
33 33
         add_filter('FHEE__EED_Events_Archive__event_list_iframe', '__return_true');
34 34
         $EED_Events_Archive->event_list();
35 35
         /** @var \EventEspresso\core\domain\entities\shortcodes\EspressoEvents $event_list */
36 36
         $event_list = \EE_Registry::instance()->create('EventEspresso\core\domain\entities\shortcodes\EspressoEvents');
37 37
         parent::__construct(
38
-            esc_html__( 'Event List', 'event_espresso' ),
38
+            esc_html__('Event List', 'event_espresso'),
39 39
             $event_list->processShortcode()
40 40
         );
41 41
         $this->addStylesheets(
42 42
             apply_filters(
43 43
                 'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__css',
44 44
                 array(
45
-                    'espresso_default'           => is_readable( EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css' )
46
-                        ? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION
47
-                        : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css?ver=' . EVENT_ESPRESSO_VERSION,
45
+                    'espresso_default'           => is_readable(EVENT_ESPRESSO_UPLOAD_DIR.'css/style.css')
46
+                        ? EVENT_ESPRESSO_UPLOAD_DIR.'css/espresso_default.css?ver='.EVENT_ESPRESSO_VERSION
47
+                        : EE_GLOBAL_ASSETS_URL.'css/espresso_default.css?ver='.EVENT_ESPRESSO_VERSION,
48 48
                 ),
49 49
                 $this
50 50
             )
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
                             \EE_Registry::instance()->CFG->map_settings->google_map_api_key
61 61
                         )
62 62
                     ),
63
-                    'ee_gmap'  => EE_HELPERS_ASSETS . 'ee_gmap.js?ver=1.0',
63
+                    'ee_gmap'  => EE_HELPERS_ASSETS.'ee_gmap.js?ver=1.0',
64 64
                 ),
65 65
                 $this
66 66
             )
Please login to merge, or discard this patch.
core/services/cache/PostRelatedCacheManager.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
      */
72 72
     public function clearPostRelatedCacheOnUpdate($post_ID, $id_prefix)
73 73
     {
74
-        $post_related_cache = (array)get_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, array());
74
+        $post_related_cache = (array) get_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, array());
75 75
         // if post is not already being tracked
76 76
         if ( ! isset($post_related_cache[$post_ID])) {
77 77
             // add array to add cache ids to
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
      */
93 93
     public function clearPostRelatedCache($post_ID)
94 94
     {
95
-        $post_related_cache = (array)get_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, array());
95
+        $post_related_cache = (array) get_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, array());
96 96
         // if post is not being tracked
97 97
         if ( ! isset($post_related_cache[$post_ID])) {
98 98
             return;
Please login to merge, or discard this patch.
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -18,93 +18,93 @@
 block discarded – undo
18 18
 class PostRelatedCacheManager extends BasicCacheManager
19 19
 {
20 20
 
21
-    /**
22
-     * @type string
23
-     */
24
-    const POST_CACHE_PREFIX = 'ee_cache_post_';
25
-
26
-    /**
27
-     * wp-option option_name for tracking post related cache
28
-     *
29
-     * @type string
30
-     */
31
-    const POST_CACHE_OPTIONS_KEY = 'ee_post_cache';
32
-
33
-
34
-
35
-    /**
36
-     * PostRelatedCacheManager constructor.
37
-     *
38
-     * @param CacheStorageInterface      $cache_storage
39
-     * @param SessionIdentifierInterface $session
40
-     */
41
-    public function __construct(CacheStorageInterface $cache_storage, SessionIdentifierInterface $session)
42
-    {
43
-        parent::__construct($cache_storage, $session);
44
-        add_action('save_post', array($this, 'clearPostRelatedCache'));
45
-    }
46
-
47
-
48
-
49
-    /**
50
-     * returns a string that will be prepended to all cache identifiers
51
-     *
52
-     * @return string
53
-     */
54
-    public function cachePrefix()
55
-    {
56
-        return PostRelatedCacheManager::POST_CACHE_PREFIX;
57
-    }
58
-
59
-
60
-
61
-    /**
62
-     * If you are caching content that pertains to a Post of any type,
63
-     * then it is recommended to pass the post id and cache id prefix to this method
64
-     * so that it can be added to the post related cache tracking.
65
-     * Then, whenever that post is updated, the cache will automatically be deleted,
66
-     * which helps to ensure that outdated cache content will not be served
67
-     *
68
-     * @param int    $post_ID    [required]
69
-     * @param string $id_prefix  [required] Appended to all cache IDs. Can be helpful in finding specific cache types.
70
-     *                           May also be helpful to include an additional specific identifier,
71
-     *                           such as a post ID as part of the $id_prefix so that individual caches
72
-     *                           can be found and/or cleared. ex: "venue-28", or "shortcode-156".
73
-     *                           BasicCacheManager::CACHE_PREFIX will also be prepended to the cache id.
74
-     */
75
-    public function clearPostRelatedCacheOnUpdate($post_ID, $id_prefix)
76
-    {
77
-        $post_related_cache = (array)get_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, array());
78
-        // if post is not already being tracked
79
-        if ( ! isset($post_related_cache[$post_ID])) {
80
-            // add array to add cache ids to
81
-            $post_related_cache[$post_ID] = array();
82
-        }
83
-        // add cache id to be tracked
84
-        $post_related_cache[$post_ID][] = $id_prefix;
85
-        update_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, $post_related_cache);
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     * callback hooked into the WordPress "save_post" action
92
-     * deletes any cache content associated with the post
93
-     *
94
-     * @param int $post_ID [required]
95
-     */
96
-    public function clearPostRelatedCache($post_ID)
97
-    {
98
-        $post_related_cache = (array)get_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, array());
99
-        // if post is not being tracked
100
-        if ( ! isset($post_related_cache[$post_ID])) {
101
-            return;
102
-        }
103
-        // get cache id prefixes for post, and delete their corresponding transients
104
-        $this->clear($post_related_cache[$post_ID]);
105
-        unset($post_related_cache[$post_ID]);
106
-        update_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, $post_related_cache);
107
-    }
21
+	/**
22
+	 * @type string
23
+	 */
24
+	const POST_CACHE_PREFIX = 'ee_cache_post_';
25
+
26
+	/**
27
+	 * wp-option option_name for tracking post related cache
28
+	 *
29
+	 * @type string
30
+	 */
31
+	const POST_CACHE_OPTIONS_KEY = 'ee_post_cache';
32
+
33
+
34
+
35
+	/**
36
+	 * PostRelatedCacheManager constructor.
37
+	 *
38
+	 * @param CacheStorageInterface      $cache_storage
39
+	 * @param SessionIdentifierInterface $session
40
+	 */
41
+	public function __construct(CacheStorageInterface $cache_storage, SessionIdentifierInterface $session)
42
+	{
43
+		parent::__construct($cache_storage, $session);
44
+		add_action('save_post', array($this, 'clearPostRelatedCache'));
45
+	}
46
+
47
+
48
+
49
+	/**
50
+	 * returns a string that will be prepended to all cache identifiers
51
+	 *
52
+	 * @return string
53
+	 */
54
+	public function cachePrefix()
55
+	{
56
+		return PostRelatedCacheManager::POST_CACHE_PREFIX;
57
+	}
58
+
59
+
60
+
61
+	/**
62
+	 * If you are caching content that pertains to a Post of any type,
63
+	 * then it is recommended to pass the post id and cache id prefix to this method
64
+	 * so that it can be added to the post related cache tracking.
65
+	 * Then, whenever that post is updated, the cache will automatically be deleted,
66
+	 * which helps to ensure that outdated cache content will not be served
67
+	 *
68
+	 * @param int    $post_ID    [required]
69
+	 * @param string $id_prefix  [required] Appended to all cache IDs. Can be helpful in finding specific cache types.
70
+	 *                           May also be helpful to include an additional specific identifier,
71
+	 *                           such as a post ID as part of the $id_prefix so that individual caches
72
+	 *                           can be found and/or cleared. ex: "venue-28", or "shortcode-156".
73
+	 *                           BasicCacheManager::CACHE_PREFIX will also be prepended to the cache id.
74
+	 */
75
+	public function clearPostRelatedCacheOnUpdate($post_ID, $id_prefix)
76
+	{
77
+		$post_related_cache = (array)get_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, array());
78
+		// if post is not already being tracked
79
+		if ( ! isset($post_related_cache[$post_ID])) {
80
+			// add array to add cache ids to
81
+			$post_related_cache[$post_ID] = array();
82
+		}
83
+		// add cache id to be tracked
84
+		$post_related_cache[$post_ID][] = $id_prefix;
85
+		update_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, $post_related_cache);
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 * callback hooked into the WordPress "save_post" action
92
+	 * deletes any cache content associated with the post
93
+	 *
94
+	 * @param int $post_ID [required]
95
+	 */
96
+	public function clearPostRelatedCache($post_ID)
97
+	{
98
+		$post_related_cache = (array)get_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, array());
99
+		// if post is not being tracked
100
+		if ( ! isset($post_related_cache[$post_ID])) {
101
+			return;
102
+		}
103
+		// get cache id prefixes for post, and delete their corresponding transients
104
+		$this->clear($post_related_cache[$post_ID]);
105
+		unset($post_related_cache[$post_ID]);
106
+		update_option(PostRelatedCacheManager::POST_CACHE_OPTIONS_KEY, $post_related_cache);
107
+	}
108 108
 
109 109
 
110 110
 }
Please login to merge, or discard this patch.
core/services/cache/CacheManagerInterface.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -18,43 +18,43 @@
 block discarded – undo
18 18
 interface CacheManagerInterface
19 19
 {
20 20
 
21
-    /**
22
-     * returns a string that will be prepended to all cache identifiers
23
-     *
24
-     * @return string
25
-     */
26
-    public function cachePrefix();
27
-
28
-
29
-
30
-    /**
31
-     * @param string  $id_prefix [required] Prepended to all cache IDs. Can be helpful in finding specific cache types.
32
-     *                           May also be helpful to include an additional specific identifier,
33
-     *                           such as a post ID as part of the $id_prefix so that individual caches
34
-     *                           can be found and/or cleared. ex: "venue-28", or "shortcode-156".
35
-     *                           BasicCacheManager::CACHE_PREFIX will also be prepended to the cache id.
36
-     * @param string  $cache_id  [required] Additional identifying details that make this cache unique.
37
-     *                           It is advisable to use some of the actual data
38
-     *                           that is used to generate the content being cached,
39
-     *                           in order to guarantee that the cache id is unique for that content.
40
-     *                           The cache id will be md5'd before usage to make it more db friendly,
41
-     *                           and the entire cache id string will be truncated to 190 characters.
42
-     * @param Closure $callback  [required] since the point of caching is to avoid generating content when not
43
-     *                           necessary,
44
-     *                           we wrap our content creation in a Closure so that it is not executed until needed.
45
-     * @param int     $expiration
46
-     * @return Closure|mixed
47
-     */
48
-    public function get($id_prefix, $cache_id, Closure $callback, $expiration = HOUR_IN_SECONDS);
49
-
50
-
51
-
52
-    /**
53
-     * @param array|string $cache_id [required] Could be an ID prefix affecting many caches
54
-     *                               or a specific ID targeting a single cache item
55
-     * @return void
56
-     */
57
-    public function clear($cache_id);
21
+	/**
22
+	 * returns a string that will be prepended to all cache identifiers
23
+	 *
24
+	 * @return string
25
+	 */
26
+	public function cachePrefix();
27
+
28
+
29
+
30
+	/**
31
+	 * @param string  $id_prefix [required] Prepended to all cache IDs. Can be helpful in finding specific cache types.
32
+	 *                           May also be helpful to include an additional specific identifier,
33
+	 *                           such as a post ID as part of the $id_prefix so that individual caches
34
+	 *                           can be found and/or cleared. ex: "venue-28", or "shortcode-156".
35
+	 *                           BasicCacheManager::CACHE_PREFIX will also be prepended to the cache id.
36
+	 * @param string  $cache_id  [required] Additional identifying details that make this cache unique.
37
+	 *                           It is advisable to use some of the actual data
38
+	 *                           that is used to generate the content being cached,
39
+	 *                           in order to guarantee that the cache id is unique for that content.
40
+	 *                           The cache id will be md5'd before usage to make it more db friendly,
41
+	 *                           and the entire cache id string will be truncated to 190 characters.
42
+	 * @param Closure $callback  [required] since the point of caching is to avoid generating content when not
43
+	 *                           necessary,
44
+	 *                           we wrap our content creation in a Closure so that it is not executed until needed.
45
+	 * @param int     $expiration
46
+	 * @return Closure|mixed
47
+	 */
48
+	public function get($id_prefix, $cache_id, Closure $callback, $expiration = HOUR_IN_SECONDS);
49
+
50
+
51
+
52
+	/**
53
+	 * @param array|string $cache_id [required] Could be an ID prefix affecting many caches
54
+	 *                               or a specific ID targeting a single cache item
55
+	 * @return void
56
+	 */
57
+	public function clear($cache_id);
58 58
 
59 59
 }
60 60
 // End of file CacheManagerInterface.php
Please login to merge, or discard this patch.
core/services/cache/CacheStorageInterface.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -15,49 +15,49 @@
 block discarded – undo
15 15
 interface CacheStorageInterface
16 16
 {
17 17
 
18
-    /**
19
-     * Saves supplied data
20
-     * if an expiration is set, then it automatically schedules the cache for deletion
21
-     *
22
-     * @param string $key        [required]
23
-     * @param string $data       [required]
24
-     * @param int    $expiration number of seconds until the cache expires
25
-     * @return bool
26
-     */
27
-    public function add($key, $data, $expiration = 0);
18
+	/**
19
+	 * Saves supplied data
20
+	 * if an expiration is set, then it automatically schedules the cache for deletion
21
+	 *
22
+	 * @param string $key        [required]
23
+	 * @param string $data       [required]
24
+	 * @param int    $expiration number of seconds until the cache expires
25
+	 * @return bool
26
+	 */
27
+	public function add($key, $data, $expiration = 0);
28 28
 
29 29
 
30 30
 
31
-    /**
32
-     * retrieves cache data
33
-     * should automatically trigger early cache refresh for standard cache items
34
-     * in order to avoid cache stampedes on busy sites.
35
-     * For non-standard cache items like PHP Session data where early refreshing is not wanted,
36
-     * the $standard_cache parameter should be set to false when retrieving data
37
-     *
38
-     * @param string $key [required]
39
-     * @param bool   $standard_cache
40
-     * @return mixed
41
-     */
42
-    public function get($key, $standard_cache = true);
31
+	/**
32
+	 * retrieves cache data
33
+	 * should automatically trigger early cache refresh for standard cache items
34
+	 * in order to avoid cache stampedes on busy sites.
35
+	 * For non-standard cache items like PHP Session data where early refreshing is not wanted,
36
+	 * the $standard_cache parameter should be set to false when retrieving data
37
+	 *
38
+	 * @param string $key [required]
39
+	 * @param bool   $standard_cache
40
+	 * @return mixed
41
+	 */
42
+	public function get($key, $standard_cache = true);
43 43
 
44 44
 
45 45
 
46
-    /**
47
-     * delete a single cached item
48
-     *
49
-     * @param string $key [required] full or partial cache key to be deleted
50
-     */
51
-    public function delete($key);
46
+	/**
47
+	 * delete a single cached item
48
+	 *
49
+	 * @param string $key [required] full or partial cache key to be deleted
50
+	 */
51
+	public function delete($key);
52 52
 
53 53
 
54 54
 
55
-    /**
56
-     * delete multiple cached items
57
-     *
58
-     * @param array $keys [required] array of full or partial cache keys to be deleted
59
-     */
60
-    public function deleteMany(array $keys);
55
+	/**
56
+	 * delete multiple cached items
57
+	 *
58
+	 * @param array $keys [required] array of full or partial cache keys to be deleted
59
+	 */
60
+	public function deleteMany(array $keys);
61 61
 
62 62
 }
63 63
 // End of file CacheStorageInterface.php
Please login to merge, or discard this patch.