Merge pull request #17374 from totten/master-setlocale
[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 ) {
270 $config = CRM_Core_Config::singleton();
271 $script = '';
272 $separator = '&';
273 $wpPageParam = '';
274 $fragment = isset($fragment) ? ('#' . $fragment) : '';
275
276 $path = CRM_Utils_String::stripPathChars($path);
277 $basepage = FALSE;
278
279 //this means wp function we are trying to use is not available,
280 //so load bootStrap
281 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
282 if (!function_exists('get_option')) {
283 $this->loadBootStrap();
284 }
285
286 if ($config->userFrameworkFrontend) {
287 global $post;
288 if (get_option('permalink_structure') != '') {
289 $script = get_permalink($post->ID);
290 }
291 if ($config->wpBasePage == $post->post_name) {
292 $basepage = TRUE;
293 }
294 // when shortcode is included in page
295 // also make sure we have valid query object
296 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
297 global $wp_query;
298 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
299 if (get_query_var('page_id')) {
300 $wpPageParam = "page_id=" . get_query_var('page_id');
301 }
302 elseif (get_query_var('p')) {
303 // when shortcode is inserted in post
304 $wpPageParam = "p=" . get_query_var('p');
305 }
306 }
307 }
308
309 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
310
311 if (!isset($path) && !isset($query)) {
312 // FIXME: This short-circuited codepath is the same as the general one below, except
313 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
314 // why it's different (and I can only find two obvious use-cases for this codepath,
315 // of which at least one looks gratuitous). A more ambitious person would simply remove
316 // this code.
317 return $base . $fragment;
318 }
319
320 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam || $script != '')) {
321 $base = $script;
322 }
323
324 $queryParts = [];
325
326 if (
327 // not using clean URLs
328 !$config->cleanURL
329 // requesting an admin URL
330 || ((is_admin() && !$frontend) || $forceBackend)
331 // is shortcode
332 || (!$basepage && $script != '')
333 ) {
334
335 // pre-existing logic
336 if (isset($path)) {
337 // Admin URLs still need "page=CiviCRM", front-end URLs do not.
338 if ((is_admin() && !$frontend) || $forceBackend) {
339 $queryParts[] = 'page=CiviCRM';
340 }
341 else {
342 $queryParts[] = 'civiwp=CiviCRM';
343 }
344 $queryParts[] = 'q=' . rawurlencode($path);
345 }
346 if ($wpPageParam) {
347 $queryParts[] = $wpPageParam;
348 }
349 if (!empty($query)) {
350 $queryParts[] = $query;
351 }
352
353 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
354
355 }
356 else {
357
358 // clean URLs
359 if (isset($path)) {
360 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
361 }
362 if (isset($query)) {
363 $query = ltrim($query, '=?&');
364 $queryParts[] = $query;
365 }
366
367 if (!empty($queryParts)) {
368 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
369 }
370 else {
371 $final = $base . $fragment;
372 }
373
374 }
375
376 return $final;
377 }
378
379 /**
380 * 27-09-2016
381 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
382 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
383 * For now leave hard coded wp-admin references.
384 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
385 *
386 * @param $absolute
387 * @param $frontend
388 * @param $forceBackend
389 *
390 * @return mixed|null|string
391 */
392 private function getBaseUrl($absolute, $frontend, $forceBackend) {
393 $config = CRM_Core_Config::singleton();
394 if ((is_admin() && !$frontend) || $forceBackend) {
395 return Civi::paths()->getUrl('[wp.backend]/.', $absolute ? 'absolute' : 'relative');
396 }
397 else {
398 return Civi::paths()->getUrl('[wp.frontend]/.', $absolute ? 'absolute' : 'relative');
399 }
400 }
401
402 /**
403 * @inheritDoc
404 */
405 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
406 $config = CRM_Core_Config::singleton();
407
408 if ($loadCMSBootstrap) {
409 $config->userSystem->loadBootStrap([
410 'name' => $name,
411 'pass' => $password,
412 ]);
413 }
414
415 $user = wp_authenticate($name, $password);
416 if (is_a($user, 'WP_Error')) {
417 return FALSE;
418 }
419
420 // TODO: need to change this to make sure we matched only one row
421
422 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
423 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
424 if (!$contactID) {
425 return FALSE;
426 }
427 return [$contactID, $user->data->ID, mt_rand()];
428 }
429
430 /**
431 * FIXME: Do something
432 *
433 * @param string $message
434 */
435 public function setMessage($message) {
436 }
437
438 /**
439 * @param \string $user
440 *
441 * @return bool
442 */
443 public function loadUser($user) {
444 $userdata = get_user_by('login', $user);
445 if (!$userdata->data->ID) {
446 return FALSE;
447 }
448
449 $uid = $userdata->data->ID;
450 wp_set_current_user($uid);
451 $contactID = CRM_Core_BAO_UFMatch::getContactId($uid);
452
453 // lets store contact id and user id in session
454 $session = CRM_Core_Session::singleton();
455 $session->set('ufID', $uid);
456 $session->set('userID', $contactID);
457 return TRUE;
458 }
459
460 /**
461 * FIXME: Use CMS-native approach
462 * @throws \CRM_Core_Exception
463 */
464 public function permissionDenied() {
465 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
466 }
467
468 /**
469 * Determine the native ID of the CMS user.
470 *
471 * @param string $username
472 *
473 * @return int|null
474 */
475 public function getUfId($username) {
476 $userdata = get_user_by('login', $username);
477 if (!$userdata->data->ID) {
478 return NULL;
479 }
480 return $userdata->data->ID;
481 }
482
483 /**
484 * @inheritDoc
485 */
486 public function logout() {
487 // destroy session
488 if (session_id()) {
489 session_destroy();
490 }
491 wp_logout();
492 wp_redirect(wp_login_url());
493 }
494
495 /**
496 * @inheritDoc
497 */
498 public function getUFLocale() {
499 // Bail early if method is called when WordPress isn't bootstrapped.
500 // Additionally, the function checked here is located in pluggable.php
501 // and is required by wp_get_referer() - so this also bails early if it is
502 // called too early in the request lifecycle.
503 // @see https://core.trac.wordpress.org/ticket/25294
504 if (!function_exists('wp_validate_redirect')) {
505 return NULL;
506 }
507
508 // Default to WordPress User locale.
509 $locale = get_user_locale();
510
511 // Is this a "back-end" AJAX call?
512 $is_backend = FALSE;
513 if (wp_doing_ajax() && FALSE !== strpos(wp_get_referer(), admin_url())) {
514 $is_backend = TRUE;
515 }
516
517 // Ignore when in WordPress admin or it's a "back-end" AJAX call.
518 if (!(is_admin() || $is_backend)) {
519
520 // Reaching here means it is very likely to be a front-end context.
521
522 // Default to WordPress locale.
523 $locale = get_locale();
524
525 // Maybe override with the locale that Polylang reports.
526 if (function_exists('pll_current_language')) {
527 $pll_locale = pll_current_language('locale');
528 if (!empty($pll_locale)) {
529 $locale = $pll_locale;
530 }
531 }
532
533 // Maybe override with the locale that WPML reports.
534 elseif (defined('ICL_LANGUAGE_CODE')) {
535 $languages = apply_filters('wpml_active_languages', NULL);
536 foreach ($languages as $language) {
537 if ($language['active']) {
538 $locale = $language['default_locale'];
539 break;
540 }
541 }
542 }
543
544 // TODO: Set locale for other WordPress plugins.
545 // @see https://wordpress.org/plugins/tags/multilingual/
546 // A hook would be nice here.
547
548 }
549
550 if (!empty($locale)) {
551 // If for some reason only we get a language code, convert it to a locale.
552 if (2 === strlen($locale)) {
553 $locale = CRM_Core_I18n_PseudoConstant::longForShort($locale);
554 }
555 return $locale;
556 }
557 else {
558 return NULL;
559 }
560 }
561
562 /**
563 * @inheritDoc
564 */
565 public function setUFLocale($civicrm_language) {
566 // TODO (probably not possible with WPML?)
567 return TRUE;
568 }
569
570 /**
571 * Load wordpress bootstrap.
572 *
573 * @param array $params
574 * Optional credentials
575 * - name: string, cms username
576 * - pass: string, cms password
577 * @param bool $loadUser
578 * @param bool $throwError
579 * @param mixed $realPath
580 *
581 * @return bool
582 * @throws \CRM_Core_Exception
583 */
584 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
585 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
586
587 $name = $params['name'] ?? NULL;
588 $pass = $params['pass'] ?? NULL;
589
590 if (!defined('WP_USE_THEMES')) {
591 define('WP_USE_THEMES', FALSE);
592 }
593
594 $cmsRootPath = $this->cmsRootPath();
595 if (!$cmsRootPath) {
596 throw new CRM_Core_Exception("Could not find the install directory for WordPress");
597 }
598 $path = Civi::settings()->get('wpLoadPhp');
599 if (!empty($path)) {
600 require_once $path;
601 }
602 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) {
603 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
604 }
605 else {
606 throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress");
607 }
608 $wpUserTimezone = get_option('timezone_string');
609 if ($wpUserTimezone) {
610 date_default_timezone_set($wpUserTimezone);
611 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
612 }
613 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
614 $uid = $params['uid'] ?? NULL;
615 if (!$uid) {
616 $name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST));
617 $pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST));
618 if ($name) {
619 $uid = wp_authenticate($name, $pass);
620 if (!$uid) {
621 if ($throwError) {
622 echo '<br />Sorry, unrecognized username or password.';
623 exit();
624 }
625 return FALSE;
626 }
627 }
628 }
629 if ($uid) {
630 if ($uid instanceof WP_User) {
631 $account = wp_set_current_user($uid->ID);
632 }
633 else {
634 $account = wp_set_current_user($uid);
635 }
636 if ($account && $account->data->ID) {
637 global $user;
638 $user = $account;
639 return TRUE;
640 }
641 }
642 return TRUE;
643 }
644
645 /**
646 * @param $dir
647 *
648 * @return bool
649 */
650 public function validInstallDir($dir) {
651 $includePath = "$dir/wp-includes";
652 if (@file_exists("$includePath/version.php")) {
653 return TRUE;
654 }
655 return FALSE;
656 }
657
658 /**
659 * Determine the location of the CMS root.
660 *
661 * @return string|NULL
662 * local file system path to CMS root, or NULL if it cannot be determined
663 */
664 public function cmsRootPath() {
665
666 // Return early if the path is already set.
667 global $civicrm_paths;
668 if (!empty($civicrm_paths['cms.root']['path'])) {
669 return $civicrm_paths['cms.root']['path'];
670 }
671
672 // Return early if constant has been defined.
673 if (defined('CIVICRM_CMSDIR')) {
674 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
675 return CIVICRM_CMSDIR;
676 }
677 }
678
679 // Return early if path to wp-load.php can be retrieved from settings.
680 $setting = Civi::settings()->get('wpLoadPhp');
681 if (!empty($setting)) {
682 $path = str_replace('wp-load.php', '', $setting);
683 $cmsRoot = rtrim($path, '/\\');
684 if ($this->validInstallDir($cmsRoot)) {
685 return $cmsRoot;
686 }
687 }
688
689 /*
690 * Keep previous logic as fallback of last resort.
691 *
692 * At some point, it would be good to remove this because there are serious
693 * problems in correctly locating WordPress in this manner. In summary, it
694 * is impossible to do so reliably.
695 *
696 * @see https://github.com/civicrm/civicrm-wordpress/pull/63#issuecomment-61792328
697 * @see https://github.com/civicrm/civicrm-core/pull/11086#issuecomment-335454992
698 */
699 $cmsRoot = $valid = NULL;
700
701 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
702
703 // Might be Windows installation.
704 $firstVar = array_shift($pathVars);
705 if ($firstVar) {
706 $cmsRoot = $firstVar;
707 }
708
709 // Start with CMS dir search.
710 foreach ($pathVars as $var) {
711 $cmsRoot .= "/$var";
712 if ($this->validInstallDir($cmsRoot)) {
713 // Stop as we found bootstrap.
714 $valid = TRUE;
715 break;
716 }
717 }
718
719 return ($valid) ? $cmsRoot : NULL;
720 }
721
722 /**
723 * @inheritDoc
724 */
725 public function createUser(&$params, $mail) {
726 $user_data = [
727 'ID' => '',
728 'user_pass' => $params['cms_pass'],
729 'user_login' => $params['cms_name'],
730 'user_email' => $params[$mail],
731 'nickname' => $params['cms_name'],
732 'role' => get_option('default_role'),
733 ];
734 if (isset($params['contactID'])) {
735 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
736 if ($contactType == 'Individual') {
737 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
738 $params['contactID'], 'first_name'
739 );
740 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
741 $params['contactID'], 'last_name'
742 );
743 }
744 }
745
746 $uid = wp_insert_user($user_data);
747
748 $creds = [];
749 $creds['user_login'] = $params['cms_name'];
750 $creds['user_password'] = $params['cms_pass'];
751 $creds['remember'] = TRUE;
752 $user = wp_signon($creds, FALSE);
753
754 wp_new_user_notification($uid, $user_data['user_pass']);
755 return $uid;
756 }
757
758 /**
759 * @inheritDoc
760 */
761 public function updateCMSName($ufID, $ufName) {
762 // CRM-10620
763 if (function_exists('wp_update_user')) {
764 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
765 $ufName = CRM_Utils_Type::escape($ufName, 'String');
766
767 $values = ['ID' => $ufID, 'user_email' => $ufName];
768 if ($ufID) {
769 wp_update_user($values);
770 }
771 }
772 }
773
774 /**
775 * @param array $params
776 * @param $errors
777 * @param string $emailName
778 */
779 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
780 $config = CRM_Core_Config::singleton();
781
782 $dao = new CRM_Core_DAO();
783 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
784 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
785
786 if (!empty($params['name'])) {
787 if (!validate_username($params['name'])) {
788 $errors['cms_name'] = ts("Your username contains invalid characters");
789 }
790 elseif (username_exists(sanitize_user($params['name']))) {
791 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
792 }
793 }
794
795 if (!empty($params['mail'])) {
796 if (!is_email($params['mail'])) {
797 $errors[$emailName] = "Your email is invaid";
798 }
799 elseif (email_exists($params['mail'])) {
800 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
801 [1 => $params['mail'], 2 => wp_lostpassword_url()]
802 );
803 }
804 }
805 }
806
807 /**
808 * @inheritDoc
809 */
810 public function isUserLoggedIn() {
811 $isloggedIn = FALSE;
812 if (function_exists('is_user_logged_in')) {
813 $isloggedIn = is_user_logged_in();
814 }
815
816 return $isloggedIn;
817 }
818
819 /**
820 * @inheritDoc
821 */
822 public function isUserRegistrationPermitted() {
823 if (!get_option('users_can_register')) {
824 return FALSE;
825 }
826 return TRUE;
827 }
828
829 /**
830 * @inheritDoc
831 */
832 public function isPasswordUserGenerated() {
833 return TRUE;
834 }
835
836 /**
837 * @return mixed
838 */
839 public function getLoggedInUserObject() {
840 if (function_exists('is_user_logged_in') &&
841 is_user_logged_in()
842 ) {
843 global $current_user;
844 }
845 return $current_user;
846 }
847
848 /**
849 * @inheritDoc
850 */
851 public function getLoggedInUfID() {
852 $ufID = NULL;
853 $current_user = $this->getLoggedInUserObject();
854 return $current_user->ID ?? NULL;
855 }
856
857 /**
858 * @inheritDoc
859 */
860 public function getLoggedInUniqueIdentifier() {
861 $user = $this->getLoggedInUserObject();
862 return $this->getUniqueIdentifierFromUserObject($user);
863 }
864
865 /**
866 * Get User ID from UserFramework system (Joomla)
867 * @param object $user
868 * Object as described by the CMS.
869 *
870 * @return int|null
871 */
872 public function getUserIDFromUserObject($user) {
873 return !empty($user->ID) ? $user->ID : NULL;
874 }
875
876 /**
877 * @inheritDoc
878 */
879 public function getUniqueIdentifierFromUserObject($user) {
880 return empty($user->user_email) ? NULL : $user->user_email;
881 }
882
883 /**
884 * @inheritDoc
885 */
886 public function getLoginURL($destination = '') {
887 $config = CRM_Core_Config::singleton();
888 $loginURL = wp_login_url();
889 return $loginURL;
890 }
891
892 /**
893 * FIXME: Do something.
894 *
895 * @param \CRM_Core_Form $form
896 *
897 * @return NULL|string
898 */
899 public function getLoginDestination(&$form) {
900 return NULL;
901 }
902
903 /**
904 * @inheritDoc
905 */
906 public function getVersion() {
907 if (function_exists('get_bloginfo')) {
908 return get_bloginfo('version', 'display');
909 }
910 else {
911 return 'Unknown';
912 }
913 }
914
915 /**
916 * @inheritDoc
917 */
918 public function getTimeZoneString() {
919 return get_option('timezone_string');
920 }
921
922 /**
923 * @inheritDoc
924 */
925 public function getUserRecordUrl($contactID) {
926 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
927 if (CRM_Core_Session::singleton()
928 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(['cms:administer users'])
929 ) {
930 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
931 }
932 }
933
934 /**
935 * Append WP js to coreResourcesList.
936 *
937 * @param \Civi\Core\Event\GenericHookEvent $e
938 */
939 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) {
940 $e->list[] = 'js/crm.wordpress.js';
941 }
942
943 /**
944 * @inheritDoc
945 */
946 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent $e) {
947 // Set menubar breakpoint to match WP admin theme
948 if ($e->asset == 'crm-menubar.css') {
949 $e->params['breakpoint'] = 783;
950 }
951 }
952
953 /**
954 * @inheritDoc
955 */
956 public function synchronizeUsers() {
957 $config = CRM_Core_Config::singleton();
958 if (PHP_SAPI != 'cli') {
959 set_time_limit(300);
960 }
961 $id = 'ID';
962 $mail = 'user_email';
963
964 $uf = $config->userFramework;
965 $contactCount = 0;
966 $contactCreated = 0;
967 $contactMatching = 0;
968
969 // Previously used the $wpdb global - which means WordPress *must* be bootstrapped.
970 $wpUsers = get_users(array(
971 'blog_id' => get_current_blog_id(),
972 'number' => -1,
973 ));
974
975 foreach ($wpUsers as $wpUserData) {
976 $contactCount++;
977 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData,
978 $wpUserData->$id,
979 $wpUserData->$mail,
980 $uf,
981 1,
982 'Individual',
983 TRUE
984 )
985 ) {
986 $contactCreated++;
987 }
988 else {
989 $contactMatching++;
990 }
991 if (is_object($match)) {
992 $match->free();
993 }
994 }
995
996 return [
997 'contactCount' => $contactCount,
998 'contactMatching' => $contactMatching,
999 'contactCreated' => $contactCreated,
1000 ];
1001 }
1002
1003 /**
1004 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
1005 *
1006 * @param \Psr\Http\Message\ResponseInterface $response
1007 */
1008 public function sendResponse(\Psr\Http\Message\ResponseInterface $response) {
1009 // use WordPress function status_header to ensure 404 response is sent
1010 status_header($response->getStatusCode());
1011 foreach ($response->getHeaders() as $name => $values) {
1012 CRM_Utils_System::setHttpHeader($name, implode(', ', (array) $values));
1013 }
1014 echo $response->getBody();
1015 CRM_Utils_System::civiExit();
1016 }
1017
1018 }