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
{
25 public function __construct() {
27 * 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
28 * functions and leave the codebase oblivious to the type of CMS
32 $this->is_drupal
= FALSE;
33 $this->is_wordpress
= TRUE;
36 public function initialize() {
38 $this->registerPathVars();
42 * Specify the default computation for various paths/URLs.
44 protected function registerPathVars():void
{
45 $isNormalBoot = function_exists('get_option');
47 // Normal mode - CMS boots first, then calls Civi. "Normal" web pages and newer extern routes.
48 // To simplify the code-paths, some items are re-registered with WP-specific functions.
49 $cmsRoot = function() {
51 'path' => untrailingslashit(ABSPATH
),
55 Civi
::paths()->register('cms', $cmsRoot);
56 Civi
::paths()->register('cms.root', $cmsRoot);
57 Civi
::paths()->register('civicrm.root', function () {
59 'path' => CIVICRM_PLUGIN_DIR
. 'civicrm' . DIRECTORY_SEPARATOR
,
60 'url' => CIVICRM_PLUGIN_URL
. 'civicrm/',
63 Civi
::paths()->register('wp.frontend.base', function () {
65 'url' => home_url('/'),
68 Civi
::paths()->register('wp.frontend', function () {
69 $config = CRM_Core_Config
::singleton();
70 $basepage = get_page_by_path($config->wpBasePage
);
72 'url' => get_permalink($basepage->ID
),
75 Civi
::paths()->register('wp.backend.base', function () {
80 Civi
::paths()->register('wp.backend', function() {
82 'url' => admin_url('admin.php'),
87 // Legacy support - only relevant for older extern routes.
89 ->register('wp.frontend.base', function () {
90 return ['url' => rtrim(CIVICRM_UF_BASEURL
, '/') . '/'];
92 ->register('wp.frontend', function () {
93 $config = \CRM_Core_Config
::singleton();
94 $suffix = defined('CIVICRM_UF_WP_BASEPAGE') ? CIVICRM_UF_WP_BASEPAGE
: $config->wpBasePage
;
96 'url' => Civi
::paths()->getVariable('wp.frontend.base', 'url') . $suffix,
99 ->register('wp.backend.base', function () {
100 return ['url' => rtrim(CIVICRM_UF_BASEURL
, '/') . '/wp-admin/'];
102 ->register('wp.backend', function () {
104 'url' => Civi
::paths()->getVariable('wp.backend.base', 'url') . 'admin.php',
113 public function setTitle($title, $pageTitle = NULL) {
118 // FIXME: Why is this global?
119 global $civicrm_wp_title;
120 $civicrm_wp_title = $title;
122 // yes, set page title, depending on context
123 $context = civi_wp()->civicrm_context_get();
127 $template = CRM_Core_Smarty
::singleton();
128 $template->assign('pageTitle', $pageTitle);
133 * Moved from CRM_Utils_System_Base
135 public function getDefaultFileStorage() {
136 // NOTE: On WordPress, this will be circumvented in the future. However,
137 // should retain it to allow transitional/upgrade code determine the old value.
139 $config = CRM_Core_Config
::singleton();
140 $cmsUrl = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
141 $cmsPath = $this->cmsRootPath();
142 $filesPath = CRM_Utils_File
::baseFilePath();
143 $filesRelPath = CRM_Utils_File
::relativize($filesPath, $cmsPath);
144 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
146 'url' => CRM_Utils_File
::addTrailingSlash($filesURL, '/'),
147 'path' => CRM_Utils_File
::addTrailingSlash($filesPath),
152 * Determine the location of the CiviCRM source tree.
155 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
156 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
158 public function getCiviSourceStorage() {
159 global $civicrm_root;
161 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
162 // More generally, we shouldn't be using $config here.
163 if (!defined('CIVICRM_UF_BASEURL')) {
164 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
167 $cmsPath = $this->cmsRootPath();
169 // $config = CRM_Core_Config::singleton();
170 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
171 $cmsUrl = CIVICRM_UF_BASEURL
;
172 if (CRM_Utils_System
::isSSL()) {
173 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
175 $civiRelPath = CRM_Utils_File
::relativize(realpath($civicrm_root), realpath($cmsPath));
176 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
178 'url' => CRM_Utils_File
::addTrailingSlash($civiUrl, '/'),
179 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
186 public function appendBreadCrumb($breadCrumbs) {
187 $breadCrumb = wp_get_breadcrumb();
189 if (is_array($breadCrumbs)) {
190 foreach ($breadCrumbs as $crumbs) {
191 if (stripos($crumbs['url'], 'id%%')) {
192 $args = ['cid', 'mid'];
193 foreach ($args as $a) {
194 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
198 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
202 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
206 $template = CRM_Core_Smarty
::singleton();
207 $template->assign_by_ref('breadcrumb', $breadCrumb);
208 wp_set_breadcrumb($breadCrumb);
214 public function resetBreadCrumb() {
216 wp_set_breadcrumb($bc);
222 public function addHTMLHead($head) {
223 static $registered = FALSE;
226 add_action('wp_head', [__CLASS__
, '_showHTMLHead']);
228 add_action('admin_head', [__CLASS__
, '_showHTMLHead']);
230 CRM_Core_Region
::instance('wp_head')->add([
236 * WP action callback.
238 public static function _showHTMLHead() {
239 $region = CRM_Core_Region
::instance('wp_head', FALSE);
241 echo $region->render('');
248 public function mapConfigToSSL() {
250 $base_url = str_replace('http://', 'https://', $base_url);
262 $forceBackend = FALSE,
265 $config = CRM_Core_Config
::singleton();
269 $fragment = isset($fragment) ?
('#' . $fragment) : '';
271 $path = CRM_Utils_String
::stripPathChars($path);
274 //this means wp function we are trying to use is not available,
276 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
277 if (!function_exists('get_option')) {
278 $this->loadBootStrap();
281 if ($config->userFrameworkFrontend
) {
283 if (get_option('permalink_structure') != '') {
284 $script = get_permalink($post->ID
);
286 if ($config->wpBasePage
== $post->post_name
) {
289 // when shortcode is included in page
290 // also make sure we have valid query object
291 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
293 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
294 if (get_query_var('page_id')) {
295 $wpPageParam = "page_id=" . get_query_var('page_id');
297 elseif (get_query_var('p')) {
298 // when shortcode is inserted in post
299 $wpPageParam = "p=" . get_query_var('p');
304 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
306 if (!isset($path) && !isset($query)) {
307 // FIXME: This short-circuited codepath is the same as the general one below, except
308 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
309 // why it's different (and I can only find two obvious use-cases for this codepath,
310 // of which at least one looks gratuitous). A more ambitious person would simply remove
312 return $base . $fragment;
315 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
322 // not using clean URLs
324 // requesting an admin URL
325 ||
((is_admin() && !$frontend) ||
$forceBackend)
327 ||
(!$basepage && $script != '')
330 // pre-existing logic
332 // Admin URLs still need "page=CiviCRM", front-end URLs do not.
333 if ((is_admin() && !$frontend) ||
$forceBackend) {
334 $queryParts[] = 'page=CiviCRM';
337 $queryParts[] = 'civiwp=CiviCRM';
339 $queryParts[] = 'q=' . rawurlencode($path);
342 $queryParts[] = $wpPageParam;
344 if (!empty($query)) {
345 $queryParts[] = $query;
348 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
355 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
358 $query = ltrim($query, '=?&');
359 $queryParts[] = $query;
362 if (!empty($queryParts)) {
363 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
366 $final = $base . $fragment;
376 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
377 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
378 * For now leave hard coded wp-admin references.
379 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
383 * @param $forceBackend
385 * @return mixed|null|string
387 private function getBaseUrl($absolute, $frontend, $forceBackend) {
388 $config = CRM_Core_Config
::singleton();
389 if ((is_admin() && !$frontend) ||
$forceBackend) {
390 return Civi
::paths()->getUrl('[wp.backend]/.', $absolute ?
'absolute' : 'relative');
393 return Civi
::paths()->getUrl('[wp.frontend]/.', $absolute ?
'absolute' : 'relative');
400 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
401 $config = CRM_Core_Config
::singleton();
403 if ($loadCMSBootstrap) {
404 $config->userSystem
->loadBootStrap([
410 $user = wp_authenticate($name, $password);
411 if (is_a($user, 'WP_Error')) {
415 // TODO: need to change this to make sure we matched only one row
417 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
418 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
422 return [$contactID, $user->data
->ID
, mt_rand()];
426 * FIXME: Do something
428 * @param string $message
430 public function setMessage($message) {
434 * @param \string $user
438 public function loadUser($user) {
439 $userdata = get_user_by('login', $user);
440 if (!$userdata->data
->ID
) {
444 $uid = $userdata->data
->ID
;
445 wp_set_current_user($uid);
446 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
448 // lets store contact id and user id in session
449 $session = CRM_Core_Session
::singleton();
450 $session->set('ufID', $uid);
451 $session->set('userID', $contactID);
456 * FIXME: Use CMS-native approach
457 * @throws \CRM_Core_Exception
459 public function permissionDenied() {
460 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
464 * Determine the native ID of the CMS user.
466 * @param string $username
470 public function getUfId($username) {
471 $userdata = get_user_by('login', $username);
472 if (!$userdata->data
->ID
) {
475 return $userdata->data
->ID
;
481 public function logout() {
487 wp_redirect(wp_login_url());
493 public function getUFLocale() {
494 // Bail early if method is called when WordPress isn't bootstrapped.
495 // Additionally, the function checked here is located in pluggable.php
496 // and is required by wp_get_referer() - so this also bails early if it is
497 // called too early in the request lifecycle.
498 // @see https://core.trac.wordpress.org/ticket/25294
499 if (!function_exists('wp_validate_redirect')) {
503 // Default to WordPress User locale.
504 $locale = get_user_locale();
506 // Is this a "back-end" AJAX call?
508 if (wp_doing_ajax() && FALSE !== strpos(wp_get_referer(), admin_url())) {
512 // Ignore when in WordPress admin or it's a "back-end" AJAX call.
513 if (!(is_admin() ||
$is_backend)) {
515 // Reaching here means it is very likely to be a front-end context.
517 // Default to WordPress locale.
518 $locale = get_locale();
520 // Maybe override with the locale that Polylang reports.
521 if (function_exists('pll_current_language')) {
522 $pll_locale = pll_current_language('locale');
523 if (!empty($pll_locale)) {
524 $locale = $pll_locale;
528 // Maybe override with the locale that WPML reports.
529 elseif (defined('ICL_LANGUAGE_CODE')) {
530 $languages = apply_filters('wpml_active_languages', NULL);
531 foreach ($languages as $language) {
532 if ($language['active']) {
533 $locale = $language['default_locale'];
539 // TODO: Set locale for other WordPress plugins.
540 // @see https://wordpress.org/plugins/tags/multilingual/
541 // A hook would be nice here.
545 if (!empty($locale)) {
546 // If for some reason only we get a language code, convert it to a locale.
547 if (2 === strlen($locale)) {
548 $locale = CRM_Core_I18n_PseudoConstant
::longForShort($locale);
560 public function setUFLocale($civicrm_language) {
561 // TODO (probably not possible with WPML?)
566 * Load wordpress bootstrap.
568 * @param array $params
569 * Optional credentials
570 * - name: string, cms username
571 * - pass: string, cms password
572 * @param bool $loadUser
573 * @param bool $throwError
574 * @param mixed $realPath
577 * @throws \CRM_Core_Exception
579 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
580 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
582 $name = $params['name'] ??
NULL;
583 $pass = $params['pass'] ??
NULL;
585 if (!defined('WP_USE_THEMES')) {
586 define('WP_USE_THEMES', FALSE);
589 $cmsRootPath = $this->cmsRootPath();
591 throw new CRM_Core_Exception("Could not find the install directory for WordPress");
593 $path = Civi
::settings()->get('wpLoadPhp');
597 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
598 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
601 throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress");
603 $wpUserTimezone = get_option('timezone_string');
604 if ($wpUserTimezone) {
605 date_default_timezone_set($wpUserTimezone);
606 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
608 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
609 $uid = $params['uid'] ??
NULL;
611 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
612 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
614 $uid = wp_authenticate($name, $pass);
617 echo '<br />Sorry, unrecognized username or password.';
625 if ($uid instanceof WP_User
) {
626 $account = wp_set_current_user($uid->ID
);
629 $account = wp_set_current_user($uid);
631 if ($account && $account->data
->ID
) {
645 public function validInstallDir($dir) {
646 $includePath = "$dir/wp-includes";
647 if (@file_exists
("$includePath/version.php")) {
654 * Determine the location of the CMS root.
656 * @return string|NULL
657 * local file system path to CMS root, or NULL if it cannot be determined
659 public function cmsRootPath() {
661 // Return early if the path is already set.
662 global $civicrm_paths;
663 if (!empty($civicrm_paths['cms.root']['path'])) {
664 return $civicrm_paths['cms.root']['path'];
667 // Return early if constant has been defined.
668 if (defined('CIVICRM_CMSDIR')) {
669 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
670 return CIVICRM_CMSDIR
;
674 // Return early if path to wp-load.php can be retrieved from settings.
675 $setting = Civi
::settings()->get('wpLoadPhp');
676 if (!empty($setting)) {
677 $path = str_replace('wp-load.php', '', $setting);
678 $cmsRoot = rtrim($path, '/\\');
679 if ($this->validInstallDir($cmsRoot)) {
685 * Keep previous logic as fallback of last resort.
687 * At some point, it would be good to remove this because there are serious
688 * problems in correctly locating WordPress in this manner. In summary, it
689 * is impossible to do so reliably.
691 * @see https://github.com/civicrm/civicrm-wordpress/pull/63#issuecomment-61792328
692 * @see https://github.com/civicrm/civicrm-core/pull/11086#issuecomment-335454992
694 $cmsRoot = $valid = NULL;
696 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
698 // Might be Windows installation.
699 $firstVar = array_shift($pathVars);
701 $cmsRoot = $firstVar;
704 // Start with CMS dir search.
705 foreach ($pathVars as $var) {
707 if ($this->validInstallDir($cmsRoot)) {
708 // Stop as we found bootstrap.
714 return ($valid) ?
$cmsRoot : NULL;
720 public function createUser(&$params, $mail) {
723 'user_pass' => $params['cms_pass'],
724 'user_login' => $params['cms_name'],
725 'user_email' => $params[$mail],
726 'nickname' => $params['cms_name'],
727 'role' => get_option('default_role'),
729 if (isset($params['contactID'])) {
730 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
731 if ($contactType == 'Individual') {
732 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
733 $params['contactID'], 'first_name'
735 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
736 $params['contactID'], 'last_name'
741 $uid = wp_insert_user($user_data);
744 $creds['user_login'] = $params['cms_name'];
745 $creds['user_password'] = $params['cms_pass'];
746 $creds['remember'] = TRUE;
747 $user = wp_signon($creds, FALSE);
749 wp_new_user_notification($uid, $user_data['user_pass']);
756 public function updateCMSName($ufID, $ufName) {
758 if (function_exists('wp_update_user')) {
759 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
760 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
762 $values = ['ID' => $ufID, 'user_email' => $ufName];
764 wp_update_user($values);
770 * @param array $params
772 * @param string $emailName
774 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
775 $config = CRM_Core_Config
::singleton();
777 $dao = new CRM_Core_DAO();
778 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
779 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
781 if (!empty($params['name'])) {
782 if (!validate_username($params['name'])) {
783 $errors['cms_name'] = ts("Your username contains invalid characters");
785 elseif (username_exists(sanitize_user($params['name']))) {
786 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
790 if (!empty($params['mail'])) {
791 if (!is_email($params['mail'])) {
792 $errors[$emailName] = "Your email is invaid";
794 elseif (email_exists($params['mail'])) {
795 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
796 [1 => $params['mail'], 2 => wp_lostpassword_url()]
805 public function isUserLoggedIn() {
807 if (function_exists('is_user_logged_in')) {
808 $isloggedIn = is_user_logged_in();
817 public function isUserRegistrationPermitted() {
818 if (!get_option('users_can_register')) {
827 public function isPasswordUserGenerated() {
834 public function getLoggedInUserObject() {
835 if (function_exists('is_user_logged_in') &&
838 global $current_user;
840 return $current_user;
846 public function getLoggedInUfID() {
848 $current_user = $this->getLoggedInUserObject();
849 return $current_user->ID ??
NULL;
855 public function getLoggedInUniqueIdentifier() {
856 $user = $this->getLoggedInUserObject();
857 return $this->getUniqueIdentifierFromUserObject($user);
861 * Get User ID from UserFramework system (Joomla)
862 * @param object $user
863 * Object as described by the CMS.
867 public function getUserIDFromUserObject($user) {
868 return !empty($user->ID
) ?
$user->ID
: NULL;
874 public function getUniqueIdentifierFromUserObject($user) {
875 return empty($user->user_email
) ?
NULL : $user->user_email
;
881 public function getLoginURL($destination = '') {
882 $config = CRM_Core_Config
::singleton();
883 $loginURL = wp_login_url();
888 * FIXME: Do something.
890 * @param \CRM_Core_Form $form
892 * @return NULL|string
894 public function getLoginDestination(&$form) {
901 public function getVersion() {
902 if (function_exists('get_bloginfo')) {
903 return get_bloginfo('version', 'display');
913 public function getTimeZoneString() {
914 return get_option('timezone_string');
920 public function getUserRecordUrl($contactID) {
921 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
922 if (CRM_Core_Session
::singleton()
923 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(['cms:administer users'])
925 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
930 * Append WP js to coreResourcesList.
932 * @param \Civi\Core\Event\GenericHookEvent $e
934 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
935 $e->list[] = 'js/crm.wordpress.js';
941 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent
$e) {
942 // Set menubar breakpoint to match WP admin theme
943 if ($e->asset
== 'crm-menubar.css') {
944 $e->params
['breakpoint'] = 783;
951 public function synchronizeUsers() {
952 $config = CRM_Core_Config
::singleton();
953 if (PHP_SAPI
!= 'cli') {
957 $mail = 'user_email';
959 $uf = $config->userFramework
;
962 $contactMatching = 0;
964 // Previously used the $wpdb global - which means WordPress *must* be bootstrapped.
965 $wpUsers = get_users(array(
966 'blog_id' => get_current_blog_id(),
970 foreach ($wpUsers as $wpUserData) {
972 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
986 if (is_object($match)) {
992 'contactCount' => $contactCount,
993 'contactMatching' => $contactMatching,
994 'contactCreated' => $contactCreated,
999 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
1001 * @param \Psr\Http\Message\ResponseInterface $response
1003 public function sendResponse(\Psr\Http\Message\ResponseInterface
$response) {
1004 // use WordPress function status_header to ensure 404 response is sent
1005 status_header($response->getStatusCode());
1006 foreach ($response->getHeaders() as $name => $values) {
1007 CRM_Utils_System
::setHttpHeader($name, implode(', ', (array) $values));
1009 echo $response->getBody();
1010 CRM_Utils_System
::civiExit();
1014 * Start a new session if there's no existing session ID.
1016 * Checks are needed to prevent sessions being started when not necessary.
1018 public function sessionStart() {
1019 $session_id = session_id();
1021 // Check WordPress pseudo-cron.
1023 if (function_exists('wp_doing_cron') && wp_doing_cron()) {
1029 if (defined('WP_CLI') && WP_CLI
) {
1033 // Check PHP on the command line - e.g. `cv`.
1035 if (PHP_SAPI
!== 'cli') {
1039 // Maybe start session.
1040 if (empty($session_id) && !$wp_cron && !$wp_cli && !$php_cli) {