Merge pull request #18008 from civicrm/5.28
[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 */
25 public function __construct() {
26 /**
27 * 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
28 * functions and leave the codebase oblivious to the type of CMS
29 * @deprecated
30 * @var bool
31 */
32 $this->is_drupal = FALSE;
33 $this->is_wordpress = TRUE;
34 }
35
36 public function initialize() {
37 parent::initialize();
38 $this->registerPathVars();
39 }
40
41 /**
42 * Specify the default computation for various paths/URLs.
43 */
44 protected function registerPathVars():void {
45 $isNormalBoot = function_exists('get_option');
46 if ($isNormalBoot) {
47 // Normal mode - CMS boots first, then calls Civi. "Normal" web pages and newer extern routes.
48 // To simplify the code-paths, some items are re-registered with WP-specific functions.
49 $cmsRoot = function() {
50 return [
51 'path' => untrailingslashit(ABSPATH),
52 'url' => home_url(),
53 ];
54 };
55 Civi::paths()->register('cms', $cmsRoot);
56 Civi::paths()->register('cms.root', $cmsRoot);
57 Civi::paths()->register('civicrm.root', function () {
58 return [
59 'path' => CIVICRM_PLUGIN_DIR . 'civicrm' . DIRECTORY_SEPARATOR,
60 'url' => CIVICRM_PLUGIN_URL . 'civicrm/',
61 ];
62 });
63 Civi::paths()->register('wp.frontend.base', function () {
64 return [
65 'url' => home_url('/'),
66 ];
67 });
68 Civi::paths()->register('wp.frontend', function () {
69 $config = CRM_Core_Config::singleton();
70 $basepage = get_page_by_path($config->wpBasePage);
71 return [
72 'url' => get_permalink($basepage->ID),
73 ];
74 });
75 Civi::paths()->register('wp.backend.base', function () {
76 return [
77 'url' => admin_url(),
78 ];
79 });
80 Civi::paths()->register('wp.backend', function() {
81 return [
82 'url' => admin_url('admin.php'),
83 ];
84 });
85 }
86 else {
87 // Legacy support - only relevant for older extern routes.
88 Civi::paths()
89 ->register('wp.frontend.base', function () {
90 return ['url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/'];
91 })
92 ->register('wp.frontend', function () {
93 $config = \CRM_Core_Config::singleton();
94 $suffix = defined('CIVICRM_UF_WP_BASEPAGE') ? CIVICRM_UF_WP_BASEPAGE : $config->wpBasePage;
95 return [
96 'url' => Civi::paths()->getVariable('wp.frontend.base', 'url') . $suffix,
97 ];
98 })
99 ->register('wp.backend.base', function () {
100 return ['url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/wp-admin/'];
101 })
102 ->register('wp.backend', function () {
103 return [
104 'url' => Civi::paths()->getVariable('wp.backend.base', 'url') . 'admin.php',
105 ];
106 });
107 }
108 }
109
110 /**
111 * @inheritDoc
112 */
113 public function setTitle($title, $pageTitle = NULL) {
114 if (!$pageTitle) {
115 $pageTitle = $title;
116 }
117
118 // FIXME: Why is this global?
119 global $civicrm_wp_title;
120 $civicrm_wp_title = $title;
121
122 // yes, set page title, depending on context
123 $context = civi_wp()->civicrm_context_get();
124 switch ($context) {
125 case 'admin':
126 case 'shortcode':
127 $template = CRM_Core_Smarty::singleton();
128 $template->assign('pageTitle', $pageTitle);
129 }
130 }
131
132 /**
133 * Moved from CRM_Utils_System_Base
134 */
135 public function getDefaultFileStorage() {
136 $config = CRM_Core_Config::singleton();
137 $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
138 $cmsPath = $this->cmsRootPath();
139 $filesPath = CRM_Utils_File::baseFilePath();
140 $filesRelPath = CRM_Utils_File::relativize($filesPath, $cmsPath);
141 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
142 return [
143 'url' => CRM_Utils_File::addTrailingSlash($filesURL, '/'),
144 'path' => CRM_Utils_File::addTrailingSlash($filesPath),
145 ];
146 }
147
148 /**
149 * Determine the location of the CiviCRM source tree.
150 *
151 * @return array
152 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
153 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
154 */
155 public function getCiviSourceStorage() {
156 global $civicrm_root;
157
158 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
159 // More generally, we shouldn't be using $config here.
160 if (!defined('CIVICRM_UF_BASEURL')) {
161 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
162 }
163
164 $cmsPath = $this->cmsRootPath();
165
166 // $config = CRM_Core_Config::singleton();
167 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
168 $cmsUrl = CIVICRM_UF_BASEURL;
169 if (CRM_Utils_System::isSSL()) {
170 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
171 }
172 $civiRelPath = CRM_Utils_File::relativize(realpath($civicrm_root), realpath($cmsPath));
173 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
174 return [
175 'url' => CRM_Utils_File::addTrailingSlash($civiUrl, '/'),
176 'path' => CRM_Utils_File::addTrailingSlash($civicrm_root),
177 ];
178 }
179
180 /**
181 * @inheritDoc
182 */
183 public function appendBreadCrumb($breadCrumbs) {
184 $breadCrumb = wp_get_breadcrumb();
185
186 if (is_array($breadCrumbs)) {
187 foreach ($breadCrumbs as $crumbs) {
188 if (stripos($crumbs['url'], 'id%%')) {
189 $args = ['cid', 'mid'];
190 foreach ($args as $a) {
191 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
192 FALSE, NULL, $_GET
193 );
194 if ($val) {
195 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
196 }
197 }
198 }
199 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
200 }
201 }
202
203 $template = CRM_Core_Smarty::singleton();
204 $template->assign_by_ref('breadcrumb', $breadCrumb);
205 wp_set_breadcrumb($breadCrumb);
206 }
207
208 /**
209 * @inheritDoc
210 */
211 public function resetBreadCrumb() {
212 $bc = [];
213 wp_set_breadcrumb($bc);
214 }
215
216 /**
217 * @inheritDoc
218 */
219 public function addHTMLHead($head) {
220 static $registered = FALSE;
221 if (!$registered) {
222 // front-end view
223 add_action('wp_head', [__CLASS__, '_showHTMLHead']);
224 // back-end views
225 add_action('admin_head', [__CLASS__, '_showHTMLHead']);
226 }
227 CRM_Core_Region::instance('wp_head')->add([
228 'markup' => $head,
229 ]);
230 }
231
232 /**
233 * WP action callback.
234 */
235 public static function _showHTMLHead() {
236 $region = CRM_Core_Region::instance('wp_head', FALSE);
237 if ($region) {
238 echo $region->render('');
239 }
240 }
241
242 /**
243 * @inheritDoc
244 */
245 public function mapConfigToSSL() {
246 global $base_url;
247 $base_url = str_replace('http://', 'https://', $base_url);
248 }
249
250 /**
251 * @inheritDoc
252 */
253 public function url(
254 $path = NULL,
255 $query = NULL,
256 $absolute = FALSE,
257 $fragment = NULL,
258 $frontend = FALSE,
259 $forceBackend = FALSE,
260 $htmlize = TRUE
261 ) {
262 $config = CRM_Core_Config::singleton();
263 $script = '';
264 $separator = '&';
265 $wpPageParam = '';
266 $fragment = isset($fragment) ? ('#' . $fragment) : '';
267
268 $path = CRM_Utils_String::stripPathChars($path);
269 $basepage = FALSE;
270
271 //this means wp function we are trying to use is not available,
272 //so load bootStrap
273 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
274 if (!function_exists('get_option')) {
275 $this->loadBootStrap();
276 }
277
278 if ($config->userFrameworkFrontend) {
279 global $post;
280 if (get_option('permalink_structure') != '') {
281 $script = get_permalink($post->ID);
282 }
283 if ($config->wpBasePage == $post->post_name) {
284 $basepage = TRUE;
285 }
286 // when shortcode is included in page
287 // also make sure we have valid query object
288 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
289 global $wp_query;
290 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
291 if (get_query_var('page_id')) {
292 $wpPageParam = "page_id=" . get_query_var('page_id');
293 }
294 elseif (get_query_var('p')) {
295 // when shortcode is inserted in post
296 $wpPageParam = "p=" . get_query_var('p');
297 }
298 }
299 }
300
301 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
302
303 if (!isset($path) && !isset($query)) {
304 // FIXME: This short-circuited codepath is the same as the general one below, except
305 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
306 // why it's different (and I can only find two obvious use-cases for this codepath,
307 // of which at least one looks gratuitous). A more ambitious person would simply remove
308 // this code.
309 return $base . $fragment;
310 }
311
312 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam || $script != '')) {
313 $base = $script;
314 }
315
316 $queryParts = [];
317
318 if (
319 // not using clean URLs
320 !$config->cleanURL
321 // requesting an admin URL
322 || ((is_admin() && !$frontend) || $forceBackend)
323 // is shortcode
324 || (!$basepage && $script != '')
325 ) {
326
327 // pre-existing logic
328 if (isset($path)) {
329 // Admin URLs still need "page=CiviCRM", front-end URLs do not.
330 if ((is_admin() && !$frontend) || $forceBackend) {
331 $queryParts[] = 'page=CiviCRM';
332 }
333 else {
334 $queryParts[] = 'civiwp=CiviCRM';
335 }
336 $queryParts[] = 'q=' . rawurlencode($path);
337 }
338 if ($wpPageParam) {
339 $queryParts[] = $wpPageParam;
340 }
341 if (!empty($query)) {
342 $queryParts[] = $query;
343 }
344
345 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
346
347 }
348 else {
349
350 // clean URLs
351 if (isset($path)) {
352 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
353 }
354 if (isset($query)) {
355 $query = ltrim($query, '=?&');
356 $queryParts[] = $query;
357 }
358
359 if (!empty($queryParts)) {
360 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
361 }
362 else {
363 $final = $base . $fragment;
364 }
365
366 }
367
368 return $final;
369 }
370
371 /**
372 * 27-09-2016
373 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
374 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
375 * For now leave hard coded wp-admin references.
376 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
377 *
378 * @param $absolute
379 * @param $frontend
380 * @param $forceBackend
381 *
382 * @return mixed|null|string
383 */
384 private function getBaseUrl($absolute, $frontend, $forceBackend) {
385 $config = CRM_Core_Config::singleton();
386 if ((is_admin() && !$frontend) || $forceBackend) {
387 return Civi::paths()->getUrl('[wp.backend]/.', $absolute ? 'absolute' : 'relative');
388 }
389 else {
390 return Civi::paths()->getUrl('[wp.frontend]/.', $absolute ? 'absolute' : 'relative');
391 }
392 }
393
394 /**
395 * @inheritDoc
396 */
397 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
398 $config = CRM_Core_Config::singleton();
399
400 if ($loadCMSBootstrap) {
401 $config->userSystem->loadBootStrap([
402 'name' => $name,
403 'pass' => $password,
404 ]);
405 }
406
407 $user = wp_authenticate($name, $password);
408 if (is_a($user, 'WP_Error')) {
409 return FALSE;
410 }
411
412 // TODO: need to change this to make sure we matched only one row
413
414 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
415 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
416 if (!$contactID) {
417 return FALSE;
418 }
419 return [$contactID, $user->data->ID, mt_rand()];
420 }
421
422 /**
423 * FIXME: Do something
424 *
425 * @param string $message
426 */
427 public function setMessage($message) {
428 }
429
430 /**
431 * @param \string $user
432 *
433 * @return bool
434 */
435 public function loadUser($user) {
436 $userdata = get_user_by('login', $user);
437 if (!$userdata->data->ID) {
438 return FALSE;
439 }
440
441 $uid = $userdata->data->ID;
442 wp_set_current_user($uid);
443 $contactID = CRM_Core_BAO_UFMatch::getContactId($uid);
444
445 // lets store contact id and user id in session
446 $session = CRM_Core_Session::singleton();
447 $session->set('ufID', $uid);
448 $session->set('userID', $contactID);
449 return TRUE;
450 }
451
452 /**
453 * FIXME: Use CMS-native approach
454 * @throws \CRM_Core_Exception
455 */
456 public function permissionDenied() {
457 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
458 }
459
460 /**
461 * Determine the native ID of the CMS user.
462 *
463 * @param string $username
464 *
465 * @return int|null
466 */
467 public function getUfId($username) {
468 $userdata = get_user_by('login', $username);
469 if (!$userdata->data->ID) {
470 return NULL;
471 }
472 return $userdata->data->ID;
473 }
474
475 /**
476 * @inheritDoc
477 */
478 public function logout() {
479 // destroy session
480 if (session_id()) {
481 session_destroy();
482 }
483 wp_logout();
484 wp_redirect(wp_login_url());
485 }
486
487 /**
488 * @inheritDoc
489 */
490 public function getUFLocale() {
491 // Bail early if method is called when WordPress isn't bootstrapped.
492 // Additionally, the function checked here is located in pluggable.php
493 // and is required by wp_get_referer() - so this also bails early if it is
494 // called too early in the request lifecycle.
495 // @see https://core.trac.wordpress.org/ticket/25294
496 if (!function_exists('wp_validate_redirect')) {
497 return NULL;
498 }
499
500 // Default to WordPress User locale.
501 $locale = get_user_locale();
502
503 // Is this a "back-end" AJAX call?
504 $is_backend = FALSE;
505 if (wp_doing_ajax() && FALSE !== strpos(wp_get_referer(), admin_url())) {
506 $is_backend = TRUE;
507 }
508
509 // Ignore when in WordPress admin or it's a "back-end" AJAX call.
510 if (!(is_admin() || $is_backend)) {
511
512 // Reaching here means it is very likely to be a front-end context.
513
514 // Default to WordPress locale.
515 $locale = get_locale();
516
517 // Maybe override with the locale that Polylang reports.
518 if (function_exists('pll_current_language')) {
519 $pll_locale = pll_current_language('locale');
520 if (!empty($pll_locale)) {
521 $locale = $pll_locale;
522 }
523 }
524
525 // Maybe override with the locale that WPML reports.
526 elseif (defined('ICL_LANGUAGE_CODE')) {
527 $languages = apply_filters('wpml_active_languages', NULL);
528 foreach ($languages as $language) {
529 if ($language['active']) {
530 $locale = $language['default_locale'];
531 break;
532 }
533 }
534 }
535
536 // TODO: Set locale for other WordPress plugins.
537 // @see https://wordpress.org/plugins/tags/multilingual/
538 // A hook would be nice here.
539
540 }
541
542 if (!empty($locale)) {
543 // If for some reason only we get a language code, convert it to a locale.
544 if (2 === strlen($locale)) {
545 $locale = CRM_Core_I18n_PseudoConstant::longForShort($locale);
546 }
547 return $locale;
548 }
549 else {
550 return NULL;
551 }
552 }
553
554 /**
555 * @inheritDoc
556 */
557 public function setUFLocale($civicrm_language) {
558 // TODO (probably not possible with WPML?)
559 return TRUE;
560 }
561
562 /**
563 * Load wordpress bootstrap.
564 *
565 * @param array $params
566 * Optional credentials
567 * - name: string, cms username
568 * - pass: string, cms password
569 * @param bool $loadUser
570 * @param bool $throwError
571 * @param mixed $realPath
572 *
573 * @return bool
574 * @throws \CRM_Core_Exception
575 */
576 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
577 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
578
579 $name = $params['name'] ?? NULL;
580 $pass = $params['pass'] ?? NULL;
581
582 if (!defined('WP_USE_THEMES')) {
583 define('WP_USE_THEMES', FALSE);
584 }
585
586 $cmsRootPath = $this->cmsRootPath();
587 if (!$cmsRootPath) {
588 throw new CRM_Core_Exception("Could not find the install directory for WordPress");
589 }
590 $path = Civi::settings()->get('wpLoadPhp');
591 if (!empty($path)) {
592 require_once $path;
593 }
594 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) {
595 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
596 }
597 else {
598 throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress");
599 }
600 $wpUserTimezone = get_option('timezone_string');
601 if ($wpUserTimezone) {
602 date_default_timezone_set($wpUserTimezone);
603 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
604 }
605 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
606 $uid = $params['uid'] ?? NULL;
607 if (!$uid) {
608 $name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST));
609 $pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST));
610 if ($name) {
611 $uid = wp_authenticate($name, $pass);
612 if (!$uid) {
613 if ($throwError) {
614 echo '<br />Sorry, unrecognized username or password.';
615 exit();
616 }
617 return FALSE;
618 }
619 }
620 }
621 if ($uid) {
622 if ($uid instanceof WP_User) {
623 $account = wp_set_current_user($uid->ID);
624 }
625 else {
626 $account = wp_set_current_user($uid);
627 }
628 if ($account && $account->data->ID) {
629 global $user;
630 $user = $account;
631 return TRUE;
632 }
633 }
634 return TRUE;
635 }
636
637 /**
638 * @param $dir
639 *
640 * @return bool
641 */
642 public function validInstallDir($dir) {
643 $includePath = "$dir/wp-includes";
644 if (@file_exists("$includePath/version.php")) {
645 return TRUE;
646 }
647 return FALSE;
648 }
649
650 /**
651 * Determine the location of the CMS root.
652 *
653 * @return string|NULL
654 * local file system path to CMS root, or NULL if it cannot be determined
655 */
656 public function cmsRootPath() {
657
658 // Return early if the path is already set.
659 global $civicrm_paths;
660 if (!empty($civicrm_paths['cms.root']['path'])) {
661 return $civicrm_paths['cms.root']['path'];
662 }
663
664 // Return early if constant has been defined.
665 if (defined('CIVICRM_CMSDIR')) {
666 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
667 return CIVICRM_CMSDIR;
668 }
669 }
670
671 // Return early if path to wp-load.php can be retrieved from settings.
672 $setting = Civi::settings()->get('wpLoadPhp');
673 if (!empty($setting)) {
674 $path = str_replace('wp-load.php', '', $setting);
675 $cmsRoot = rtrim($path, '/\\');
676 if ($this->validInstallDir($cmsRoot)) {
677 return $cmsRoot;
678 }
679 }
680
681 /*
682 * Keep previous logic as fallback of last resort.
683 *
684 * At some point, it would be good to remove this because there are serious
685 * problems in correctly locating WordPress in this manner. In summary, it
686 * is impossible to do so reliably.
687 *
688 * @see https://github.com/civicrm/civicrm-wordpress/pull/63#issuecomment-61792328
689 * @see https://github.com/civicrm/civicrm-core/pull/11086#issuecomment-335454992
690 */
691 $cmsRoot = $valid = NULL;
692
693 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
694
695 // Might be Windows installation.
696 $firstVar = array_shift($pathVars);
697 if ($firstVar) {
698 $cmsRoot = $firstVar;
699 }
700
701 // Start with CMS dir search.
702 foreach ($pathVars as $var) {
703 $cmsRoot .= "/$var";
704 if ($this->validInstallDir($cmsRoot)) {
705 // Stop as we found bootstrap.
706 $valid = TRUE;
707 break;
708 }
709 }
710
711 return ($valid) ? $cmsRoot : NULL;
712 }
713
714 /**
715 * @inheritDoc
716 */
717 public function createUser(&$params, $mail) {
718 $user_data = [
719 'ID' => '',
720 'user_pass' => $params['cms_pass'],
721 'user_login' => $params['cms_name'],
722 'user_email' => $params[$mail],
723 'nickname' => $params['cms_name'],
724 'role' => get_option('default_role'),
725 ];
726 if (isset($params['contactID'])) {
727 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
728 if ($contactType == 'Individual') {
729 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
730 $params['contactID'], 'first_name'
731 );
732 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
733 $params['contactID'], 'last_name'
734 );
735 }
736 }
737
738 $uid = wp_insert_user($user_data);
739
740 $creds = [];
741 $creds['user_login'] = $params['cms_name'];
742 $creds['user_password'] = $params['cms_pass'];
743 $creds['remember'] = TRUE;
744 $user = wp_signon($creds, FALSE);
745
746 wp_new_user_notification($uid, $user_data['user_pass']);
747 return $uid;
748 }
749
750 /**
751 * @inheritDoc
752 */
753 public function updateCMSName($ufID, $ufName) {
754 // CRM-10620
755 if (function_exists('wp_update_user')) {
756 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
757 $ufName = CRM_Utils_Type::escape($ufName, 'String');
758
759 $values = ['ID' => $ufID, 'user_email' => $ufName];
760 if ($ufID) {
761 wp_update_user($values);
762 }
763 }
764 }
765
766 /**
767 * @param array $params
768 * @param $errors
769 * @param string $emailName
770 */
771 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
772 $config = CRM_Core_Config::singleton();
773
774 $dao = new CRM_Core_DAO();
775 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
776 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
777
778 if (!empty($params['name'])) {
779 if (!validate_username($params['name'])) {
780 $errors['cms_name'] = ts("Your username contains invalid characters");
781 }
782 elseif (username_exists(sanitize_user($params['name']))) {
783 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
784 }
785 }
786
787 if (!empty($params['mail'])) {
788 if (!is_email($params['mail'])) {
789 $errors[$emailName] = "Your email is invaid";
790 }
791 elseif (email_exists($params['mail'])) {
792 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
793 [1 => $params['mail'], 2 => wp_lostpassword_url()]
794 );
795 }
796 }
797 }
798
799 /**
800 * @inheritDoc
801 */
802 public function isUserLoggedIn() {
803 $isloggedIn = FALSE;
804 if (function_exists('is_user_logged_in')) {
805 $isloggedIn = is_user_logged_in();
806 }
807
808 return $isloggedIn;
809 }
810
811 /**
812 * @inheritDoc
813 */
814 public function isUserRegistrationPermitted() {
815 if (!get_option('users_can_register')) {
816 return FALSE;
817 }
818 return TRUE;
819 }
820
821 /**
822 * @inheritDoc
823 */
824 public function isPasswordUserGenerated() {
825 return TRUE;
826 }
827
828 /**
829 * @return mixed
830 */
831 public function getLoggedInUserObject() {
832 if (function_exists('is_user_logged_in') &&
833 is_user_logged_in()
834 ) {
835 global $current_user;
836 }
837 return $current_user;
838 }
839
840 /**
841 * @inheritDoc
842 */
843 public function getLoggedInUfID() {
844 $ufID = NULL;
845 $current_user = $this->getLoggedInUserObject();
846 return $current_user->ID ?? NULL;
847 }
848
849 /**
850 * @inheritDoc
851 */
852 public function getLoggedInUniqueIdentifier() {
853 $user = $this->getLoggedInUserObject();
854 return $this->getUniqueIdentifierFromUserObject($user);
855 }
856
857 /**
858 * Get User ID from UserFramework system (Joomla)
859 * @param object $user
860 * Object as described by the CMS.
861 *
862 * @return int|null
863 */
864 public function getUserIDFromUserObject($user) {
865 return !empty($user->ID) ? $user->ID : NULL;
866 }
867
868 /**
869 * @inheritDoc
870 */
871 public function getUniqueIdentifierFromUserObject($user) {
872 return empty($user->user_email) ? NULL : $user->user_email;
873 }
874
875 /**
876 * @inheritDoc
877 */
878 public function getLoginURL($destination = '') {
879 $config = CRM_Core_Config::singleton();
880 $loginURL = wp_login_url();
881 return $loginURL;
882 }
883
884 /**
885 * FIXME: Do something.
886 *
887 * @param \CRM_Core_Form $form
888 *
889 * @return NULL|string
890 */
891 public function getLoginDestination(&$form) {
892 return NULL;
893 }
894
895 /**
896 * @inheritDoc
897 */
898 public function getVersion() {
899 if (function_exists('get_bloginfo')) {
900 return get_bloginfo('version', 'display');
901 }
902 else {
903 return 'Unknown';
904 }
905 }
906
907 /**
908 * @inheritDoc
909 */
910 public function getTimeZoneString() {
911 return get_option('timezone_string');
912 }
913
914 /**
915 * @inheritDoc
916 */
917 public function getUserRecordUrl($contactID) {
918 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
919 if (CRM_Core_Session::singleton()
920 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(['cms:administer users'])
921 ) {
922 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
923 }
924 }
925
926 /**
927 * Append WP js to coreResourcesList.
928 *
929 * @param \Civi\Core\Event\GenericHookEvent $e
930 */
931 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) {
932 $e->list[] = 'js/crm.wordpress.js';
933 }
934
935 /**
936 * @inheritDoc
937 */
938 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent $e) {
939 // Set menubar breakpoint to match WP admin theme
940 if ($e->asset == 'crm-menubar.css') {
941 $e->params['breakpoint'] = 783;
942 }
943 }
944
945 /**
946 * @inheritDoc
947 */
948 public function synchronizeUsers() {
949 $config = CRM_Core_Config::singleton();
950 if (PHP_SAPI != 'cli') {
951 set_time_limit(300);
952 }
953 $id = 'ID';
954 $mail = 'user_email';
955
956 $uf = $config->userFramework;
957 $contactCount = 0;
958 $contactCreated = 0;
959 $contactMatching = 0;
960
961 // Previously used the $wpdb global - which means WordPress *must* be bootstrapped.
962 $wpUsers = get_users(array(
963 'blog_id' => get_current_blog_id(),
964 'number' => -1,
965 ));
966
967 foreach ($wpUsers as $wpUserData) {
968 $contactCount++;
969 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData,
970 $wpUserData->$id,
971 $wpUserData->$mail,
972 $uf,
973 1,
974 'Individual',
975 TRUE
976 )
977 ) {
978 $contactCreated++;
979 }
980 else {
981 $contactMatching++;
982 }
983 if (is_object($match)) {
984 $match->free();
985 }
986 }
987
988 return [
989 'contactCount' => $contactCount,
990 'contactMatching' => $contactMatching,
991 'contactCreated' => $contactCreated,
992 ];
993 }
994
995 /**
996 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
997 *
998 * @param \Psr\Http\Message\ResponseInterface $response
999 */
1000 public function sendResponse(\Psr\Http\Message\ResponseInterface $response) {
1001 // use WordPress function status_header to ensure 404 response is sent
1002 status_header($response->getStatusCode());
1003 foreach ($response->getHeaders() as $name => $values) {
1004 CRM_Utils_System::setHttpHeader($name, implode(', ', (array) $values));
1005 }
1006 echo $response->getBody();
1007 CRM_Utils_System::civiExit();
1008 }
1009
1010 /**
1011 * Start a new session if there's no existing session ID.
1012 *
1013 * Checks are needed to prevent sessions being started when not necessary.
1014 */
1015 public function sessionStart() {
1016 $session_id = session_id();
1017
1018 // Check WordPress pseudo-cron.
1019 $wp_cron = FALSE;
1020 if (function_exists('wp_doing_cron') && wp_doing_cron()) {
1021 $wp_cron = TRUE;
1022 }
1023
1024 // Check WP-CLI.
1025 $wp_cli = FALSE;
1026 if (defined('WP_CLI') && WP_CLI) {
1027 $wp_cli = TRUE;
1028 }
1029
1030 // Check PHP on the command line - e.g. `cv`.
1031 $php_cli = TRUE;
1032 if (PHP_SAPI !== 'cli') {
1033 $php_cli = FALSE;
1034 }
1035
1036 // Maybe start session.
1037 if (empty($session_id) && !$wp_cron && !$wp_cli && !$php_cli) {
1038 session_start();
1039 }
1040 }
1041
1042 }