Merge pull request #14195 from mlutfy/dev932
[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 // Encode all but the *path* placeholder
274 if ($path !== '*path*') {
275 $path = rawurlencode($path);
276 }
277 $queryParts[] = "q={$path}";
278 }
279 if ($wpPageParam) {
280 $queryParts[] = $wpPageParam;
281 }
282 if (!empty($query)) {
283 $queryParts[] = $query;
284 }
285
286 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
287
288 }
289 else {
290
291 // clean URLs
292 if (isset($path)) {
293 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
294 }
295 if (isset($query)) {
296 $query = ltrim($query, '=?&');
297 $queryParts[] = $query;
298 }
299
300 if (!empty($queryParts)) {
301 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
302 }
303 else {
304 $final = $base . $fragment;
305 }
306
307 }
308
309 return $final;
310 }
311
312 /**
313 * 27-09-2016
314 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
315 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
316 * For now leave hard coded wp-admin references.
317 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
318 *
319 * @param $absolute
320 * @param $frontend
321 * @param $forceBackend
322 *
323 * @return mixed|null|string
324 */
325 private function getBaseUrl($absolute, $frontend, $forceBackend) {
326 $config = CRM_Core_Config::singleton();
327 if ((is_admin() && !$frontend) || $forceBackend) {
328 return Civi::paths()->getUrl('[wp.backend]/.', $absolute ? 'absolute' : 'relative');
329 }
330 else {
331 return Civi::paths()->getUrl('[wp.frontend]/.', $absolute ? 'absolute' : 'relative');
332 }
333 }
334
335 /**
336 * @inheritDoc
337 */
338 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
339 $config = CRM_Core_Config::singleton();
340
341 if ($loadCMSBootstrap) {
342 $config->userSystem->loadBootStrap([
343 'name' => $name,
344 'pass' => $password,
345 ]);
346 }
347
348 $user = wp_authenticate($name, $password);
349 if (is_a($user, 'WP_Error')) {
350 return FALSE;
351 }
352
353 // TODO: need to change this to make sure we matched only one row
354
355 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
356 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
357 if (!$contactID) {
358 return FALSE;
359 }
360 return [$contactID, $user->data->ID, mt_rand()];
361 }
362
363 /**
364 * FIXME: Do something
365 *
366 * @param string $message
367 */
368 public function setMessage($message) {
369 }
370
371 /**
372 * @param \string $user
373 *
374 * @return bool
375 */
376 public function loadUser($user) {
377 $userdata = get_user_by('login', $user);
378 if (!$userdata->data->ID) {
379 return FALSE;
380 }
381
382 $uid = $userdata->data->ID;
383 wp_set_current_user($uid);
384 $contactID = CRM_Core_BAO_UFMatch::getContactId($uid);
385
386 // lets store contact id and user id in session
387 $session = CRM_Core_Session::singleton();
388 $session->set('ufID', $uid);
389 $session->set('userID', $contactID);
390 return TRUE;
391 }
392
393 /**
394 * FIXME: Use CMS-native approach
395 */
396 public function permissionDenied() {
397 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
398 }
399
400 /**
401 * Determine the native ID of the CMS user.
402 *
403 * @param string $username
404 * @return int|NULL
405 */
406 public function getUfId($username) {
407 $userdata = get_user_by('login', $username);
408 if (!$userdata->data->ID) {
409 return NULL;
410 }
411 return $userdata->data->ID;
412 }
413
414 /**
415 * @inheritDoc
416 */
417 public function logout() {
418 // destroy session
419 if (session_id()) {
420 session_destroy();
421 }
422 wp_logout();
423 wp_redirect(wp_login_url());
424 }
425
426 /**
427 * @inheritDoc
428 */
429 public function getUFLocale() {
430 // Polylang plugin
431 if (function_exists('pll_current_language')) {
432 $language = pll_current_language();
433 }
434 // WPML plugin
435 elseif (defined('ICL_LANGUAGE_CODE')) {
436 $language = ICL_LANGUAGE_CODE;
437 }
438
439 // TODO: set language variable for others WordPress plugin
440
441 if (!empty($language)) {
442 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language, 0, 2));
443 }
444 else {
445 return NULL;
446 }
447 }
448
449 /**
450 * @inheritDoc
451 */
452 public function setUFLocale($civicrm_language) {
453 // TODO (probably not possible with WPML?)
454 return TRUE;
455 }
456
457 /**
458 * Load wordpress bootstrap.
459 *
460 * @param array $params
461 * Optional credentials
462 * - name: string, cms username
463 * - pass: string, cms password
464 * @param bool $loadUser
465 * @param bool $throwError
466 * @param mixed $realPath
467 *
468 * @return bool
469 */
470 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
471 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
472
473 $name = CRM_Utils_Array::value('name', $params);
474 $pass = CRM_Utils_Array::value('pass', $params);
475
476 if (!defined('WP_USE_THEMES')) {
477 define('WP_USE_THEMES', FALSE);
478 }
479
480 $cmsRootPath = $this->cmsRootPath();
481 if (!$cmsRootPath) {
482 CRM_Core_Error::fatal("Could not find the install directory for WordPress");
483 }
484 $path = Civi::settings()->get('wpLoadPhp');
485 if (!empty($path)) {
486 require_once $path;
487 }
488 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) {
489 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
490 }
491 else {
492 CRM_Core_Error::fatal("Could not find the bootstrap file for WordPress");
493 }
494 $wpUserTimezone = get_option('timezone_string');
495 if ($wpUserTimezone) {
496 date_default_timezone_set($wpUserTimezone);
497 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
498 }
499 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
500 $uid = CRM_Utils_Array::value('uid', $params);
501 if (!$uid) {
502 $name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST));
503 $pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST));
504 if ($name) {
505 $uid = wp_authenticate($name, $pass);
506 if (!$uid) {
507 if ($throwError) {
508 echo '<br />Sorry, unrecognized username or password.';
509 exit();
510 }
511 return FALSE;
512 }
513 }
514 }
515 if ($uid) {
516 if ($uid instanceof WP_User) {
517 $account = wp_set_current_user($uid->ID);
518 }
519 else {
520 $account = wp_set_current_user($uid);
521 }
522 if ($account && $account->data->ID) {
523 global $user;
524 $user = $account;
525 return TRUE;
526 }
527 }
528 return TRUE;
529 }
530
531 /**
532 * @param $dir
533 *
534 * @return bool
535 */
536 public function validInstallDir($dir) {
537 $includePath = "$dir/wp-includes";
538 if (@file_exists("$includePath/version.php")) {
539 return TRUE;
540 }
541 return FALSE;
542 }
543
544 /**
545 * Determine the location of the CMS root.
546 *
547 * @return string|NULL
548 * local file system path to CMS root, or NULL if it cannot be determined
549 */
550 public function cmsRootPath() {
551 global $civicrm_paths;
552 if (!empty($civicrm_paths['cms.root']['path'])) {
553 return $civicrm_paths['cms.root']['path'];
554 }
555
556 $cmsRoot = $valid = NULL;
557 if (defined('CIVICRM_CMSDIR')) {
558 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
559 $cmsRoot = CIVICRM_CMSDIR;
560 $valid = TRUE;
561 }
562 }
563 else {
564 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
565
566 //might be windows installation.
567 $firstVar = array_shift($pathVars);
568 if ($firstVar) {
569 $cmsRoot = $firstVar;
570 }
571
572 //start w/ csm dir search.
573 foreach ($pathVars as $var) {
574 $cmsRoot .= "/$var";
575 if ($this->validInstallDir($cmsRoot)) {
576 //stop as we found bootstrap.
577 $valid = TRUE;
578 break;
579 }
580 }
581 }
582
583 return ($valid) ? $cmsRoot : NULL;
584 }
585
586 /**
587 * @inheritDoc
588 */
589 public function createUser(&$params, $mail) {
590 $user_data = [
591 'ID' => '',
592 'user_pass' => $params['cms_pass'],
593 'user_login' => $params['cms_name'],
594 'user_email' => $params[$mail],
595 'nickname' => $params['cms_name'],
596 'role' => get_option('default_role'),
597 ];
598 if (isset($params['contactID'])) {
599 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
600 if ($contactType == 'Individual') {
601 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
602 $params['contactID'], 'first_name'
603 );
604 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
605 $params['contactID'], 'last_name'
606 );
607 }
608 }
609
610 $uid = wp_insert_user($user_data);
611
612 $creds = [];
613 $creds['user_login'] = $params['cms_name'];
614 $creds['user_password'] = $params['cms_pass'];
615 $creds['remember'] = TRUE;
616 $user = wp_signon($creds, FALSE);
617
618 wp_new_user_notification($uid, $user_data['user_pass']);
619 return $uid;
620 }
621
622 /**
623 * @inheritDoc
624 */
625 public function updateCMSName($ufID, $ufName) {
626 // CRM-10620
627 if (function_exists('wp_update_user')) {
628 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
629 $ufName = CRM_Utils_Type::escape($ufName, 'String');
630
631 $values = ['ID' => $ufID, 'user_email' => $ufName];
632 if ($ufID) {
633 wp_update_user($values);
634 }
635 }
636 }
637
638 /**
639 * @param array $params
640 * @param $errors
641 * @param string $emailName
642 */
643 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
644 $config = CRM_Core_Config::singleton();
645
646 $dao = new CRM_Core_DAO();
647 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
648 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
649
650 if (!empty($params['name'])) {
651 if (!validate_username($params['name'])) {
652 $errors['cms_name'] = ts("Your username contains invalid characters");
653 }
654 elseif (username_exists(sanitize_user($params['name']))) {
655 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
656 }
657 }
658
659 if (!empty($params['mail'])) {
660 if (!is_email($params['mail'])) {
661 $errors[$emailName] = "Your email is invaid";
662 }
663 elseif (email_exists($params['mail'])) {
664 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
665 [1 => $params['mail'], 2 => wp_lostpassword_url()]
666 );
667 }
668 }
669 }
670
671 /**
672 * @inheritDoc
673 */
674 public function isUserLoggedIn() {
675 $isloggedIn = FALSE;
676 if (function_exists('is_user_logged_in')) {
677 $isloggedIn = is_user_logged_in();
678 }
679
680 return $isloggedIn;
681 }
682
683 /**
684 * @inheritDoc
685 */
686 public function isUserRegistrationPermitted() {
687 if (!get_option('users_can_register')) {
688 return FALSE;
689 }
690 return TRUE;
691 }
692
693 /**
694 * @inheritDoc
695 */
696 public function isPasswordUserGenerated() {
697 return TRUE;
698 }
699
700 /**
701 * @return mixed
702 */
703 public function getLoggedInUserObject() {
704 if (function_exists('is_user_logged_in') &&
705 is_user_logged_in()
706 ) {
707 global $current_user;
708 }
709 return $current_user;
710 }
711
712 /**
713 * @inheritDoc
714 */
715 public function getLoggedInUfID() {
716 $ufID = NULL;
717 $current_user = $this->getLoggedInUserObject();
718 return isset($current_user->ID) ? $current_user->ID : NULL;
719 }
720
721 /**
722 * @inheritDoc
723 */
724 public function getLoggedInUniqueIdentifier() {
725 $user = $this->getLoggedInUserObject();
726 return $this->getUniqueIdentifierFromUserObject($user);
727 }
728
729 /**
730 * Get User ID from UserFramework system (Joomla)
731 * @param object $user
732 * Object as described by the CMS.
733 *
734 * @return int|null
735 */
736 public function getUserIDFromUserObject($user) {
737 return !empty($user->ID) ? $user->ID : NULL;
738 }
739
740 /**
741 * @inheritDoc
742 */
743 public function getUniqueIdentifierFromUserObject($user) {
744 return empty($user->user_email) ? NULL : $user->user_email;
745 }
746
747 /**
748 * @inheritDoc
749 */
750 public function getLoginURL($destination = '') {
751 $config = CRM_Core_Config::singleton();
752 $loginURL = wp_login_url();
753 return $loginURL;
754 }
755
756 /**
757 * FIXME: Do something.
758 *
759 * @param \CRM_Core_Form $form
760 *
761 * @return NULL|string
762 */
763 public function getLoginDestination(&$form) {
764 return NULL;
765 }
766
767 /**
768 * @inheritDoc
769 */
770 public function getVersion() {
771 if (function_exists('get_bloginfo')) {
772 return get_bloginfo('version', 'display');
773 }
774 else {
775 return 'Unknown';
776 }
777 }
778
779 /**
780 * @inheritDoc
781 */
782 public function getTimeZoneString() {
783 return get_option('timezone_string');
784 }
785
786 /**
787 * @inheritDoc
788 */
789 public function getUserRecordUrl($contactID) {
790 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
791 if (CRM_Core_Session::singleton()
792 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(['cms:administer users'])
793 ) {
794 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
795 }
796 }
797
798 /**
799 * Append WP js to coreResourcesList.
800 *
801 * @param \Civi\Core\Event\GenericHookEvent $e
802 */
803 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) {
804 $e->list[] = 'js/crm.wordpress.js';
805 }
806
807 /**
808 * @inheritDoc
809 */
810 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent $e) {
811 // Set menubar breakpoint to match WP admin theme
812 if ($e->asset == 'crm-menubar.css') {
813 $e->params['breakpoint'] = 783;
814 }
815 }
816
817 /**
818 * @inheritDoc
819 */
820 public function synchronizeUsers() {
821 $config = CRM_Core_Config::singleton();
822 if (PHP_SAPI != 'cli') {
823 set_time_limit(300);
824 }
825 $id = 'ID';
826 $mail = 'user_email';
827
828 $uf = $config->userFramework;
829 $contactCount = 0;
830 $contactCreated = 0;
831 $contactMatching = 0;
832
833 global $wpdb;
834 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
835
836 foreach ($wpUserIds as $wpUserId) {
837 $wpUserData = get_userdata($wpUserId);
838 $contactCount++;
839 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData,
840 $wpUserData->$id,
841 $wpUserData->$mail,
842 $uf,
843 1,
844 'Individual',
845 TRUE
846 )
847 ) {
848 $contactCreated++;
849 }
850 else {
851 $contactMatching++;
852 }
853 if (is_object($match)) {
854 $match->free();
855 }
856 }
857
858 return [
859 'contactCount' => $contactCount,
860 'contactMatching' => $contactMatching,
861 'contactCreated' => $contactCreated,
862 ];
863 }
864
865 }