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 $config = CRM_Core_Config
::singleton();
137 $cmsUrl = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
138 $cmsPath = $this->cmsRootPath();
139 $filesPath = CRM_Utils_File
::baseFilePath();
140 $filesRelPath = CRM_Utils_File
::relativize($filesPath, $cmsPath);
141 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
143 'url' => CRM_Utils_File
::addTrailingSlash($filesURL, '/'),
144 'path' => CRM_Utils_File
::addTrailingSlash($filesPath),
149 * Determine the location of the CiviCRM source tree.
152 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
153 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
155 public function getCiviSourceStorage() {
156 global $civicrm_root;
158 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
159 // More generally, we shouldn't be using $config here.
160 if (!defined('CIVICRM_UF_BASEURL')) {
161 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
164 $cmsPath = $this->cmsRootPath();
166 // $config = CRM_Core_Config::singleton();
167 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
168 $cmsUrl = CIVICRM_UF_BASEURL
;
169 if (CRM_Utils_System
::isSSL()) {
170 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
172 $civiRelPath = CRM_Utils_File
::relativize(realpath($civicrm_root), realpath($cmsPath));
173 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
175 'url' => CRM_Utils_File
::addTrailingSlash($civiUrl, '/'),
176 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
183 public function appendBreadCrumb($breadCrumbs) {
184 $breadCrumb = wp_get_breadcrumb();
186 if (is_array($breadCrumbs)) {
187 foreach ($breadCrumbs as $crumbs) {
188 if (stripos($crumbs['url'], 'id%%')) {
189 $args = ['cid', 'mid'];
190 foreach ($args as $a) {
191 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
195 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
199 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
203 $template = CRM_Core_Smarty
::singleton();
204 $template->assign_by_ref('breadcrumb', $breadCrumb);
205 wp_set_breadcrumb($breadCrumb);
211 public function resetBreadCrumb() {
213 wp_set_breadcrumb($bc);
219 public function addHTMLHead($head) {
220 static $registered = FALSE;
223 add_action('wp_head', [__CLASS__
, '_showHTMLHead']);
225 add_action('admin_head', [__CLASS__
, '_showHTMLHead']);
227 CRM_Core_Region
::instance('wp_head')->add([
233 * WP action callback.
235 public static function _showHTMLHead() {
236 $region = CRM_Core_Region
::instance('wp_head', FALSE);
238 echo $region->render('');
245 public function mapConfigToSSL() {
247 $base_url = str_replace('http://', 'https://', $base_url);
259 $forceBackend = FALSE,
262 $config = CRM_Core_Config
::singleton();
266 $fragment = isset($fragment) ?
('#' . $fragment) : '';
268 $path = CRM_Utils_String
::stripPathChars($path);
271 //this means wp function we are trying to use is not available,
273 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
274 if (!function_exists('get_option')) {
275 $this->loadBootStrap();
278 if ($config->userFrameworkFrontend
) {
280 if (get_option('permalink_structure') != '') {
281 $script = get_permalink($post->ID
);
283 if ($config->wpBasePage
== $post->post_name
) {
286 // when shortcode is included in page
287 // also make sure we have valid query object
288 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
290 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
291 if (get_query_var('page_id')) {
292 $wpPageParam = "page_id=" . get_query_var('page_id');
294 elseif (get_query_var('p')) {
295 // when shortcode is inserted in post
296 $wpPageParam = "p=" . get_query_var('p');
301 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
303 if (!isset($path) && !isset($query)) {
304 // FIXME: This short-circuited codepath is the same as the general one below, except
305 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
306 // why it's different (and I can only find two obvious use-cases for this codepath,
307 // of which at least one looks gratuitous). A more ambitious person would simply remove
309 return $base . $fragment;
312 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
319 // not using clean URLs
321 // requesting an admin URL
322 ||
((is_admin() && !$frontend) ||
$forceBackend)
324 ||
(!$basepage && $script != '')
327 // pre-existing logic
329 // Admin URLs still need "page=CiviCRM", front-end URLs do not.
330 if ((is_admin() && !$frontend) ||
$forceBackend) {
331 $queryParts[] = 'page=CiviCRM';
334 $queryParts[] = 'civiwp=CiviCRM';
336 $queryParts[] = 'q=' . rawurlencode($path);
339 $queryParts[] = $wpPageParam;
341 if (!empty($query)) {
342 $queryParts[] = $query;
345 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
352 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
355 $query = ltrim($query, '=?&');
356 $queryParts[] = $query;
359 if (!empty($queryParts)) {
360 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
363 $final = $base . $fragment;
373 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
374 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
375 * For now leave hard coded wp-admin references.
376 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
380 * @param $forceBackend
382 * @return mixed|null|string
384 private function getBaseUrl($absolute, $frontend, $forceBackend) {
385 $config = CRM_Core_Config
::singleton();
386 if ((is_admin() && !$frontend) ||
$forceBackend) {
387 return Civi
::paths()->getUrl('[wp.backend]/.', $absolute ?
'absolute' : 'relative');
390 return Civi
::paths()->getUrl('[wp.frontend]/.', $absolute ?
'absolute' : 'relative');
397 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
398 $config = CRM_Core_Config
::singleton();
400 if ($loadCMSBootstrap) {
401 $config->userSystem
->loadBootStrap([
407 $user = wp_authenticate($name, $password);
408 if (is_a($user, 'WP_Error')) {
412 // TODO: need to change this to make sure we matched only one row
414 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
415 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
419 return [$contactID, $user->data
->ID
, mt_rand()];
423 * FIXME: Do something
425 * @param string $message
427 public function setMessage($message) {
431 * @param \string $user
435 public function loadUser($user) {
436 $userdata = get_user_by('login', $user);
437 if (!$userdata->data
->ID
) {
441 $uid = $userdata->data
->ID
;
442 wp_set_current_user($uid);
443 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
445 // lets store contact id and user id in session
446 $session = CRM_Core_Session
::singleton();
447 $session->set('ufID', $uid);
448 $session->set('userID', $contactID);
453 * FIXME: Use CMS-native approach
454 * @throws \CRM_Core_Exception
456 public function permissionDenied() {
457 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
461 * Determine the native ID of the CMS user.
463 * @param string $username
467 public function getUfId($username) {
468 $userdata = get_user_by('login', $username);
469 if (!$userdata->data
->ID
) {
472 return $userdata->data
->ID
;
478 public function logout() {
484 wp_redirect(wp_login_url());
490 public function getUFLocale() {
491 // Bail early if method is called when WordPress isn't bootstrapped.
492 // Additionally, the function checked here is located in pluggable.php
493 // and is required by wp_get_referer() - so this also bails early if it is
494 // called too early in the request lifecycle.
495 // @see https://core.trac.wordpress.org/ticket/25294
496 if (!function_exists('wp_validate_redirect')) {
500 // Default to WordPress User locale.
501 $locale = get_user_locale();
503 // Is this a "back-end" AJAX call?
505 if (wp_doing_ajax() && FALSE !== strpos(wp_get_referer(), admin_url())) {
509 // Ignore when in WordPress admin or it's a "back-end" AJAX call.
510 if (!(is_admin() ||
$is_backend)) {
512 // Reaching here means it is very likely to be a front-end context.
514 // Default to WordPress locale.
515 $locale = get_locale();
517 // Maybe override with the locale that Polylang reports.
518 if (function_exists('pll_current_language')) {
519 $pll_locale = pll_current_language('locale');
520 if (!empty($pll_locale)) {
521 $locale = $pll_locale;
525 // Maybe override with the locale that WPML reports.
526 elseif (defined('ICL_LANGUAGE_CODE')) {
527 $languages = apply_filters('wpml_active_languages', NULL);
528 foreach ($languages as $language) {
529 if ($language['active']) {
530 $locale = $language['default_locale'];
536 // TODO: Set locale for other WordPress plugins.
537 // @see https://wordpress.org/plugins/tags/multilingual/
538 // A hook would be nice here.
542 if (!empty($locale)) {
543 // If for some reason only we get a language code, convert it to a locale.
544 if (2 === strlen($locale)) {
545 $locale = CRM_Core_I18n_PseudoConstant
::longForShort($locale);
557 public function setUFLocale($civicrm_language) {
558 // TODO (probably not possible with WPML?)
563 * Load wordpress bootstrap.
565 * @param array $params
566 * Optional credentials
567 * - name: string, cms username
568 * - pass: string, cms password
569 * @param bool $loadUser
570 * @param bool $throwError
571 * @param mixed $realPath
574 * @throws \CRM_Core_Exception
576 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
577 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
579 $name = $params['name'] ??
NULL;
580 $pass = $params['pass'] ??
NULL;
582 if (!defined('WP_USE_THEMES')) {
583 define('WP_USE_THEMES', FALSE);
586 $cmsRootPath = $this->cmsRootPath();
588 throw new CRM_Core_Exception("Could not find the install directory for WordPress");
590 $path = Civi
::settings()->get('wpLoadPhp');
594 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
595 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
598 throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress");
600 $wpUserTimezone = get_option('timezone_string');
601 if ($wpUserTimezone) {
602 date_default_timezone_set($wpUserTimezone);
603 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
605 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
606 $uid = $params['uid'] ??
NULL;
608 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
609 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
611 $uid = wp_authenticate($name, $pass);
614 echo '<br />Sorry, unrecognized username or password.';
622 if ($uid instanceof WP_User
) {
623 $account = wp_set_current_user($uid->ID
);
626 $account = wp_set_current_user($uid);
628 if ($account && $account->data
->ID
) {
642 public function validInstallDir($dir) {
643 $includePath = "$dir/wp-includes";
644 if (@file_exists
("$includePath/version.php")) {
651 * Determine the location of the CMS root.
653 * @return string|NULL
654 * local file system path to CMS root, or NULL if it cannot be determined
656 public function cmsRootPath() {
658 // Return early if the path is already set.
659 global $civicrm_paths;
660 if (!empty($civicrm_paths['cms.root']['path'])) {
661 return $civicrm_paths['cms.root']['path'];
664 // Return early if constant has been defined.
665 if (defined('CIVICRM_CMSDIR')) {
666 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
667 return CIVICRM_CMSDIR
;
671 // Return early if path to wp-load.php can be retrieved from settings.
672 $setting = Civi
::settings()->get('wpLoadPhp');
673 if (!empty($setting)) {
674 $path = str_replace('wp-load.php', '', $setting);
675 $cmsRoot = rtrim($path, '/\\');
676 if ($this->validInstallDir($cmsRoot)) {
682 * Keep previous logic as fallback of last resort.
684 * At some point, it would be good to remove this because there are serious
685 * problems in correctly locating WordPress in this manner. In summary, it
686 * is impossible to do so reliably.
688 * @see https://github.com/civicrm/civicrm-wordpress/pull/63#issuecomment-61792328
689 * @see https://github.com/civicrm/civicrm-core/pull/11086#issuecomment-335454992
691 $cmsRoot = $valid = NULL;
693 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
695 // Might be Windows installation.
696 $firstVar = array_shift($pathVars);
698 $cmsRoot = $firstVar;
701 // Start with CMS dir search.
702 foreach ($pathVars as $var) {
704 if ($this->validInstallDir($cmsRoot)) {
705 // Stop as we found bootstrap.
711 return ($valid) ?
$cmsRoot : NULL;
717 public function createUser(&$params, $mail) {
720 'user_pass' => $params['cms_pass'],
721 'user_login' => $params['cms_name'],
722 'user_email' => $params[$mail],
723 'nickname' => $params['cms_name'],
724 'role' => get_option('default_role'),
726 if (isset($params['contactID'])) {
727 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
728 if ($contactType == 'Individual') {
729 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
730 $params['contactID'], 'first_name'
732 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
733 $params['contactID'], 'last_name'
738 $uid = wp_insert_user($user_data);
741 $creds['user_login'] = $params['cms_name'];
742 $creds['user_password'] = $params['cms_pass'];
743 $creds['remember'] = TRUE;
744 $user = wp_signon($creds, FALSE);
746 wp_new_user_notification($uid, $user_data['user_pass']);
753 public function updateCMSName($ufID, $ufName) {
755 if (function_exists('wp_update_user')) {
756 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
757 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
759 $values = ['ID' => $ufID, 'user_email' => $ufName];
761 wp_update_user($values);
767 * @param array $params
769 * @param string $emailName
771 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
772 $config = CRM_Core_Config
::singleton();
774 $dao = new CRM_Core_DAO();
775 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
776 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
778 if (!empty($params['name'])) {
779 if (!validate_username($params['name'])) {
780 $errors['cms_name'] = ts("Your username contains invalid characters");
782 elseif (username_exists(sanitize_user($params['name']))) {
783 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
787 if (!empty($params['mail'])) {
788 if (!is_email($params['mail'])) {
789 $errors[$emailName] = "Your email is invaid";
791 elseif (email_exists($params['mail'])) {
792 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
793 [1 => $params['mail'], 2 => wp_lostpassword_url()]
802 public function isUserLoggedIn() {
804 if (function_exists('is_user_logged_in')) {
805 $isloggedIn = is_user_logged_in();
814 public function isUserRegistrationPermitted() {
815 if (!get_option('users_can_register')) {
824 public function isPasswordUserGenerated() {
831 public function getLoggedInUserObject() {
832 if (function_exists('is_user_logged_in') &&
835 global $current_user;
837 return $current_user;
843 public function getLoggedInUfID() {
845 $current_user = $this->getLoggedInUserObject();
846 return $current_user->ID ??
NULL;
852 public function getLoggedInUniqueIdentifier() {
853 $user = $this->getLoggedInUserObject();
854 return $this->getUniqueIdentifierFromUserObject($user);
858 * Get User ID from UserFramework system (Joomla)
859 * @param object $user
860 * Object as described by the CMS.
864 public function getUserIDFromUserObject($user) {
865 return !empty($user->ID
) ?
$user->ID
: NULL;
871 public function getUniqueIdentifierFromUserObject($user) {
872 return empty($user->user_email
) ?
NULL : $user->user_email
;
878 public function getLoginURL($destination = '') {
879 $config = CRM_Core_Config
::singleton();
880 $loginURL = wp_login_url();
885 * FIXME: Do something.
887 * @param \CRM_Core_Form $form
889 * @return NULL|string
891 public function getLoginDestination(&$form) {
898 public function getVersion() {
899 if (function_exists('get_bloginfo')) {
900 return get_bloginfo('version', 'display');
910 public function getTimeZoneString() {
911 return get_option('timezone_string');
917 public function getUserRecordUrl($contactID) {
918 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
919 if (CRM_Core_Session
::singleton()
920 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(['cms:administer users'])
922 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
927 * Append WP js to coreResourcesList.
929 * @param \Civi\Core\Event\GenericHookEvent $e
931 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
932 $e->list[] = 'js/crm.wordpress.js';
938 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent
$e) {
939 // Set menubar breakpoint to match WP admin theme
940 if ($e->asset
== 'crm-menubar.css') {
941 $e->params
['breakpoint'] = 783;
948 public function synchronizeUsers() {
949 $config = CRM_Core_Config
::singleton();
950 if (PHP_SAPI
!= 'cli') {
954 $mail = 'user_email';
956 $uf = $config->userFramework
;
959 $contactMatching = 0;
961 // Previously used the $wpdb global - which means WordPress *must* be bootstrapped.
962 $wpUsers = get_users(array(
963 'blog_id' => get_current_blog_id(),
967 foreach ($wpUsers as $wpUserData) {
969 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
983 if (is_object($match)) {
989 'contactCount' => $contactCount,
990 'contactMatching' => $contactMatching,
991 'contactCreated' => $contactCreated,
996 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
998 * @param \Psr\Http\Message\ResponseInterface $response
1000 public function sendResponse(\Psr\Http\Message\ResponseInterface
$response) {
1001 // use WordPress function status_header to ensure 404 response is sent
1002 status_header($response->getStatusCode());
1003 foreach ($response->getHeaders() as $name => $values) {
1004 CRM_Utils_System
::setHttpHeader($name, implode(', ', (array) $values));
1006 echo $response->getBody();
1007 CRM_Utils_System
::civiExit();
1011 * Start a new session if there's no existing session ID.
1013 * Checks are needed to prevent sessions being started when not necessary.
1015 public function sessionStart() {
1016 $session_id = session_id();
1018 // Check WordPress pseudo-cron.
1020 if (function_exists('wp_doing_cron') && wp_doing_cron()) {
1026 if (defined('WP_CLI') && WP_CLI
) {
1030 // Check PHP on the command line - e.g. `cv`.
1032 if (PHP_SAPI
!== 'cli') {
1036 // Maybe start session.
1037 if (empty($session_id) && !$wp_cron && !$wp_cli && !$php_cli) {