PluginProbe
ManageWP Worker / 4.9.25
ManageWP Worker v4.9.25
4.9.38 4.9.37 4.9.36 4.9.35 4.9.34 3.8.7 3.8.8 3.9.0 3.9.1 3.9.10 3.9.11 3.9.12 3.9.13 3.9.14 3.9.15 3.9.16 3.9.17 3.9.18 3.9.19 3.9.2 3.9.20 3.9.21 3.9.22 3.9.23 3.9.24 All 73 releases
worker / src / MWP / WordPress / Context.php

Context.php in ManageWP Worker 4.9.25, at src/MWP/WordPress/Context.php

839 lines 19.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 * This file is part of the ManageWP Worker plugin.
4 *
5 * (c) ManageWP LLC <contact@managewp.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11 /**
12 * Proxy class for WordPress' function calls. This is the only class that should be able to use WordPress' internal functions.
13 * The rule of thumb is that if a function does not exist since WordPress 3.0.0, it should be defined here.
14 */
15 class MWP_WordPress_Context
16 {
17
18 private $context;
19
20 private $constants;
21
22 private $useGlobals;
23
24 /**
25 * @param array $globals The context to work with. Defaults to $GLOBALS, using the same global variables as WordPress.
26 * @param array $constants The list of constants to use. Defaults to global constants.
27 */
28 public function __construct(array &$globals = null, array $constants = null)
29 {
30 if ($globals !== null) {
31 $this->context = $globals;
32 $this->useGlobals = false;
33 } else {
34 $this->useGlobals = true;
35 }
36
37 if ($constants !== null) {
38 $this->constants = $constants;
39 }
40 }
41
42 public function set($name, $value)
43 {
44 if ($this->useGlobals) {
45 $GLOBALS[$name] = $value;
46 } else {
47 $this->context[$name] = $value;
48 }
49 }
50
51 public function get($name)
52 {
53 if ($this->useGlobals) {
54 return isset($GLOBALS[$name]) ? $GLOBALS[$name] : null;
55 }
56
57 return isset($this->context[$name]) ? $this->context[$name] : null;
58 }
59
60 /**
61 * @return wpdb
62 */
63 public function getDb()
64 {
65 return $this->get('wpdb');
66 }
67
68 /**
69 * Escapes data for use in a MySQL query.
70 *
71 * Usually you should prepare queries using wpdb::prepare().
72 * Sometimes, spot-escaping is required or useful. One example
73 * is preparing an array for use in an IN clause.
74 *
75 * @param array|string $data
76 *
77 * @return array|string
78 */
79 public function escapeParameter($data)
80 {
81 return esc_sql($data);
82 }
83
84 /**
85 * @return string
86 */
87 public function getVersion()
88 {
89 return $this->get('wp_version');
90 }
91
92 /**
93 * @param string $version
94 *
95 * @return bool
96 */
97 public function isVersionAtLeast($version)
98 {
99 if (version_compare($version, $this->getVersion(), '<=')) {
100 return true;
101 }
102
103 return false;
104 }
105
106 /**
107 * @param string $tag
108 * @param Callable $functionToAdd
109 * @param int $priority
110 * @param int $acceptedArgs
111 *
112 * @see add_action()
113 * @link http://codex.wordpress.org/Function_Reference/add_action
114 */
115 public function addAction($tag, $functionToAdd, $priority = 10, $acceptedArgs = 1)
116 {
117 add_action($tag, $functionToAdd, $priority, $acceptedArgs);
118 }
119
120 /**
121 * @param string $name
122 * @param array $args
123 */
124 public function doAction($name, array $args = array())
125 {
126 if ($name == 'admin_init') {
127 do_action($name);
128 } else {
129 do_action($name, $args);
130 }
131 }
132
133 /**
134 * @param string $optionName The option to delete.
135 * @param bool $global Whether to delete the option from the whole network. Used for network un-installation.
136 *
137 * @see delete_site_option()
138 * @see delete_option()
139 * @link http://codex.wordpress.org/Function_Reference/register_uninstall_hook
140 */
141 public function optionDelete($optionName, $global = false)
142 {
143 if ($global && is_multisite()) {
144 $db = $this->getDb();
145 $blogIDs = $db->get_col("SELECT blog_id FROM $db->blogs");
146 foreach ($blogIDs as $blogID) {
147 delete_blog_option($blogID, $optionName);
148 }
149 } else {
150 delete_option($optionName);
151 }
152 }
153
154 /**
155 * @param string $optionName
156 * @param mixed $optionValue
157 * @param bool $global
158 *
159 * @see update_site_option()
160 * @see update_option()
161 * @link
162 */
163 public function optionSet($optionName, $optionValue, $global = false)
164 {
165 if ($global && is_multisite()) {
166 $db = $this->getDb();
167 $blogIDs = $db->get_col("SELECT blog_id FROM $db->blogs");
168 foreach ($blogIDs as $blogID) {
169 update_blog_option($blogID, $optionName, $optionValue);
170 }
171 } else {
172 update_option($optionName, $optionValue, true);
173 }
174 }
175
176 /**
177 * @param string $option Name of option to retrieve.
178 * @param mixed $default Optional. Default value to return if the option does not exist.
179 * @param int $siteId Site ID to update. Only used in multisite installations.
180 * @param bool $useCache Whether to use cache. Multisite only.
181 *
182 * @return mixed Value set for the option.
183 *
184 * @see get_option()
185 * @link http://codex.wordpress.org/Function_Reference/get_option
186 */
187 public function optionGet($option, $default = false, $siteId = null, $useCache = true)
188 {
189 if ($siteId !== null && is_multisite()) {
190 return get_site_option($option, $default, $useCache);
191 }
192
193 return get_option($option, $default);
194 }
195
196 /**
197 * WordPress' function get_current_blog_id() is not available before version 3.1.0.
198 *
199 * @return int
200 *
201 * @see get_current_blog_id()
202 */
203 public function getCurrentBlogId()
204 {
205 return abs(intval($this->get('blog_id')));
206 }
207
208 /**
209 * @param string $constant
210 *
211 * @return bool
212 */
213 public function hasConstant($constant)
214 {
215 if (is_array($this->constants)) {
216 return isset($this->constants[$constant]);
217 }
218
219 return defined($constant);
220 }
221
222 /**
223 * @param string $constant
224 *
225 * @return int|string
226 * @throws Exception If the constant does not exist.
227 */
228 public function getConstant($constant)
229 {
230 if (!$this->hasConstant($constant)) {
231 throw new Exception(sprintf('The constant "%s" is not defined', $constant));
232 }
233
234 if (is_array($this->constants)) {
235 return $this->constants[$constant];
236 }
237
238 return constant($constant);
239 }
240
241 public function setConstant($name, $value, $throw = true)
242 {
243 if ($this->hasConstant($name)) {
244 if ($throw) {
245 throw new Exception(sprintf('The constant "%s" is already defined', $name));
246 }
247
248 return;
249 }
250
251 if (is_array($this->constants)) {
252 $this->constants[$name] = $value;
253
254 return;
255 }
256
257 define($name, $value);
258 }
259
260 /**
261 * @return string
262 *
263 * @see plugin_basename()
264 */
265 public function getPluginBasename()
266 {
267 $dirName = explode('/', plugin_basename(__FILE__), 2);
268 $dirName = $dirName[0];
269
270 return $dirName.'/init.php';
271 }
272
273 public function getPlugins()
274 {
275 if (!function_exists('get_mu_plugins')) {
276 require_once($this->getConstant('ABSPATH').'wp-admin/includes/plugin.php');
277 }
278
279 return get_plugins();
280 }
281
282 public function getMustUsePlugins()
283 {
284 if (!function_exists('get_mu_plugins')) {
285 require_once($this->getConstant('ABSPATH').'wp-admin/includes/plugin.php');
286 }
287
288 return get_mu_plugins();
289 }
290
291 public function isPluginActive($pluginBasename)
292 {
293 return is_plugin_active($pluginBasename);
294 }
295
296 public function isPluginActiveForNetwork($pluginBasename)
297 {
298 return is_plugin_active_for_network($pluginBasename);
299 }
300
301 public function getThemes()
302 {
303 $wpThemeDirectories = $this->get('wp_theme_directories');
304
305 // When the plugin is MU-loaded, the WordPress theme directories are not set.
306 if (empty($wpThemeDirectories)) {
307 // Register the default theme directory root.
308 register_theme_directory(get_theme_root());
309 }
310
311 if ($this->isVersionAtLeast('3.4')) {
312 return wp_get_themes();
313 }
314
315 return get_themes();
316 }
317
318 public function getCurrentTheme()
319 {
320 $wpThemeDirectories = $this->get('wp_theme_directories');
321
322 // When the plugin is MU-loaded, the WordPress theme directories are not set.
323 if ($this->isMustUse() && empty($wpThemeDirectories)) {
324 // Register the default theme directory root.
325 register_theme_directory(get_theme_root());
326 }
327
328 if ($this->isVersionAtLeast('3.4')) {
329 return wp_get_theme();
330 }
331
332 return get_current_theme();
333 }
334
335 public function getStylesheetDirectory()
336 {
337 return get_stylesheet_directory();
338 }
339
340 /**
341 * @param string $key
342 * @param mixed $value
343 * @param int $expire Expiration time in seconds from now.
344 *
345 * @return bool
346 */
347 public function transientSet($key, $value, $expire = 0)
348 {
349 return set_site_transient($key, $value, $expire);
350 }
351
352 /**
353 * @param string $key
354 *
355 * @return mixed
356 */
357 public function transientGet($key)
358 {
359 return get_site_transient($key);
360 }
361
362 /**
363 * @param string $key
364 *
365 * @return bool
366 */
367 public function transientDelete($key)
368 {
369 return delete_site_transient($key);
370 }
371
372 private function isMustUse()
373 {
374 $mwpIsMu = $this->get('mwp_is_mu');
375
376 if (empty($mwpIsMu)) {
377 return false;
378 }
379
380 return true;
381 }
382
383 /**
384 * @param string $tag
385 * @param Callable $functionToAdd
386 * @param int $priority
387 * @param int $acceptedArgs
388 */
389 public function addFilter($tag, $functionToAdd, $priority = 10, $acceptedArgs = 1)
390 {
391 add_filter($tag, $functionToAdd, $priority, $acceptedArgs);
392 }
393
394 public function enqueueScript($handle, $src = false, $dependencies = array(), $ver = false, $inFooter = false)
395 {
396 wp_enqueue_script($handle, $src, $dependencies, $ver, $inFooter);
397 }
398
399 public function enqueueStyle($handle, $src = false, $dependencies = array(), $ver = false, $media = 'all')
400 {
401 wp_enqueue_style($handle, $src, $dependencies, $ver, $media);
402 }
403
404 public function addMenuPage($pageTitle, $menuTitle, $capability, $slug, $callback = '', $iconUrl = '', $position = null)
405 {
406 add_menu_page($pageTitle, $menuTitle, $capability, $slug, $callback, $iconUrl, $position);
407 }
408
409 public function translate($text, $domain = 'default')
410 {
411 return translate($text, $domain);
412 }
413
414 public function output($content)
415 {
416 print $content;
417 }
418
419 public function getCurrentUser()
420 {
421 $this->requirePluggable();
422 $this->requireCookieConstants();
423
424 return wp_get_current_user();
425 }
426
427 public function getHomeUrl()
428 {
429 return get_home_url();
430 }
431
432 public function sendMail($to, $subject, $message, $headers = '', $attachments = array())
433 {
434 $this->requirePluggable();
435
436 return wp_mail($to, $subject, $message, $headers, $attachments);
437 }
438
439 public function getAdminUrl($where)
440 {
441 return admin_url($where);
442 }
443
444 public function isInAdminPanel()
445 {
446 return is_admin();
447 }
448
449 public function isGranted($capability)
450 {
451 $this->requirePluggable();
452 $this->requireCookieConstants();
453
454 return current_user_can($capability);
455 }
456
457 /**
458 * @param string $name Value name.
459 *
460 * @return mixed Context (global) value. Null if one doesn't exist.
461 *
462 * @throws Exception If the context value does not exist.
463 */
464 public function &getContextValue($name)
465 {
466 if (!$this->hasContextValue($name)) {
467 throw new Exception(sprintf('Context value "%s" does not exist', $name));
468 }
469
470 // Ternary operator not used since it breaks the needed reference
471 if ($this->useGlobals) {
472 return $GLOBALS[$name];
473 }
474
475 return $this->context[$name];
476 }
477
478 /**
479 * @param string $name Value name.
480 *
481 * @return bool
482 */
483 public function hasContextValue($name)
484 {
485 return array_key_exists($name, $this->useGlobals ? $GLOBALS : $this->context);
486 }
487
488 public function getDropInPlugins()
489 {
490 if (!function_exists('get_dropins')) {
491 require_once ABSPATH.'wp-admin/includes/plugin.php';
492 }
493
494 return get_dropins();
495 }
496
497 public function requirePluggable()
498 {
499 require_once $this->getConstant('ABSPATH').$this->getConstant('WPINC').'/pluggable.php';
500 }
501
502 public function requireCookieConstants()
503 {
504 wp_cookie_constants();
505 }
506
507 public function requireAdminUserLibrary()
508 {
509 require_once $this->getConstant('ABSPATH').'wp-admin/includes/user.php';
510 }
511
512 public function getUserRoles()
513 {
514 $this->requireAdminUserLibrary();
515
516 return get_editable_roles();
517 }
518
519 /**
520 * @param string $username
521 *
522 * @return WP_User|stdClass|null
523 */
524 public function getUserByUsername($username)
525 {
526 $this->requirePluggable();
527
528 $user = get_user_by('login', $username);
529
530 if (!$user) {
531 return null;
532 }
533
534 return $user;
535 }
536
537 /**
538 * @param int $code
539 *
540 * @return WP_User
541 *
542 * @throws MWP_Worker_Exception
543 */
544 public function getAdminUser($code)
545 {
546 /** @var wpdb $wpdb */
547 global $wpdb;
548
549 $this->requirePluggable();
550
551 $query = "SELECT * FROM {$wpdb->users} WHERE ID IN (SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = '{$wpdb->prefix}capabilities' AND meta_value LIKE '%administrator%') ORDER BY ID LIMIT 1";
552 $result = $wpdb->get_row($query);
553
554 if (null === $result) {
555 throw new MWP_Worker_Exception($code, "We could not find an administrator user to use. Please contact support.");
556 }
557 /** @handled class */
558 $user = new WP_User();
559 $user->init($result);
560
561 return $user;
562 }
563
564 public function isPluginEnabled($pluginBasename)
565 {
566 $plugins = (array)$this->optionGet('active_plugins', array());
567
568 return in_array($pluginBasename, $plugins);
569 }
570
571 /**
572 * @param WP_User|stdClass $user
573 */
574 public function setCurrentUser($user)
575 {
576 $this->requirePluggable();
577
578 wp_set_current_user($user->ID);
579 }
580
581 /**
582 * @param WP_User|stdClass $user
583 * @param bool $remember
584 * @param string $secure
585 */
586 public function setAuthCookie($user, $remember = false, $secure = '')
587 {
588 $this->requireCookieConstants();
589
590 wp_set_auth_cookie($user->ID, $remember, $secure);
591 }
592
593 public function wpDie($message = '', $title = '', $args = array())
594 {
595 wp_die($message, $title, $args);
596 // This is just a stub, the script will have exit()-ed just before this point.
597 exit();
598 }
599
600 /**
601 * Returns current site's URL.
602 *
603 * @return string|void
604 */
605 public function getSiteUrl()
606 {
607 return get_bloginfo('wpurl');
608 }
609
610 public function requireWpRewrite()
611 {
612 if ($this->get('wp_rewrite') instanceof WP_Rewrite) {
613 return;
614 }
615
616 /** @handled class */
617 $this->set('wp_rewrite', new WP_Rewrite());
618 }
619
620 public function requireTaxonomies()
621 {
622 $wpTaxonomies = $this->get('wp_taxonomies');
623
624 if (!empty($wpTaxonomies)) {
625 return;
626 }
627
628 create_initial_taxonomies();
629 }
630
631 public function requirePostTypes()
632 {
633 $wpPostTypes = $this->get('wp_post_types');
634
635 if (!empty($wpPostTypes)) {
636 return;
637 }
638
639 create_initial_post_types();
640 }
641
642 public function requireTheme()
643 {
644 $wpThemeDirectories = $this->get('wp_theme_directories');
645
646 if (!empty($wpThemeDirectories)) {
647 return;
648 }
649
650 register_theme_directory(get_theme_root());
651 }
652
653 public function getLocale()
654 {
655 return get_locale();
656 }
657
658 public function tryDeserialize($content)
659 {
660 return maybe_unserialize($content);
661 }
662
663 public function getSiteTitle()
664 {
665 return get_bloginfo('name');
666 }
667
668 public function getSiteDescription()
669 {
670 return get_bloginfo('description');
671 }
672
673 /**
674 * Always returns main site's url (in multisite installations).
675 *
676 * @see getSiteUrl
677 *
678 * @return string|void
679 */
680 public function getMasterSiteUrl()
681 {
682 return site_url();
683 }
684
685 public function isMultisite()
686 {
687 return is_multisite();
688 }
689
690 public function isMainSite()
691 {
692 return is_main_site();
693 }
694
695 public function isNetworkAdmin()
696 {
697 return is_network_admin();
698 }
699
700 public function getSiteId()
701 {
702 return get_current_blog_id();
703 }
704
705 public function getDbName()
706 {
707 return $this->getConstant('DB_NAME');
708 }
709
710 /**
711 * @param int $attachmentId
712 * @param string $style
713 *
714 * @return null
715 */
716 public function getImageInfo($attachmentId, $style)
717 {
718 $info = wp_get_attachment_image_src($attachmentId, $style);
719
720 if (!$info) {
721 return null;
722 }
723
724 return array(
725 'url' => $info[0],
726 'width' => $info[1],
727 'height' => $info[2],
728 'original' => !$info[3],
729 );
730 }
731
732 public function addImageStyle($name, $width = 0, $height = 0, $crop = false)
733 {
734 add_image_size($name, $width, $height);
735 }
736
737 public function setCookie($name, $value, $expire = 0)
738 {
739 setcookie($name, $value, $expire, $this->getConstant('SITECOOKIEPATH'), $this->getConstant('COOKIE_DOMAIN'), $this->isSsl(), true);
740 }
741
742 /**
743 * @return bool
744 */
745 public function isSsl()
746 {
747 return (bool)is_ssl();
748 }
749
750 /**
751 * @return bool
752 */
753 public function isSslAdmin()
754 {
755 return $this->isSsl() || force_ssl_admin();
756 }
757
758 public function removeAction($tag, $function, $priority = 10)
759 {
760 remove_action($tag, $function, $priority);
761 }
762
763 public function addSubMenuPage($parentSlug, $pageTitle, $menuTitle, $capability, $menuSlug, $function = '')
764 {
765 return add_submenu_page($parentSlug, $pageTitle, $menuTitle, $capability, $menuSlug, $function);
766 }
767
768 public function wpNonceUrl($url, $action = -1, $name = '_wpnonce')
769 {
770 return wp_nonce_url($url, $action, $name);
771 }
772
773 /**
774 * @param int $userId
775 * @param string $metaKey
776 *
777 * @return mixed
778 */
779 public function getUserMeta($userId, $metaKey)
780 {
781 return get_user_meta($userId, $metaKey, true);
782 }
783
784 /**
785 * @param int $userId
786 * @param string $metaKey
787 * @param mixed $metaValue
788 *
789 * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
790 */
791 public function setUserMeta($userId, $metaKey, $metaValue)
792 {
793 return update_user_meta($userId, $metaKey, $metaValue);
794 }
795
796 /**
797 * @param int $userId
798 *
799 * @return WP_Session_Tokens|null Returns null if the class does not exist, ie. before WordPress version 4.0.0.
800 */
801 public function getSessionTokens($userId)
802 {
803 if (!class_exists('WP_Session_Tokens', false)) {
804 return null;
805 }
806
807 /** @handled static */
808
809 return WP_Session_Tokens::get_instance($userId);
810 }
811
812 public function getCurrentTime()
813 {
814 return new DateTime('@'.current_time('timestamp'));
815 }
816
817 /**
818 * @param int $userId
819 * @param string $key
820 * @param mixed $value
821 *
822 * @return bool|int
823 */
824 public function updateUserMeta($userId, $key, $value)
825 {
826 return update_user_meta($userId, $key, $value);
827 }
828
829 /**
830 * @param string $str
831 *
832 * @return bool
833 */
834 public function seemsUtf8($str)
835 {
836 return seems_utf8($str);
837 }
838 }
839