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
21 * WordPress specific stuff goes here
23 class CRM_Utils_System_WordPress
extends CRM_Utils_System_Base
{
27 public function __construct() {
29 * 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
30 * functions and leave the codebase oblivious to the type of CMS
34 $this->is_drupal
= FALSE;
35 $this->is_wordpress
= TRUE;
38 public function initialize() {
40 $this->registerPathVars();
44 * Specify the default computation for various paths/URLs.
46 protected function registerPathVars():void
{
47 $isNormalBoot = function_exists('get_option');
49 // Normal mode - CMS boots first, then calls Civi. "Normal" web pages and newer extern routes.
50 // To simplify the code-paths, some items are re-registered with WP-specific functions.
51 $cmsRoot = function() {
53 'path' => untrailingslashit(ABSPATH
),
57 Civi
::paths()->register('cms', $cmsRoot);
58 Civi
::paths()->register('cms.root', $cmsRoot);
59 Civi
::paths()->register('civicrm.files', function () {
60 $upload_dir = wp_get_upload_dir();
62 'path' => $upload_dir['basedir'] . DIRECTORY_SEPARATOR
. 'civicrm' . DIRECTORY_SEPARATOR
,
63 'url' => $upload_dir['baseurl'] . '/civicrm/',
66 Civi
::paths()->register('civicrm.root', function () {
68 'path' => CIVICRM_PLUGIN_DIR
. 'civicrm' . DIRECTORY_SEPARATOR
,
69 'url' => CIVICRM_PLUGIN_URL
. 'civicrm/',
72 Civi
::paths()->register('wp.frontend.base', function () {
74 'url' => home_url('/'),
77 Civi
::paths()->register('wp.frontend', function () {
78 $config = CRM_Core_Config
::singleton();
79 $basepage = get_page_by_path($config->wpBasePage
);
81 'url' => get_permalink($basepage->ID
),
84 Civi
::paths()->register('wp.backend.base', function () {
89 Civi
::paths()->register('wp.backend', function() {
91 'url' => admin_url('admin.php'),
96 // Legacy support - only relevant for older extern routes.
98 ->register('wp.frontend.base', function () {
99 return ['url' => rtrim(CIVICRM_UF_BASEURL
, '/') . '/'];
101 ->register('wp.frontend', function () {
102 $config = \CRM_Core_Config
::singleton();
103 $suffix = defined('CIVICRM_UF_WP_BASEPAGE') ? CIVICRM_UF_WP_BASEPAGE
: $config->wpBasePage
;
105 'url' => Civi
::paths()->getVariable('wp.frontend.base', 'url') . $suffix,
108 ->register('wp.backend.base', function () {
109 return ['url' => rtrim(CIVICRM_UF_BASEURL
, '/') . '/wp-admin/'];
111 ->register('wp.backend', function () {
113 'url' => Civi
::paths()->getVariable('wp.backend.base', 'url') . 'admin.php',
122 public function setTitle($title, $pageTitle = NULL) {
127 // FIXME: Why is this global?
128 global $civicrm_wp_title;
129 $civicrm_wp_title = $title;
131 // yes, set page title, depending on context
132 $context = civi_wp()->civicrm_context_get();
136 $template = CRM_Core_Smarty
::singleton();
137 $template->assign('pageTitle', $pageTitle);
142 * Moved from CRM_Utils_System_Base
144 public function getDefaultFileStorage() {
145 $config = CRM_Core_Config
::singleton();
146 $cmsUrl = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
147 $cmsPath = $this->cmsRootPath();
148 $filesPath = CRM_Utils_File
::baseFilePath();
149 $filesRelPath = CRM_Utils_File
::relativize($filesPath, $cmsPath);
150 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
152 'url' => CRM_Utils_File
::addTrailingSlash($filesURL, '/'),
153 'path' => CRM_Utils_File
::addTrailingSlash($filesPath),
158 * Determine the location of the CiviCRM source tree.
161 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
162 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
164 public function getCiviSourceStorage() {
165 global $civicrm_root;
167 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
168 // More generally, we shouldn't be using $config here.
169 if (!defined('CIVICRM_UF_BASEURL')) {
170 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
173 $cmsPath = $this->cmsRootPath();
175 // $config = CRM_Core_Config::singleton();
176 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
177 $cmsUrl = CIVICRM_UF_BASEURL
;
178 if (CRM_Utils_System
::isSSL()) {
179 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
181 $civiRelPath = CRM_Utils_File
::relativize(realpath($civicrm_root), realpath($cmsPath));
182 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
184 'url' => CRM_Utils_File
::addTrailingSlash($civiUrl, '/'),
185 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
192 public function appendBreadCrumb($breadCrumbs) {
193 $breadCrumb = wp_get_breadcrumb();
195 if (is_array($breadCrumbs)) {
196 foreach ($breadCrumbs as $crumbs) {
197 if (stripos($crumbs['url'], 'id%%')) {
198 $args = ['cid', 'mid'];
199 foreach ($args as $a) {
200 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
204 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
208 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
212 $template = CRM_Core_Smarty
::singleton();
213 $template->assign_by_ref('breadcrumb', $breadCrumb);
214 wp_set_breadcrumb($breadCrumb);
220 public function resetBreadCrumb() {
222 wp_set_breadcrumb($bc);
228 public function addHTMLHead($head) {
229 static $registered = FALSE;
232 add_action('wp_head', [__CLASS__
, '_showHTMLHead']);
234 add_action('admin_head', [__CLASS__
, '_showHTMLHead']);
236 CRM_Core_Region
::instance('wp_head')->add([
242 * WP action callback.
244 public static function _showHTMLHead() {
245 $region = CRM_Core_Region
::instance('wp_head', FALSE);
247 echo $region->render('');
254 public function mapConfigToSSL() {
256 $base_url = str_replace('http://', 'https://', $base_url);
268 $forceBackend = FALSE
270 $config = CRM_Core_Config
::singleton();
274 $fragment = isset($fragment) ?
('#' . $fragment) : '';
276 $path = CRM_Utils_String
::stripPathChars($path);
279 //this means wp function we are trying to use is not available,
281 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
282 if (!function_exists('get_option')) {
283 $this->loadBootStrap();
286 if ($config->userFrameworkFrontend
) {
288 if (get_option('permalink_structure') != '') {
289 $script = get_permalink($post->ID
);
291 if ($config->wpBasePage
== $post->post_name
) {
294 // when shortcode is included in page
295 // also make sure we have valid query object
296 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
298 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
299 if (get_query_var('page_id')) {
300 $wpPageParam = "page_id=" . get_query_var('page_id');
302 elseif (get_query_var('p')) {
303 // when shortcode is inserted in post
304 $wpPageParam = "p=" . get_query_var('p');
309 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
311 if (!isset($path) && !isset($query)) {
312 // FIXME: This short-circuited codepath is the same as the general one below, except
313 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
314 // why it's different (and I can only find two obvious use-cases for this codepath,
315 // of which at least one looks gratuitous). A more ambitious person would simply remove
317 return $base . $fragment;
320 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
327 // not using clean URLs
329 // requesting an admin URL
330 ||
((is_admin() && !$frontend) ||
$forceBackend)
332 ||
(!$basepage && $script != '')
335 // pre-existing logic
337 // Admin URLs still need "page=CiviCRM", front-end URLs do not.
338 if ((is_admin() && !$frontend) ||
$forceBackend) {
339 $queryParts[] = 'page=CiviCRM';
342 $queryParts[] = 'civiwp=CiviCRM';
344 $queryParts[] = 'q=' . rawurlencode($path);
347 $queryParts[] = $wpPageParam;
349 if (!empty($query)) {
350 $queryParts[] = $query;
353 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
360 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
363 $query = ltrim($query, '=?&');
364 $queryParts[] = $query;
367 if (!empty($queryParts)) {
368 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
371 $final = $base . $fragment;
381 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
382 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
383 * For now leave hard coded wp-admin references.
384 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
388 * @param $forceBackend
390 * @return mixed|null|string
392 private function getBaseUrl($absolute, $frontend, $forceBackend) {
393 $config = CRM_Core_Config
::singleton();
394 if ((is_admin() && !$frontend) ||
$forceBackend) {
395 return Civi
::paths()->getUrl('[wp.backend]/.', $absolute ?
'absolute' : 'relative');
398 return Civi
::paths()->getUrl('[wp.frontend]/.', $absolute ?
'absolute' : 'relative');
405 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
406 $config = CRM_Core_Config
::singleton();
408 if ($loadCMSBootstrap) {
409 $config->userSystem
->loadBootStrap([
415 $user = wp_authenticate($name, $password);
416 if (is_a($user, 'WP_Error')) {
420 // TODO: need to change this to make sure we matched only one row
422 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
423 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
427 return [$contactID, $user->data
->ID
, mt_rand()];
431 * FIXME: Do something
433 * @param string $message
435 public function setMessage($message) {
439 * @param \string $user
443 public function loadUser($user) {
444 $userdata = get_user_by('login', $user);
445 if (!$userdata->data
->ID
) {
449 $uid = $userdata->data
->ID
;
450 wp_set_current_user($uid);
451 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
453 // lets store contact id and user id in session
454 $session = CRM_Core_Session
::singleton();
455 $session->set('ufID', $uid);
456 $session->set('userID', $contactID);
461 * FIXME: Use CMS-native approach
462 * @throws \CRM_Core_Exception
464 public function permissionDenied() {
465 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
469 * Determine the native ID of the CMS user.
471 * @param string $username
475 public function getUfId($username) {
476 $userdata = get_user_by('login', $username);
477 if (!$userdata->data
->ID
) {
480 return $userdata->data
->ID
;
486 public function logout() {
492 wp_redirect(wp_login_url());
498 public function getUFLocale() {
499 // Bail early if method is called when WordPress isn't bootstrapped.
500 // Additionally, the function checked here is located in pluggable.php
501 // and is required by wp_get_referer() - so this also bails early if it is
502 // called too early in the request lifecycle.
503 // @see https://core.trac.wordpress.org/ticket/25294
504 if (!function_exists('wp_validate_redirect')) {
508 // Default to WordPress User locale.
509 $locale = get_user_locale();
511 // Is this a "back-end" AJAX call?
513 if (wp_doing_ajax() && FALSE !== strpos(wp_get_referer(), admin_url())) {
517 // Ignore when in WordPress admin or it's a "back-end" AJAX call.
518 if (!(is_admin() ||
$is_backend)) {
520 // Reaching here means it is very likely to be a front-end context.
522 // Default to WordPress locale.
523 $locale = get_locale();
525 // Maybe override with the locale that Polylang reports.
526 if (function_exists('pll_current_language')) {
527 $pll_locale = pll_current_language('locale');
528 if (!empty($pll_locale)) {
529 $locale = $pll_locale;
533 // Maybe override with the locale that WPML reports.
534 elseif (defined('ICL_LANGUAGE_CODE')) {
535 $languages = apply_filters('wpml_active_languages', NULL);
536 foreach ($languages as $language) {
537 if ($language['active']) {
538 $locale = $language['default_locale'];
544 // TODO: Set locale for other WordPress plugins.
545 // @see https://wordpress.org/plugins/tags/multilingual/
546 // A hook would be nice here.
550 if (!empty($locale)) {
551 // If for some reason only we get a language code, convert it to a locale.
552 if (2 === strlen($locale)) {
553 $locale = CRM_Core_I18n_PseudoConstant
::longForShort($locale);
565 public function setUFLocale($civicrm_language) {
566 // TODO (probably not possible with WPML?)
571 * Load wordpress bootstrap.
573 * @param array $params
574 * Optional credentials
575 * - name: string, cms username
576 * - pass: string, cms password
577 * @param bool $loadUser
578 * @param bool $throwError
579 * @param mixed $realPath
582 * @throws \CRM_Core_Exception
584 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
585 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
587 $name = $params['name'] ??
NULL;
588 $pass = $params['pass'] ??
NULL;
590 if (!defined('WP_USE_THEMES')) {
591 define('WP_USE_THEMES', FALSE);
594 $cmsRootPath = $this->cmsRootPath();
596 throw new CRM_Core_Exception("Could not find the install directory for WordPress");
598 $path = Civi
::settings()->get('wpLoadPhp');
602 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
603 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
606 throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress");
608 $wpUserTimezone = get_option('timezone_string');
609 if ($wpUserTimezone) {
610 date_default_timezone_set($wpUserTimezone);
611 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
613 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
614 $uid = $params['uid'] ??
NULL;
616 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
617 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
619 $uid = wp_authenticate($name, $pass);
622 echo '<br />Sorry, unrecognized username or password.';
630 if ($uid instanceof WP_User
) {
631 $account = wp_set_current_user($uid->ID
);
634 $account = wp_set_current_user($uid);
636 if ($account && $account->data
->ID
) {
650 public function validInstallDir($dir) {
651 $includePath = "$dir/wp-includes";
652 if (@file_exists
("$includePath/version.php")) {
659 * Determine the location of the CMS root.
661 * @return string|NULL
662 * local file system path to CMS root, or NULL if it cannot be determined
664 public function cmsRootPath() {
666 // Return early if the path is already set.
667 global $civicrm_paths;
668 if (!empty($civicrm_paths['cms.root']['path'])) {
669 return $civicrm_paths['cms.root']['path'];
672 // Return early if constant has been defined.
673 if (defined('CIVICRM_CMSDIR')) {
674 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
675 return CIVICRM_CMSDIR
;
679 // Return early if path to wp-load.php can be retrieved from settings.
680 $setting = Civi
::settings()->get('wpLoadPhp');
681 if (!empty($setting)) {
682 $path = str_replace('wp-load.php', '', $setting);
683 $cmsRoot = rtrim($path, '/\\');
684 if ($this->validInstallDir($cmsRoot)) {
690 * Keep previous logic as fallback of last resort.
692 * At some point, it would be good to remove this because there are serious
693 * problems in correctly locating WordPress in this manner. In summary, it
694 * is impossible to do so reliably.
696 * @see https://github.com/civicrm/civicrm-wordpress/pull/63#issuecomment-61792328
697 * @see https://github.com/civicrm/civicrm-core/pull/11086#issuecomment-335454992
699 $cmsRoot = $valid = NULL;
701 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
703 // Might be Windows installation.
704 $firstVar = array_shift($pathVars);
706 $cmsRoot = $firstVar;
709 // Start with CMS dir search.
710 foreach ($pathVars as $var) {
712 if ($this->validInstallDir($cmsRoot)) {
713 // Stop as we found bootstrap.
719 return ($valid) ?
$cmsRoot : NULL;
725 public function createUser(&$params, $mail) {
728 'user_pass' => $params['cms_pass'],
729 'user_login' => $params['cms_name'],
730 'user_email' => $params[$mail],
731 'nickname' => $params['cms_name'],
732 'role' => get_option('default_role'),
734 if (isset($params['contactID'])) {
735 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
736 if ($contactType == 'Individual') {
737 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
738 $params['contactID'], 'first_name'
740 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
741 $params['contactID'], 'last_name'
746 $uid = wp_insert_user($user_data);
749 $creds['user_login'] = $params['cms_name'];
750 $creds['user_password'] = $params['cms_pass'];
751 $creds['remember'] = TRUE;
752 $user = wp_signon($creds, FALSE);
754 wp_new_user_notification($uid, $user_data['user_pass']);
761 public function updateCMSName($ufID, $ufName) {
763 if (function_exists('wp_update_user')) {
764 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
765 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
767 $values = ['ID' => $ufID, 'user_email' => $ufName];
769 wp_update_user($values);
775 * @param array $params
777 * @param string $emailName
779 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
780 $config = CRM_Core_Config
::singleton();
782 $dao = new CRM_Core_DAO();
783 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
784 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
786 if (!empty($params['name'])) {
787 if (!validate_username($params['name'])) {
788 $errors['cms_name'] = ts("Your username contains invalid characters");
790 elseif (username_exists(sanitize_user($params['name']))) {
791 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
795 if (!empty($params['mail'])) {
796 if (!is_email($params['mail'])) {
797 $errors[$emailName] = "Your email is invaid";
799 elseif (email_exists($params['mail'])) {
800 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
801 [1 => $params['mail'], 2 => wp_lostpassword_url()]
810 public function isUserLoggedIn() {
812 if (function_exists('is_user_logged_in')) {
813 $isloggedIn = is_user_logged_in();
822 public function isUserRegistrationPermitted() {
823 if (!get_option('users_can_register')) {
832 public function isPasswordUserGenerated() {
839 public function getLoggedInUserObject() {
840 if (function_exists('is_user_logged_in') &&
843 global $current_user;
845 return $current_user;
851 public function getLoggedInUfID() {
853 $current_user = $this->getLoggedInUserObject();
854 return $current_user->ID ??
NULL;
860 public function getLoggedInUniqueIdentifier() {
861 $user = $this->getLoggedInUserObject();
862 return $this->getUniqueIdentifierFromUserObject($user);
866 * Get User ID from UserFramework system (Joomla)
867 * @param object $user
868 * Object as described by the CMS.
872 public function getUserIDFromUserObject($user) {
873 return !empty($user->ID
) ?
$user->ID
: NULL;
879 public function getUniqueIdentifierFromUserObject($user) {
880 return empty($user->user_email
) ?
NULL : $user->user_email
;
886 public function getLoginURL($destination = '') {
887 $config = CRM_Core_Config
::singleton();
888 $loginURL = wp_login_url();
893 * FIXME: Do something.
895 * @param \CRM_Core_Form $form
897 * @return NULL|string
899 public function getLoginDestination(&$form) {
906 public function getVersion() {
907 if (function_exists('get_bloginfo')) {
908 return get_bloginfo('version', 'display');
918 public function getTimeZoneString() {
919 return get_option('timezone_string');
925 public function getUserRecordUrl($contactID) {
926 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
927 if (CRM_Core_Session
::singleton()
928 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(['cms:administer users'])
930 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
935 * Append WP js to coreResourcesList.
937 * @param \Civi\Core\Event\GenericHookEvent $e
939 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
940 $e->list[] = 'js/crm.wordpress.js';
946 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent
$e) {
947 // Set menubar breakpoint to match WP admin theme
948 if ($e->asset
== 'crm-menubar.css') {
949 $e->params
['breakpoint'] = 783;
956 public function synchronizeUsers() {
957 $config = CRM_Core_Config
::singleton();
958 if (PHP_SAPI
!= 'cli') {
962 $mail = 'user_email';
964 $uf = $config->userFramework
;
967 $contactMatching = 0;
969 // Previously used the $wpdb global - which means WordPress *must* be bootstrapped.
970 $wpUsers = get_users(array(
971 'blog_id' => get_current_blog_id(),
975 foreach ($wpUsers as $wpUserData) {
977 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
991 if (is_object($match)) {
997 'contactCount' => $contactCount,
998 'contactMatching' => $contactMatching,
999 'contactCreated' => $contactCreated,
1004 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
1006 * @param \Psr\Http\Message\ResponseInterface $response
1008 public function sendResponse(\Psr\Http\Message\ResponseInterface
$response) {
1009 // use WordPress function status_header to ensure 404 response is sent
1010 status_header($response->getStatusCode());
1011 foreach ($response->getHeaders() as $name => $values) {
1012 CRM_Utils_System
::setHttpHeader($name, implode(', ', (array) $values));
1014 echo $response->getBody();
1015 CRM_Utils_System
::civiExit();