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