PluginProbe
ManageWP Worker / trunk
ManageWP Worker vtrunk
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 trunk, at src/MWP/WordPress/Context.php

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