3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * WordPress specific stuff goes here
21 class CRM_Utils_System_WordPress
extends CRM_Utils_System_Base
{
24 * Get a normalized version of the wpBasePage.
26 public static function getBasePage() {
27 return rtrim(Civi
::settings()->get('wpBasePage'), '/');
32 public function __construct() {
34 * 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
35 * functions and leave the codebase oblivious to the type of CMS
39 $this->is_drupal
= FALSE;
40 $this->is_wordpress
= TRUE;
43 public function initialize() {
45 $this->registerPathVars();
49 * Specify the default computation for various paths/URLs.
51 protected function registerPathVars():void
{
52 $isNormalBoot = function_exists('get_option');
54 // Normal mode - CMS boots first, then calls Civi. "Normal" web pages and newer extern routes.
55 // To simplify the code-paths, some items are re-registered with WP-specific functions.
56 $cmsRoot = function() {
58 'path' => untrailingslashit(ABSPATH
),
62 Civi
::paths()->register('cms', $cmsRoot);
63 Civi
::paths()->register('cms.root', $cmsRoot);
64 Civi
::paths()->register('civicrm.root', function () {
66 'path' => CIVICRM_PLUGIN_DIR
. 'civicrm' . DIRECTORY_SEPARATOR
,
67 'url' => CIVICRM_PLUGIN_URL
. 'civicrm/',
70 Civi
::paths()->register('wp.frontend.base', function () {
72 'url' => home_url('/'),
75 Civi
::paths()->register('wp.frontend', function () {
76 $config = CRM_Core_Config
::singleton();
77 $basepage = get_page_by_path($config->wpBasePage
);
79 'url' => get_permalink($basepage->ID
),
82 Civi
::paths()->register('wp.backend.base', function () {
87 Civi
::paths()->register('wp.backend', function() {
89 'url' => admin_url('admin.php'),
92 Civi
::paths()->register('civicrm.files', function () {
93 $upload_dir = wp_get_upload_dir();
95 $old = CRM_Core_Config
::singleton()->userSystem
->getDefaultFileStorage();
97 'path' => $upload_dir['basedir'] . DIRECTORY_SEPARATOR
. 'civicrm' . DIRECTORY_SEPARATOR
,
98 'url' => $upload_dir['baseurl'] . '/civicrm/',
101 if ($old['path'] === $new['path']) {
105 $oldExists = file_exists($old['path']);
106 $newExists = file_exists($new['path']);
108 if ($oldExists && !$newExists) {
111 elseif (!$oldExists && $newExists) {
114 elseif (!$oldExists && !$newExists) {
115 // neither exists. but that's ok. we're in one of these two cases:
116 // - we're just starting installation... which will get sorted in a moment
117 // when someone calls mkdir().
118 // - we're running a bespoke setup... which will get sorted in a moment
119 // by applying $civicrm_paths.
122 elseif ($oldExists && $newExists) {
123 // situation ambiguous. encourage admin to set value explicitly.
124 if (!isset($GLOBALS['civicrm_paths']['civicrm.files'])) {
125 \Civi
::log()->warning("The system has data from both old+new conventions. Please use civicrm.settings.php to set civicrm.files explicitly.");
132 // Legacy support - only relevant for older extern routes.
134 ->register('wp.frontend.base', function () {
135 return ['url' => rtrim(CIVICRM_UF_BASEURL
, '/') . '/'];
137 ->register('wp.frontend', function () {
138 $config = \CRM_Core_Config
::singleton();
139 $suffix = defined('CIVICRM_UF_WP_BASEPAGE') ? CIVICRM_UF_WP_BASEPAGE
: $config->wpBasePage
;
141 'url' => Civi
::paths()->getVariable('wp.frontend.base', 'url') . $suffix,
144 ->register('wp.backend.base', function () {
145 return ['url' => rtrim(CIVICRM_UF_BASEURL
, '/') . '/wp-admin/'];
147 ->register('wp.backend', function () {
149 'url' => Civi
::paths()->getVariable('wp.backend.base', 'url') . 'admin.php',
158 public function setTitle($title, $pageTitle = NULL) {
163 // FIXME: Why is this global?
164 global $civicrm_wp_title;
165 $civicrm_wp_title = $title;
167 // yes, set page title, depending on context
168 $context = civi_wp()->civicrm_context_get();
172 $template = CRM_Core_Smarty
::singleton();
173 $template->assign('pageTitle', $pageTitle);
178 * Moved from CRM_Utils_System_Base
180 public function getDefaultFileStorage() {
181 // NOTE: On WordPress, this will be circumvented in the future. However,
182 // should retain it to allow transitional/upgrade code determine the old value.
184 $config = CRM_Core_Config
::singleton();
185 $cmsUrl = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
186 $cmsPath = $this->cmsRootPath();
187 $filesPath = CRM_Utils_File
::baseFilePath();
188 $filesRelPath = CRM_Utils_File
::relativize($filesPath, $cmsPath);
189 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
191 'url' => CRM_Utils_File
::addTrailingSlash($filesURL, '/'),
192 'path' => CRM_Utils_File
::addTrailingSlash($filesPath),
197 * Determine the location of the CiviCRM source tree.
200 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
201 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
203 public function getCiviSourceStorage() {
204 global $civicrm_root;
206 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
207 // More generally, we shouldn't be using $config here.
208 if (!defined('CIVICRM_UF_BASEURL')) {
209 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
212 $cmsPath = $this->cmsRootPath();
214 // $config = CRM_Core_Config::singleton();
215 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
216 $cmsUrl = CIVICRM_UF_BASEURL
;
217 if (CRM_Utils_System
::isSSL()) {
218 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
220 $civiRelPath = CRM_Utils_File
::relativize(realpath($civicrm_root), realpath($cmsPath));
221 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
223 'url' => CRM_Utils_File
::addTrailingSlash($civiUrl, '/'),
224 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
231 public function appendBreadCrumb($breadCrumbs) {
232 $breadCrumb = wp_get_breadcrumb();
234 if (is_array($breadCrumbs)) {
235 foreach ($breadCrumbs as $crumbs) {
236 if (stripos($crumbs['url'], 'id%%')) {
237 $args = ['cid', 'mid'];
238 foreach ($args as $a) {
239 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
243 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
247 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
251 $template = CRM_Core_Smarty
::singleton();
252 $template->assign_by_ref('breadcrumb', $breadCrumb);
253 wp_set_breadcrumb($breadCrumb);
259 public function resetBreadCrumb() {
261 wp_set_breadcrumb($bc);
267 public function addHTMLHead($head) {
268 static $registered = FALSE;
271 add_action('wp_head', [__CLASS__
, '_showHTMLHead']);
273 add_action('admin_head', [__CLASS__
, '_showHTMLHead']);
275 CRM_Core_Region
::instance('wp_head')->add([
281 * WP action callback.
283 public static function _showHTMLHead() {
284 $region = CRM_Core_Region
::instance('wp_head', FALSE);
286 echo $region->render('');
293 public function mapConfigToSSL() {
295 $base_url = str_replace('http://', 'https://', $base_url);
307 $forceBackend = FALSE,
310 $config = CRM_Core_Config
::singleton();
314 $fragment = isset($fragment) ?
('#' . $fragment) : '';
316 $path = CRM_Utils_String
::stripPathChars($path);
319 //this means wp function we are trying to use is not available,
321 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
322 if (!function_exists('get_option')) {
323 $this->loadBootStrap();
326 if ($config->userFrameworkFrontend
) {
328 if (get_option('permalink_structure') != '') {
329 $script = $post ?
get_permalink($post->ID
) : "";
331 if ($post && $config->wpBasePage
== $post->post_name
) {
334 // when shortcode is included in page
335 // also make sure we have valid query object
336 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
338 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
339 if (get_query_var('page_id')) {
340 $wpPageParam = "page_id=" . get_query_var('page_id');
342 elseif (get_query_var('p')) {
343 // when shortcode is inserted in post
344 $wpPageParam = "p=" . get_query_var('p');
349 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
351 if (!isset($path) && !isset($query)) {
352 // FIXME: This short-circuited codepath is the same as the general one below, except
353 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
354 // why it's different (and I can only find two obvious use-cases for this codepath,
355 // of which at least one looks gratuitous). A more ambitious person would simply remove
357 return $base . $fragment;
360 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
367 // not using clean URLs
369 // requesting an admin URL
370 ||
((is_admin() && !$frontend) ||
$forceBackend)
372 ||
(!$basepage && $script != '')
375 // pre-existing logic
377 // Admin URLs still need "page=CiviCRM", front-end URLs do not.
378 if ((is_admin() && !$frontend) ||
$forceBackend) {
379 $queryParts[] = 'page=CiviCRM';
382 $queryParts[] = 'civiwp=CiviCRM';
384 $queryParts[] = 'q=' . rawurlencode($path);
387 $queryParts[] = $wpPageParam;
389 if (!empty($query)) {
390 $queryParts[] = $query;
393 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
400 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
403 $query = ltrim($query, '=?&');
404 $queryParts[] = $query;
407 if (!empty($queryParts)) {
408 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
411 $final = $base . $fragment;
421 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
422 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
423 * For now leave hard coded wp-admin references.
424 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
428 * @param $forceBackend
430 * @return mixed|null|string
432 private function getBaseUrl($absolute, $frontend, $forceBackend) {
433 $config = CRM_Core_Config
::singleton();
434 if ((is_admin() && !$frontend) ||
$forceBackend) {
435 return Civi
::paths()->getUrl('[wp.backend]/.', $absolute ?
'absolute' : 'relative');
438 return Civi
::paths()->getUrl('[wp.frontend]/.', $absolute ?
'absolute' : 'relative');
445 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
446 $config = CRM_Core_Config
::singleton();
448 if ($loadCMSBootstrap) {
449 $config->userSystem
->loadBootStrap([
455 $user = wp_authenticate($name, $password);
456 if (is_a($user, 'WP_Error')) {
460 // TODO: need to change this to make sure we matched only one row
462 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
463 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
467 return [$contactID, $user->data
->ID
, mt_rand()];
471 * FIXME: Do something
473 * @param string $message
475 public function setMessage($message) {
479 * @param \string $user
483 public function loadUser($user) {
484 $userdata = get_user_by('login', $user);
485 if (!$userdata->data
->ID
) {
489 $uid = $userdata->data
->ID
;
490 wp_set_current_user($uid);
491 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
493 // lets store contact id and user id in session
494 $session = CRM_Core_Session
::singleton();
495 $session->set('ufID', $uid);
496 $session->set('userID', $contactID);
501 * FIXME: Use CMS-native approach
502 * @throws \CRM_Core_Exception
504 public function permissionDenied() {
505 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
509 * Determine the native ID of the CMS user.
511 * @param string $username
515 public function getUfId($username) {
516 $userdata = get_user_by('login', $username);
517 if (!$userdata->data
->ID
) {
520 return $userdata->data
->ID
;
526 public function logout() {
532 wp_redirect(wp_login_url());
538 public function getUFLocale() {
539 // Bail early if method is called when WordPress isn't bootstrapped.
540 // Additionally, the function checked here is located in pluggable.php
541 // and is required by wp_get_referer() - so this also bails early if it is
542 // called too early in the request lifecycle.
543 // @see https://core.trac.wordpress.org/ticket/25294
544 if (!function_exists('wp_validate_redirect')) {
548 // Default to WordPress User locale.
549 $locale = get_user_locale();
551 // Is this a "back-end" AJAX call?
553 if (wp_doing_ajax() && FALSE !== strpos(wp_get_referer(), admin_url())) {
557 // Ignore when in WordPress admin or it's a "back-end" AJAX call.
558 if (!(is_admin() ||
$is_backend)) {
560 // Reaching here means it is very likely to be a front-end context.
562 // Default to WordPress locale.
563 $locale = get_locale();
565 // Maybe override with the locale that Polylang reports.
566 if (function_exists('pll_current_language')) {
567 $pll_locale = pll_current_language('locale');
568 if (!empty($pll_locale)) {
569 $locale = $pll_locale;
573 // Maybe override with the locale that WPML reports.
574 elseif (defined('ICL_LANGUAGE_CODE')) {
575 $languages = apply_filters('wpml_active_languages', NULL);
576 foreach ($languages as $language) {
577 if ($language['active']) {
578 $locale = $language['default_locale'];
584 // TODO: Set locale for other WordPress plugins.
585 // @see https://wordpress.org/plugins/tags/multilingual/
586 // A hook would be nice here.
590 if (!empty($locale)) {
591 // If for some reason only we get a language code, convert it to a locale.
592 if (2 === strlen($locale)) {
593 $locale = CRM_Core_I18n_PseudoConstant
::longForShort($locale);
605 public function setUFLocale($civicrm_language) {
606 // TODO (probably not possible with WPML?)
611 * Load wordpress bootstrap.
613 * @param array $params
614 * Optional credentials
615 * - name: string, cms username
616 * - pass: string, cms password
617 * @param bool $loadUser
618 * @param bool $throwError
619 * @param mixed $realPath
622 * @throws \CRM_Core_Exception
624 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
625 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
627 $name = $params['name'] ??
NULL;
628 $pass = $params['pass'] ??
NULL;
630 if (!defined('WP_USE_THEMES')) {
631 define('WP_USE_THEMES', FALSE);
634 $cmsRootPath = $this->cmsRootPath();
636 throw new CRM_Core_Exception("Could not find the install directory for WordPress");
638 $path = Civi
::settings()->get('wpLoadPhp');
642 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
643 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
646 throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress");
648 $wpUserTimezone = get_option('timezone_string');
649 if ($wpUserTimezone) {
650 date_default_timezone_set($wpUserTimezone);
651 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
653 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
654 $uid = $params['uid'] ??
NULL;
656 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
657 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
659 $uid = wp_authenticate($name, $pass);
662 echo '<br />Sorry, unrecognized username or password.';
670 if ($uid instanceof WP_User
) {
671 $account = wp_set_current_user($uid->ID
);
674 $account = wp_set_current_user($uid);
676 if ($account && $account->data
->ID
) {
690 public function validInstallDir($dir) {
691 $includePath = "$dir/wp-includes";
692 if (@file_exists
("$includePath/version.php")) {
699 * Determine the location of the CMS root.
701 * @return string|NULL
702 * local file system path to CMS root, or NULL if it cannot be determined
704 public function cmsRootPath() {
706 // Return early if the path is already set.
707 global $civicrm_paths;
708 if (!empty($civicrm_paths['cms.root']['path'])) {
709 return $civicrm_paths['cms.root']['path'];
712 // Return early if constant has been defined.
713 if (defined('CIVICRM_CMSDIR')) {
714 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
715 return CIVICRM_CMSDIR
;
719 // Return early if path to wp-load.php can be retrieved from settings.
720 $setting = Civi
::settings()->get('wpLoadPhp');
721 if (!empty($setting)) {
722 $path = str_replace('wp-load.php', '', $setting);
723 $cmsRoot = rtrim($path, '/\\');
724 if ($this->validInstallDir($cmsRoot)) {
730 * Keep previous logic as fallback of last resort.
732 * At some point, it would be good to remove this because there are serious
733 * problems in correctly locating WordPress in this manner. In summary, it
734 * is impossible to do so reliably.
736 * @see https://github.com/civicrm/civicrm-wordpress/pull/63#issuecomment-61792328
737 * @see https://github.com/civicrm/civicrm-core/pull/11086#issuecomment-335454992
739 $cmsRoot = $valid = NULL;
741 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
743 // Might be Windows installation.
744 $firstVar = array_shift($pathVars);
746 $cmsRoot = $firstVar;
749 // Start with CMS dir search.
750 foreach ($pathVars as $var) {
752 if ($this->validInstallDir($cmsRoot)) {
753 // Stop as we found bootstrap.
759 return ($valid) ?
$cmsRoot : NULL;
765 public function createUser(&$params, $mail) {
768 'user_pass' => $params['cms_pass'],
769 'user_login' => $params['cms_name'],
770 'user_email' => $params[$mail],
771 'nickname' => $params['cms_name'],
772 'role' => get_option('default_role'),
774 if (isset($params['contactID'])) {
775 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
776 if ($contactType == 'Individual') {
777 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
778 $params['contactID'], 'first_name'
780 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
781 $params['contactID'], 'last_name'
786 $uid = wp_insert_user($user_data);
789 $creds['user_login'] = $params['cms_name'];
790 $creds['user_password'] = $params['cms_pass'];
791 $creds['remember'] = TRUE;
792 $user = wp_signon($creds, FALSE);
794 wp_new_user_notification($uid, $user_data['user_pass']);
801 public function updateCMSName($ufID, $ufName) {
803 if (function_exists('wp_update_user')) {
804 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
805 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
807 $values = ['ID' => $ufID, 'user_email' => $ufName];
809 wp_update_user($values);
815 * @param array $params
817 * @param string $emailName
819 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
820 $config = CRM_Core_Config
::singleton();
822 $dao = new CRM_Core_DAO();
823 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
824 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
826 if (!empty($params['name'])) {
827 if (!validate_username($params['name'])) {
828 $errors['cms_name'] = ts("Your username contains invalid characters");
830 elseif (username_exists(sanitize_user($params['name']))) {
831 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
835 if (!empty($params['mail'])) {
836 if (!is_email($params['mail'])) {
837 $errors[$emailName] = "Your email is invaid";
839 elseif (email_exists($params['mail'])) {
840 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
841 [1 => $params['mail'], 2 => wp_lostpassword_url()]
850 public function isUserLoggedIn() {
852 if (function_exists('is_user_logged_in')) {
853 $isloggedIn = is_user_logged_in();
862 public function isUserRegistrationPermitted() {
863 if (!get_option('users_can_register')) {
872 public function isPasswordUserGenerated() {
879 public function getLoggedInUserObject() {
880 if (function_exists('is_user_logged_in') &&
883 global $current_user;
885 return $current_user;
891 public function getLoggedInUfID() {
893 $current_user = $this->getLoggedInUserObject();
894 return $current_user->ID ??
NULL;
900 public function getLoggedInUniqueIdentifier() {
901 $user = $this->getLoggedInUserObject();
902 return $this->getUniqueIdentifierFromUserObject($user);
906 * Get User ID from UserFramework system (Joomla)
907 * @param object $user
908 * Object as described by the CMS.
912 public function getUserIDFromUserObject($user) {
913 return !empty($user->ID
) ?
$user->ID
: NULL;
919 public function getUniqueIdentifierFromUserObject($user) {
920 return empty($user->user_email
) ?
NULL : $user->user_email
;
926 public function getLoginURL($destination = '') {
927 $config = CRM_Core_Config
::singleton();
928 $loginURL = wp_login_url();
933 * FIXME: Do something.
935 * @param \CRM_Core_Form $form
937 * @return NULL|string
939 public function getLoginDestination(&$form) {
946 public function getVersion() {
947 if (function_exists('get_bloginfo')) {
948 return get_bloginfo('version', 'display');
958 public function getTimeZoneString() {
959 return get_option('timezone_string');
965 public function getUserRecordUrl($contactID) {
966 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
967 if (CRM_Core_Session
::singleton()
968 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(['cms:administer users'])
970 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
975 * Append WP js to coreResourcesList.
977 * @param \Civi\Core\Event\GenericHookEvent $e
979 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
980 $e->list[] = 'js/crm.wordpress.js';
986 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent
$e) {
987 // Set menubar breakpoint to match WP admin theme
988 if ($e->asset
== 'crm-menubar.css') {
989 $e->params
['breakpoint'] = 783;
996 public function synchronizeUsers() {
997 $config = CRM_Core_Config
::singleton();
998 if (PHP_SAPI
!= 'cli') {
1002 $mail = 'user_email';
1004 $uf = $config->userFramework
;
1006 $contactCreated = 0;
1007 $contactMatching = 0;
1009 // Previously used the $wpdb global - which means WordPress *must* be bootstrapped.
1010 $wpUsers = get_users(array(
1011 'blog_id' => get_current_blog_id(),
1015 foreach ($wpUsers as $wpUserData) {
1017 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
1031 if (is_object($match)) {
1037 'contactCount' => $contactCount,
1038 'contactMatching' => $contactMatching,
1039 'contactCreated' => $contactCreated,
1044 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
1046 * @param \Psr\Http\Message\ResponseInterface $response
1048 public function sendResponse(\Psr\Http\Message\ResponseInterface
$response) {
1049 // use WordPress function status_header to ensure 404 response is sent
1050 status_header($response->getStatusCode());
1051 foreach ($response->getHeaders() as $name => $values) {
1052 CRM_Utils_System
::setHttpHeader($name, implode(', ', (array) $values));
1054 echo $response->getBody();
1055 CRM_Utils_System
::civiExit();
1059 * Start a new session if there's no existing session ID.
1061 * Checks are needed to prevent sessions being started when not necessary.
1063 public function sessionStart() {
1064 $session_id = session_id();
1066 // Check WordPress pseudo-cron.
1068 if (function_exists('wp_doing_cron') && wp_doing_cron()) {
1074 if (defined('WP_CLI') && WP_CLI
) {
1078 // Check PHP on the command line - e.g. `cv`.
1080 if (PHP_SAPI
!== 'cli') {
1084 // Maybe start session.
1085 if (empty($session_id) && !$wp_cron && !$wp_cli && !$php_cli) {