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