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