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