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