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