Merge pull request #19726 from seamuslee001/5.35
[civicrm-core.git] / CRM / Utils / System / WordPress.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * WordPress specific stuff goes here
20 */
21 class CRM_Utils_System_WordPress extends CRM_Utils_System_Base {
22
23 /**
24 * Get a normalized version of the wpBasePage.
25 */
26 public static function getBasePage() {
27 return strtolower(rtrim(Civi::settings()->get('wpBasePage'), '/'));
28 }
29
30 /**
31 */
32 public function __construct() {
33 /**
34 * deprecated property to check if this is a drupal install. The correct method is to have functions on the UF classes for all UF specific
35 * functions and leave the codebase oblivious to the type of CMS
36 * @deprecated
37 * @var bool
38 */
39 $this->is_drupal = FALSE;
40 $this->is_wordpress = TRUE;
41 }
42
43 public function initialize() {
44 parent::initialize();
45 $this->registerPathVars();
46 }
47
48 /**
49 * Specify the default computation for various paths/URLs.
50 */
51 protected function registerPathVars():void {
52 $isNormalBoot = function_exists('get_option');
53 if ($isNormalBoot) {
54 // Normal mode - CMS boots first, then calls Civi. "Normal" web pages and newer extern routes.
55 // To simplify the code-paths, some items are re-registered with WP-specific functions.
56 $cmsRoot = function() {
57 return [
58 'path' => untrailingslashit(ABSPATH),
59 'url' => home_url(),
60 ];
61 };
62 Civi::paths()->register('cms', $cmsRoot);
63 Civi::paths()->register('cms.root', $cmsRoot);
64 Civi::paths()->register('civicrm.root', function () {
65 return [
66 'path' => CIVICRM_PLUGIN_DIR . 'civicrm' . DIRECTORY_SEPARATOR,
67 'url' => CIVICRM_PLUGIN_URL . 'civicrm/',
68 ];
69 });
70 Civi::paths()->register('wp.frontend.base', function () {
71 return [
72 'url' => home_url('/'),
73 ];
74 });
75 Civi::paths()->register('wp.frontend', function () {
76 $config = CRM_Core_Config::singleton();
77 $basepage = get_page_by_path($config->wpBasePage);
78 return [
79 'url' => get_permalink($basepage->ID),
80 ];
81 });
82 Civi::paths()->register('wp.backend.base', function () {
83 return [
84 'url' => admin_url(),
85 ];
86 });
87 Civi::paths()->register('wp.backend', function() {
88 return [
89 'url' => admin_url('admin.php'),
90 ];
91 });
92 Civi::paths()->register('civicrm.files', function () {
93 $upload_dir = wp_get_upload_dir();
94
95 $old = CRM_Core_Config::singleton()->userSystem->getDefaultFileStorage();
96 $new = [
97 'path' => $upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'civicrm' . DIRECTORY_SEPARATOR,
98 'url' => $upload_dir['baseurl'] . '/civicrm/',
99 ];
100
101 if ($old['path'] === $new['path']) {
102 return $new;
103 }
104
105 $oldExists = file_exists($old['path']);
106 $newExists = file_exists($new['path']);
107
108 if ($oldExists && !$newExists) {
109 return $old;
110 }
111 elseif (!$oldExists && $newExists) {
112 return $new;
113 }
114 elseif (!$oldExists && !$newExists) {
115 // neither exists. but that's ok. we're in one of these two cases:
116 // - we're just starting installation... which will get sorted in a moment
117 // when someone calls mkdir().
118 // - we're running a bespoke setup... which will get sorted in a moment
119 // by applying $civicrm_paths.
120 return $new;
121 }
122 elseif ($oldExists && $newExists) {
123 // situation ambiguous. encourage admin to set value explicitly.
124 if (!isset($GLOBALS['civicrm_paths']['civicrm.files'])) {
125 \Civi::log()->warning("The system has data from both old+new conventions. Please use civicrm.settings.php to set civicrm.files explicitly.");
126 }
127 return $new;
128 }
129 });
130 }
131 else {
132 // Legacy support - only relevant for older extern routes.
133 Civi::paths()
134 ->register('wp.frontend.base', function () {
135 return ['url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/'];
136 })
137 ->register('wp.frontend', function () {
138 $config = \CRM_Core_Config::singleton();
139 $suffix = defined('CIVICRM_UF_WP_BASEPAGE') ? CIVICRM_UF_WP_BASEPAGE : $config->wpBasePage;
140 return [
141 'url' => Civi::paths()->getVariable('wp.frontend.base', 'url') . $suffix,
142 ];
143 })
144 ->register('wp.backend.base', function () {
145 return ['url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/wp-admin/'];
146 })
147 ->register('wp.backend', function () {
148 return [
149 'url' => Civi::paths()->getVariable('wp.backend.base', 'url') . 'admin.php',
150 ];
151 });
152 }
153 }
154
155 /**
156 * @inheritDoc
157 */
158 public function setTitle($title, $pageTitle = NULL) {
159 if (!$pageTitle) {
160 $pageTitle = $title;
161 }
162
163 // FIXME: Why is this global?
164 global $civicrm_wp_title;
165 $civicrm_wp_title = $title;
166
167 // yes, set page title, depending on context
168 $context = civi_wp()->civicrm_context_get();
169 switch ($context) {
170 case 'admin':
171 case 'shortcode':
172 $template = CRM_Core_Smarty::singleton();
173 $template->assign('pageTitle', $pageTitle);
174 }
175 }
176
177 /**
178 * Moved from CRM_Utils_System_Base
179 */
180 public function getDefaultFileStorage() {
181 // NOTE: On WordPress, this will be circumvented in the future. However,
182 // should retain it to allow transitional/upgrade code determine the old value.
183
184 $config = CRM_Core_Config::singleton();
185 $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
186 $cmsPath = $this->cmsRootPath();
187 $filesPath = CRM_Utils_File::baseFilePath();
188 $filesRelPath = CRM_Utils_File::relativize($filesPath, $cmsPath);
189 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
190 return [
191 'url' => CRM_Utils_File::addTrailingSlash($filesURL, '/'),
192 'path' => CRM_Utils_File::addTrailingSlash($filesPath),
193 ];
194 }
195
196 /**
197 * Determine the location of the CiviCRM source tree.
198 *
199 * @return array
200 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
201 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
202 */
203 public function getCiviSourceStorage() {
204 global $civicrm_root;
205
206 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
207 // More generally, we shouldn't be using $config here.
208 if (!defined('CIVICRM_UF_BASEURL')) {
209 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
210 }
211
212 $cmsPath = $this->cmsRootPath();
213
214 // $config = CRM_Core_Config::singleton();
215 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
216 $cmsUrl = CIVICRM_UF_BASEURL;
217 if (CRM_Utils_System::isSSL()) {
218 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
219 }
220 $civiRelPath = CRM_Utils_File::relativize(realpath($civicrm_root), realpath($cmsPath));
221 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
222 return [
223 'url' => CRM_Utils_File::addTrailingSlash($civiUrl, '/'),
224 'path' => CRM_Utils_File::addTrailingSlash($civicrm_root),
225 ];
226 }
227
228 /**
229 * @inheritDoc
230 */
231 public function appendBreadCrumb($breadCrumbs) {
232 $breadCrumb = wp_get_breadcrumb();
233
234 if (is_array($breadCrumbs)) {
235 foreach ($breadCrumbs as $crumbs) {
236 if (stripos($crumbs['url'], 'id%%')) {
237 $args = ['cid', 'mid'];
238 foreach ($args as $a) {
239 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
240 FALSE, NULL, $_GET
241 );
242 if ($val) {
243 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
244 }
245 }
246 }
247 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
248 }
249 }
250
251 $template = CRM_Core_Smarty::singleton();
252 $template->assign_by_ref('breadcrumb', $breadCrumb);
253 wp_set_breadcrumb($breadCrumb);
254 }
255
256 /**
257 * @inheritDoc
258 */
259 public function resetBreadCrumb() {
260 $bc = [];
261 wp_set_breadcrumb($bc);
262 }
263
264 /**
265 * @inheritDoc
266 */
267 public function addHTMLHead($head) {
268 static $registered = FALSE;
269 if (!$registered) {
270 // front-end view
271 add_action('wp_head', [__CLASS__, '_showHTMLHead']);
272 // back-end views
273 add_action('admin_head', [__CLASS__, '_showHTMLHead']);
274 $registered = TRUE;
275 }
276 CRM_Core_Region::instance('wp_head')->add([
277 'markup' => $head,
278 ]);
279 }
280
281 /**
282 * WP action callback.
283 */
284 public static function _showHTMLHead() {
285 $region = CRM_Core_Region::instance('wp_head', FALSE);
286 if ($region) {
287 echo $region->render('');
288 }
289 }
290
291 /**
292 * @inheritDoc
293 */
294 public function mapConfigToSSL() {
295 global $base_url;
296 $base_url = str_replace('http://', 'https://', $base_url);
297 }
298
299 /**
300 * @inheritDoc
301 */
302 public function url(
303 $path = NULL,
304 $query = NULL,
305 $absolute = FALSE,
306 $fragment = NULL,
307 $frontend = FALSE,
308 $forceBackend = FALSE,
309 $htmlize = TRUE
310 ) {
311 $config = CRM_Core_Config::singleton();
312 $script = '';
313 $separator = '&';
314 $wpPageParam = '';
315 $fragment = isset($fragment) ? ('#' . $fragment) : '';
316
317 $path = CRM_Utils_String::stripPathChars($path);
318 $basepage = FALSE;
319
320 //this means wp function we are trying to use is not available,
321 //so load bootStrap
322 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
323 if (!function_exists('get_option')) {
324 $this->loadBootStrap();
325 }
326
327 if ($config->userFrameworkFrontend) {
328 global $post;
329 if (get_option('permalink_structure') != '') {
330 $script = $post ? get_permalink($post->ID) : "";
331 }
332 if ($post && $config->wpBasePage == $post->post_name) {
333 $basepage = TRUE;
334 }
335 // when shortcode is included in page
336 // also make sure we have valid query object
337 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
338 global $wp_query;
339 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
340 if (get_query_var('page_id')) {
341 $wpPageParam = "page_id=" . get_query_var('page_id');
342 }
343 elseif (get_query_var('p')) {
344 // when shortcode is inserted in post
345 $wpPageParam = "p=" . get_query_var('p');
346 }
347 }
348 }
349
350 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
351
352 if (!isset($path) && !isset($query)) {
353 // FIXME: This short-circuited codepath is the same as the general one below, except
354 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
355 // why it's different (and I can only find two obvious use-cases for this codepath,
356 // of which at least one looks gratuitous). A more ambitious person would simply remove
357 // this code.
358 return $base . $fragment;
359 }
360
361 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam || $script != '')) {
362 $base = $script;
363 }
364
365 $queryParts = [];
366
367 if (
368 // not using clean URLs
369 !$config->cleanURL
370 // requesting an admin URL
371 || ((is_admin() && !$frontend) || $forceBackend)
372 // is shortcode
373 || (!$basepage && $script != '')
374 ) {
375
376 // pre-existing logic
377 if (isset($path)) {
378 // Admin URLs still need "page=CiviCRM", front-end URLs do not.
379 if ((is_admin() && !$frontend) || $forceBackend) {
380 $queryParts[] = 'page=CiviCRM';
381 }
382 else {
383 $queryParts[] = 'civiwp=CiviCRM';
384 }
385 $queryParts[] = 'q=' . rawurlencode($path);
386 }
387 if ($wpPageParam) {
388 $queryParts[] = $wpPageParam;
389 }
390 if (!empty($query)) {
391 $queryParts[] = $query;
392 }
393
394 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
395
396 }
397 else {
398
399 // clean URLs
400 if (isset($path)) {
401 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
402 }
403 if (isset($query)) {
404 $query = ltrim($query, '=?&');
405 $queryParts[] = $query;
406 }
407
408 if (!empty($queryParts)) {
409 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
410 }
411 else {
412 $final = $base . $fragment;
413 }
414
415 }
416
417 return $final;
418 }
419
420 /**
421 * 27-09-2016
422 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
423 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
424 * For now leave hard coded wp-admin references.
425 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
426 *
427 * @param $absolute
428 * @param $frontend
429 * @param $forceBackend
430 *
431 * @return mixed|null|string
432 */
433 private function getBaseUrl($absolute, $frontend, $forceBackend) {
434 $config = CRM_Core_Config::singleton();
435 if ((is_admin() && !$frontend) || $forceBackend) {
436 return Civi::paths()->getUrl('[wp.backend]/.', $absolute ? 'absolute' : 'relative');
437 }
438 else {
439 return Civi::paths()->getUrl('[wp.frontend]/.', $absolute ? 'absolute' : 'relative');
440 }
441 }
442
443 /**
444 * @inheritDoc
445 */
446 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
447 $config = CRM_Core_Config::singleton();
448
449 if ($loadCMSBootstrap) {
450 $config->userSystem->loadBootStrap([
451 'name' => $name,
452 'pass' => $password,
453 ]);
454 }
455
456 $user = wp_authenticate($name, $password);
457 if (is_a($user, 'WP_Error')) {
458 return FALSE;
459 }
460
461 // TODO: need to change this to make sure we matched only one row
462
463 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
464 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
465 if (!$contactID) {
466 return FALSE;
467 }
468 return [$contactID, $user->data->ID, mt_rand()];
469 }
470
471 /**
472 * FIXME: Do something
473 *
474 * @param string $message
475 */
476 public function setMessage($message) {
477 }
478
479 /**
480 * @param \string $user
481 *
482 * @return bool
483 */
484 public function loadUser($user) {
485 $userdata = get_user_by('login', $user);
486 if (!$userdata->data->ID) {
487 return FALSE;
488 }
489
490 $uid = $userdata->data->ID;
491 wp_set_current_user($uid);
492 $contactID = CRM_Core_BAO_UFMatch::getContactId($uid);
493
494 // lets store contact id and user id in session
495 $session = CRM_Core_Session::singleton();
496 $session->set('ufID', $uid);
497 $session->set('userID', $contactID);
498 return TRUE;
499 }
500
501 /**
502 * FIXME: Use CMS-native approach
503 * @throws \CRM_Core_Exception
504 */
505 public function permissionDenied() {
506 status_header(403);
507 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
508 }
509
510 /**
511 * Determine the native ID of the CMS user.
512 *
513 * @param string $username
514 *
515 * @return int|null
516 */
517 public function getUfId($username) {
518 $userdata = get_user_by('login', $username);
519 if (!$userdata->data->ID) {
520 return NULL;
521 }
522 return $userdata->data->ID;
523 }
524
525 /**
526 * @inheritDoc
527 */
528 public function logout() {
529 // destroy session
530 if (session_id()) {
531 session_destroy();
532 }
533 wp_logout();
534 wp_redirect(wp_login_url());
535 }
536
537 /**
538 * @inheritDoc
539 */
540 public function getUFLocale() {
541 // Bail early if method is called when WordPress isn't bootstrapped.
542 // Additionally, the function checked here is located in pluggable.php
543 // and is required by wp_get_referer() - so this also bails early if it is
544 // called too early in the request lifecycle.
545 // @see https://core.trac.wordpress.org/ticket/25294
546 if (!function_exists('wp_validate_redirect')) {
547 return NULL;
548 }
549
550 // Default to WordPress User locale.
551 $locale = get_user_locale();
552
553 // Is this a "back-end" AJAX call?
554 $is_backend = FALSE;
555 if (wp_doing_ajax() && FALSE !== strpos(wp_get_referer(), admin_url())) {
556 $is_backend = TRUE;
557 }
558
559 // Ignore when in WordPress admin or it's a "back-end" AJAX call.
560 if (!(is_admin() || $is_backend)) {
561
562 // Reaching here means it is very likely to be a front-end context.
563
564 // Default to WordPress locale.
565 $locale = get_locale();
566
567 // Maybe override with the locale that Polylang reports.
568 if (function_exists('pll_current_language')) {
569 $pll_locale = pll_current_language('locale');
570 if (!empty($pll_locale)) {
571 $locale = $pll_locale;
572 }
573 }
574
575 // Maybe override with the locale that WPML reports.
576 elseif (defined('ICL_LANGUAGE_CODE')) {
577 $languages = apply_filters('wpml_active_languages', NULL);
578 foreach ($languages as $language) {
579 if ($language['active']) {
580 $locale = $language['default_locale'];
581 break;
582 }
583 }
584 }
585
586 // TODO: Set locale for other WordPress plugins.
587 // @see https://wordpress.org/plugins/tags/multilingual/
588 // A hook would be nice here.
589
590 }
591
592 if (!empty($locale)) {
593 // If for some reason only we get a language code, convert it to a locale.
594 if (2 === strlen($locale)) {
595 $locale = CRM_Core_I18n_PseudoConstant::longForShort($locale);
596 }
597 return $locale;
598 }
599 else {
600 return NULL;
601 }
602 }
603
604 /**
605 * @inheritDoc
606 */
607 public function setUFLocale($civicrm_language) {
608 // TODO (probably not possible with WPML?)
609 return TRUE;
610 }
611
612 /**
613 * Load wordpress bootstrap.
614 *
615 * @param array $params
616 * Optional credentials
617 * - name: string, cms username
618 * - pass: string, cms password
619 * @param bool $loadUser
620 * @param bool $throwError
621 * @param mixed $realPath
622 *
623 * @return bool
624 * @throws \CRM_Core_Exception
625 */
626 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
627 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
628
629 $name = $params['name'] ?? NULL;
630 $pass = $params['pass'] ?? NULL;
631
632 if (!defined('WP_USE_THEMES')) {
633 define('WP_USE_THEMES', FALSE);
634 }
635
636 $cmsRootPath = $this->cmsRootPath();
637 if (!$cmsRootPath) {
638 throw new CRM_Core_Exception("Could not find the install directory for WordPress");
639 }
640 $path = Civi::settings()->get('wpLoadPhp');
641 if (!empty($path)) {
642 require_once $path;
643 }
644 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) {
645 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
646 }
647 else {
648 throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress");
649 }
650 $wpUserTimezone = get_option('timezone_string');
651 if ($wpUserTimezone) {
652 date_default_timezone_set($wpUserTimezone);
653 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
654 }
655 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
656 $uid = $params['uid'] ?? NULL;
657 if (!$uid) {
658 $name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST));
659 $pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST));
660 if ($name) {
661 $uid = wp_authenticate($name, $pass);
662 if (!$uid) {
663 if ($throwError) {
664 echo '<br />Sorry, unrecognized username or password.';
665 exit();
666 }
667 return FALSE;
668 }
669 }
670 }
671 if ($uid) {
672 if ($uid instanceof WP_User) {
673 $account = wp_set_current_user($uid->ID);
674 }
675 else {
676 $account = wp_set_current_user($uid);
677 }
678 if ($account && $account->data->ID) {
679 global $user;
680 $user = $account;
681 return TRUE;
682 }
683 }
684 return TRUE;
685 }
686
687 /**
688 * @param $dir
689 *
690 * @return bool
691 */
692 public function validInstallDir($dir) {
693 $includePath = "$dir/wp-includes";
694 if (@file_exists("$includePath/version.php")) {
695 return TRUE;
696 }
697 return FALSE;
698 }
699
700 /**
701 * Determine the location of the CMS root.
702 *
703 * @return string|NULL
704 * local file system path to CMS root, or NULL if it cannot be determined
705 */
706 public function cmsRootPath() {
707
708 // Return early if the path is already set.
709 global $civicrm_paths;
710 if (!empty($civicrm_paths['cms.root']['path'])) {
711 return $civicrm_paths['cms.root']['path'];
712 }
713
714 // Return early if constant has been defined.
715 if (defined('CIVICRM_CMSDIR')) {
716 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
717 return CIVICRM_CMSDIR;
718 }
719 }
720
721 // Return early if path to wp-load.php can be retrieved from settings.
722 $setting = Civi::settings()->get('wpLoadPhp');
723 if (!empty($setting)) {
724 $path = str_replace('wp-load.php', '', $setting);
725 $cmsRoot = rtrim($path, '/\\');
726 if ($this->validInstallDir($cmsRoot)) {
727 return $cmsRoot;
728 }
729 }
730
731 /*
732 * Keep previous logic as fallback of last resort.
733 *
734 * At some point, it would be good to remove this because there are serious
735 * problems in correctly locating WordPress in this manner. In summary, it
736 * is impossible to do so reliably.
737 *
738 * @see https://github.com/civicrm/civicrm-wordpress/pull/63#issuecomment-61792328
739 * @see https://github.com/civicrm/civicrm-core/pull/11086#issuecomment-335454992
740 */
741 $cmsRoot = $valid = NULL;
742
743 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
744
745 // Might be Windows installation.
746 $firstVar = array_shift($pathVars);
747 if ($firstVar) {
748 $cmsRoot = $firstVar;
749 }
750
751 // Start with CMS dir search.
752 foreach ($pathVars as $var) {
753 $cmsRoot .= "/$var";
754 if ($this->validInstallDir($cmsRoot)) {
755 // Stop as we found bootstrap.
756 $valid = TRUE;
757 break;
758 }
759 }
760
761 return ($valid) ? $cmsRoot : NULL;
762 }
763
764 /**
765 * @inheritDoc
766 */
767 public function createUser(&$params, $mail) {
768 $user_data = [
769 'ID' => '',
770 'user_pass' => $params['cms_pass'],
771 'user_login' => $params['cms_name'],
772 'user_email' => $params[$mail],
773 'nickname' => $params['cms_name'],
774 'role' => get_option('default_role'),
775 ];
776 if (isset($params['contactID'])) {
777 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
778 if ($contactType == 'Individual') {
779 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
780 $params['contactID'], 'first_name'
781 );
782 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
783 $params['contactID'], 'last_name'
784 );
785 }
786 }
787
788 $uid = wp_insert_user($user_data);
789
790 $creds = [];
791 $creds['user_login'] = $params['cms_name'];
792 $creds['user_password'] = $params['cms_pass'];
793 $creds['remember'] = TRUE;
794 $user = wp_signon($creds, FALSE);
795
796 wp_new_user_notification($uid, $user_data['user_pass']);
797 return $uid;
798 }
799
800 /**
801 * @inheritDoc
802 */
803 public function updateCMSName($ufID, $ufName) {
804 // CRM-10620
805 if (function_exists('wp_update_user')) {
806 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
807 $ufName = CRM_Utils_Type::escape($ufName, 'String');
808
809 $values = ['ID' => $ufID, 'user_email' => $ufName];
810 if ($ufID) {
811 wp_update_user($values);
812 }
813 }
814 }
815
816 /**
817 * @param array $params
818 * @param $errors
819 * @param string $emailName
820 */
821 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
822 $config = CRM_Core_Config::singleton();
823
824 $dao = new CRM_Core_DAO();
825 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
826 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
827
828 if (!empty($params['name'])) {
829 if (!validate_username($params['name'])) {
830 $errors['cms_name'] = ts("Your username contains invalid characters");
831 }
832 elseif (username_exists(sanitize_user($params['name']))) {
833 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
834 }
835 }
836
837 if (!empty($params['mail'])) {
838 if (!is_email($params['mail'])) {
839 $errors[$emailName] = "Your email is invaid";
840 }
841 elseif (email_exists($params['mail'])) {
842 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
843 [1 => $params['mail'], 2 => wp_lostpassword_url()]
844 );
845 }
846 }
847 }
848
849 /**
850 * @inheritDoc
851 */
852 public function isUserLoggedIn() {
853 $isloggedIn = FALSE;
854 if (function_exists('is_user_logged_in')) {
855 $isloggedIn = is_user_logged_in();
856 }
857
858 return $isloggedIn;
859 }
860
861 /**
862 * @inheritDoc
863 */
864 public function isUserRegistrationPermitted() {
865 if (!get_option('users_can_register')) {
866 return FALSE;
867 }
868 return TRUE;
869 }
870
871 /**
872 * @inheritDoc
873 */
874 public function isPasswordUserGenerated() {
875 return TRUE;
876 }
877
878 /**
879 * @return mixed
880 */
881 public function getLoggedInUserObject() {
882 if (function_exists('is_user_logged_in') &&
883 is_user_logged_in()
884 ) {
885 global $current_user;
886 }
887 return $current_user;
888 }
889
890 /**
891 * @inheritDoc
892 */
893 public function getLoggedInUfID() {
894 $ufID = NULL;
895 $current_user = $this->getLoggedInUserObject();
896 return $current_user->ID ?? NULL;
897 }
898
899 /**
900 * @inheritDoc
901 */
902 public function getLoggedInUniqueIdentifier() {
903 $user = $this->getLoggedInUserObject();
904 return $this->getUniqueIdentifierFromUserObject($user);
905 }
906
907 /**
908 * Get User ID from UserFramework system (Joomla)
909 * @param object $user
910 * Object as described by the CMS.
911 *
912 * @return int|null
913 */
914 public function getUserIDFromUserObject($user) {
915 return !empty($user->ID) ? $user->ID : NULL;
916 }
917
918 /**
919 * @inheritDoc
920 */
921 public function getUniqueIdentifierFromUserObject($user) {
922 return empty($user->user_email) ? NULL : $user->user_email;
923 }
924
925 /**
926 * @inheritDoc
927 */
928 public function getLoginURL($destination = '') {
929 $config = CRM_Core_Config::singleton();
930 $loginURL = wp_login_url();
931 return $loginURL;
932 }
933
934 /**
935 * FIXME: Do something.
936 *
937 * @param \CRM_Core_Form $form
938 *
939 * @return NULL|string
940 */
941 public function getLoginDestination(&$form) {
942 return NULL;
943 }
944
945 /**
946 * @inheritDoc
947 */
948 public function getVersion() {
949 if (function_exists('get_bloginfo')) {
950 return get_bloginfo('version', 'display');
951 }
952 else {
953 return 'Unknown';
954 }
955 }
956
957 /**
958 * @inheritDoc
959 */
960 public function getTimeZoneString() {
961 return get_option('timezone_string');
962 }
963
964 /**
965 * @inheritDoc
966 */
967 public function getUserRecordUrl($contactID) {
968 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
969 if (CRM_Core_Session::singleton()
970 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(['cms:administer users'])
971 ) {
972 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
973 }
974 }
975
976 /**
977 * Append WP js to coreResourcesList.
978 *
979 * @param \Civi\Core\Event\GenericHookEvent $e
980 */
981 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) {
982 $e->list[] = 'js/crm.wordpress.js';
983 }
984
985 /**
986 * @inheritDoc
987 */
988 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent $e) {
989 // Set menubar breakpoint to match WP admin theme
990 if ($e->asset == 'crm-menubar.css') {
991 $e->params['breakpoint'] = 783;
992 }
993 }
994
995 /**
996 * @inheritDoc
997 */
998 public function synchronizeUsers() {
999 $config = CRM_Core_Config::singleton();
1000 if (PHP_SAPI != 'cli') {
1001 set_time_limit(300);
1002 }
1003 $id = 'ID';
1004 $mail = 'user_email';
1005
1006 $uf = $config->userFramework;
1007 $contactCount = 0;
1008 $contactCreated = 0;
1009 $contactMatching = 0;
1010
1011 // Previously used the $wpdb global - which means WordPress *must* be bootstrapped.
1012 $wpUsers = get_users(array(
1013 'blog_id' => get_current_blog_id(),
1014 'number' => -1,
1015 ));
1016
1017 foreach ($wpUsers as $wpUserData) {
1018 $contactCount++;
1019 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData,
1020 $wpUserData->$id,
1021 $wpUserData->$mail,
1022 $uf,
1023 1,
1024 'Individual',
1025 TRUE
1026 )
1027 ) {
1028 $contactCreated++;
1029 }
1030 else {
1031 $contactMatching++;
1032 }
1033 if (is_object($match)) {
1034 $match->free();
1035 }
1036 }
1037
1038 return [
1039 'contactCount' => $contactCount,
1040 'contactMatching' => $contactMatching,
1041 'contactCreated' => $contactCreated,
1042 ];
1043 }
1044
1045 /**
1046 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
1047 *
1048 * @param \Psr\Http\Message\ResponseInterface $response
1049 */
1050 public function sendResponse(\Psr\Http\Message\ResponseInterface $response) {
1051 // use WordPress function status_header to ensure 404 response is sent
1052 status_header($response->getStatusCode());
1053 foreach ($response->getHeaders() as $name => $values) {
1054 CRM_Utils_System::setHttpHeader($name, implode(', ', (array) $values));
1055 }
1056 echo $response->getBody();
1057 CRM_Utils_System::civiExit();
1058 }
1059
1060 /**
1061 * Start a new session if there's no existing session ID.
1062 *
1063 * Checks are needed to prevent sessions being started when not necessary.
1064 */
1065 public function sessionStart() {
1066 $session_id = session_id();
1067
1068 // Check WordPress pseudo-cron.
1069 $wp_cron = FALSE;
1070 if (function_exists('wp_doing_cron') && wp_doing_cron()) {
1071 $wp_cron = TRUE;
1072 }
1073
1074 // Check WP-CLI.
1075 $wp_cli = FALSE;
1076 if (defined('WP_CLI') && WP_CLI) {
1077 $wp_cli = TRUE;
1078 }
1079
1080 // Check PHP on the command line - e.g. `cv`.
1081 $php_cli = TRUE;
1082 if (PHP_SAPI !== 'cli') {
1083 $php_cli = FALSE;
1084 }
1085
1086 // Maybe start session.
1087 if (empty($session_id) && !$wp_cron && !$wp_cli && !$php_cli) {
1088 session_start();
1089 }
1090 }
1091
1092 /**
1093 * Perform any necessary actions prior to redirecting via POST.
1094 *
1095 * Redirecting via POST means that cookies need to be sent with SameSite=None.
1096 */
1097 public function prePostRedirect() {
1098 // Get User Agent string.
1099 $rawUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
1100 $userAgent = mb_convert_encoding($rawUserAgent, 'UTF-8');
1101
1102 // Bail early if User Agent does not support `SameSite=None`.
1103 $shouldUseSameSite = CRM_Utils_SameSite::shouldSendSameSiteNone($userAgent);
1104 if (!$shouldUseSameSite) {
1105 return;
1106 }
1107
1108 // Make sure session cookie is present in header.
1109 $cookie_params = session_name() . '=' . session_id() . '; SameSite=None; Secure';
1110 CRM_Utils_System::setHttpHeader('Set-Cookie', $cookie_params);
1111
1112 // Add WordPress auth cookies when user is logged in.
1113 $user = wp_get_current_user();
1114 if ($user->exists()) {
1115 self::setAuthCookies($user->ID, TRUE, TRUE);
1116 }
1117 }
1118
1119 /**
1120 * Explicitly set WordPress authentication cookies.
1121 *
1122 * Chrome 84 introduced a cookie policy change which prevents cookies for the
1123 * session and for WordPress user authentication from being indentified when
1124 * a purchaser returns to the site from PayPal using the "Back to Merchant"
1125 * button.
1126 *
1127 * In order to comply with this policy, cookies need to be sent with their
1128 * "SameSite" attribute set to "None" and with the "Secure" flag set, but this
1129 * isn't possible to do via `wp_set_auth_cookie()` as it stands.
1130 *
1131 * This method is a modified clone of `wp_set_auth_cookie()` which satisfies
1132 * the Chrome policy.
1133 *
1134 * @see wp_set_auth_cookie()
1135 *
1136 * The $remember parameter increases the time that the cookie will be kept. The
1137 * default the cookie is kept without remembering is two days. When $remember is
1138 * set, the cookies will be kept for 14 days or two weeks.
1139 *
1140 * @param int $user_id The WordPress User ID.
1141 * @param bool $remember Whether to remember the user.
1142 * @param bool|string $secure Whether the auth cookie should only be sent over
1143 * HTTPS. Default is an empty string which means the
1144 * value of `is_ssl()` will be used.
1145 * @param string $token Optional. User's session token to use for this cookie.
1146 */
1147 private function setAuthCookies($user_id, $remember = FALSE, $secure = '', $token = '') {
1148 if ($remember) {
1149 /** This filter is documented in wp-includes/pluggable.php */
1150 $expiration = time() + apply_filters('auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember);
1151
1152 /*
1153 * Ensure the browser will continue to send the cookie after the expiration time is reached.
1154 * Needed for the login grace period in wp_validate_auth_cookie().
1155 */
1156 $expire = $expiration + (12 * HOUR_IN_SECONDS);
1157 }
1158 else {
1159 /** This filter is documented in wp-includes/pluggable.php */
1160 $expiration = time() + apply_filters('auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember);
1161 $expire = 0;
1162 }
1163
1164 if ('' === $secure) {
1165 $secure = is_ssl();
1166 }
1167
1168 // Front-end cookie is secure when the auth cookie is secure and the site's home URL is forced HTTPS.
1169 $secure_logged_in_cookie = $secure && 'https' === parse_url(get_option('home'), PHP_URL_SCHEME);
1170
1171 /** This filter is documented in wp-includes/pluggable.php */
1172 $secure = apply_filters('secure_auth_cookie', $secure, $user_id);
1173
1174 /** This filter is documented in wp-includes/pluggable.php */
1175 $secure_logged_in_cookie = apply_filters('secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure);
1176
1177 if ($secure) {
1178 $auth_cookie_name = SECURE_AUTH_COOKIE;
1179 $scheme = 'secure_auth';
1180 }
1181 else {
1182 $auth_cookie_name = AUTH_COOKIE;
1183 $scheme = 'auth';
1184 }
1185
1186 if ('' === $token) {
1187 $manager = WP_Session_Tokens::get_instance($user_id);
1188 $token = $manager->create($expiration);
1189 }
1190
1191 $auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme, $token);
1192 $logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in', $token);
1193
1194 /** This filter is documented in wp-includes/pluggable.php */
1195 do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme, $token);
1196
1197 /** This filter is documented in wp-includes/pluggable.php */
1198 do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in', $token);
1199
1200 /** This filter is documented in wp-includes/pluggable.php */
1201 if (!apply_filters('send_auth_cookies', TRUE)) {
1202 return;
1203 }
1204
1205 $base_options = [
1206 'expires' => $expire,
1207 'domain' => COOKIE_DOMAIN,
1208 'httponly' => TRUE,
1209 'samesite' => 'None',
1210 ];
1211
1212 self::setAuthCookie($auth_cookie_name, $auth_cookie, $base_options + ['secure' => $secure, 'path' => PLUGINS_COOKIE_PATH]);
1213 self::setAuthCookie($auth_cookie_name, $auth_cookie, $base_options + ['secure' => $secure, 'path' => ADMIN_COOKIE_PATH]);
1214 self::setAuthCookie(LOGGED_IN_COOKIE, $logged_in_cookie, $base_options + ['secure' => $secure_logged_in_cookie, 'path' => COOKIEPATH]);
1215 if (COOKIEPATH != SITECOOKIEPATH) {
1216 self::setAuthCookie(LOGGED_IN_COOKIE, $logged_in_cookie, $base_options + ['secure' => $secure_logged_in_cookie, 'path' => SITECOOKIEPATH]);
1217 }
1218 }
1219
1220 /**
1221 * Set cookie with "SameSite" flag.
1222 *
1223 * The method here is compatible with all versions of PHP. Needed because it
1224 * is only as of PHP 7.3.0 that the setcookie() method supports the "SameSite"
1225 * attribute in its options and will accept "None" as a valid value.
1226 *
1227 * @param $name The name of the cookie.
1228 * @param $value The value of the cookie.
1229 * @param array $options The header options for the cookie.
1230 */
1231 private function setAuthCookie($name, $value, $options) {
1232 $header = 'Set-Cookie: ';
1233 $header .= rawurlencode($name) . '=' . rawurlencode($value) . '; ';
1234 $header .= 'expires=' . gmdate('D, d-M-Y H:i:s T', $options['expires']) . '; ';
1235 $header .= 'Max-Age=' . max(0, (int) ($options['expires'] - time())) . '; ';
1236 $header .= 'path=' . rawurlencode($options['path']) . '; ';
1237 $header .= 'domain=' . rawurlencode($options['domain']) . '; ';
1238
1239 if (!empty($options['secure'])) {
1240 $header .= 'secure; ';
1241 }
1242 $header .= 'httponly; ';
1243 $header .= 'SameSite=' . rawurlencode($options['samesite']);
1244
1245 header($header, FALSE);
1246 $_COOKIE[$name] = $value;
1247 }
1248
1249 /**
1250 * Return the CMS-specific url for its permissions page
1251 * @return array
1252 */
1253 public function getCMSPermissionsUrlParams() {
1254 return ['ufAccessURL' => CRM_Utils_System::url('civicrm/admin/access/wp-permissions', 'reset=1')];
1255 }
1256
1257 }