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,
271 $config = CRM_Core_Config
::singleton();
275 $fragment = isset($fragment) ?
('#' . $fragment) : '';
277 $path = CRM_Utils_String
::stripPathChars($path);
280 //this means wp function we are trying to use is not available,
282 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
283 if (!function_exists('get_option')) {
284 $this->loadBootStrap();
287 if ($config->userFrameworkFrontend
) {
289 if (get_option('permalink_structure') != '') {
290 $script = get_permalink($post->ID
);
292 if ($config->wpBasePage
== $post->post_name
) {
295 // when shortcode is included in page
296 // also make sure we have valid query object
297 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
299 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
300 if (get_query_var('page_id')) {
301 $wpPageParam = "page_id=" . get_query_var('page_id');
303 elseif (get_query_var('p')) {
304 // when shortcode is inserted in post
305 $wpPageParam = "p=" . get_query_var('p');
310 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
312 if (!isset($path) && !isset($query)) {
313 // FIXME: This short-circuited codepath is the same as the general one below, except
314 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
315 // why it's different (and I can only find two obvious use-cases for this codepath,
316 // of which at least one looks gratuitous). A more ambitious person would simply remove
318 return $base . $fragment;
321 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
328 // not using clean URLs
330 // requesting an admin URL
331 ||
((is_admin() && !$frontend) ||
$forceBackend)
333 ||
(!$basepage && $script != '')
336 // pre-existing logic
338 // Admin URLs still need "page=CiviCRM", front-end URLs do not.
339 if ((is_admin() && !$frontend) ||
$forceBackend) {
340 $queryParts[] = 'page=CiviCRM';
343 $queryParts[] = 'civiwp=CiviCRM';
345 $queryParts[] = 'q=' . rawurlencode($path);
348 $queryParts[] = $wpPageParam;
350 if (!empty($query)) {
351 $queryParts[] = $query;
354 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
361 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
364 $query = ltrim($query, '=?&');
365 $queryParts[] = $query;
368 if (!empty($queryParts)) {
369 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
372 $final = $base . $fragment;
382 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
383 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
384 * For now leave hard coded wp-admin references.
385 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
389 * @param $forceBackend
391 * @return mixed|null|string
393 private function getBaseUrl($absolute, $frontend, $forceBackend) {
394 $config = CRM_Core_Config
::singleton();
395 if ((is_admin() && !$frontend) ||
$forceBackend) {
396 return Civi
::paths()->getUrl('[wp.backend]/.', $absolute ?
'absolute' : 'relative');
399 return Civi
::paths()->getUrl('[wp.frontend]/.', $absolute ?
'absolute' : 'relative');
406 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
407 $config = CRM_Core_Config
::singleton();
409 if ($loadCMSBootstrap) {
410 $config->userSystem
->loadBootStrap([
416 $user = wp_authenticate($name, $password);
417 if (is_a($user, 'WP_Error')) {
421 // TODO: need to change this to make sure we matched only one row
423 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
424 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
428 return [$contactID, $user->data
->ID
, mt_rand()];
432 * FIXME: Do something
434 * @param string $message
436 public function setMessage($message) {
440 * @param \string $user
444 public function loadUser($user) {
445 $userdata = get_user_by('login', $user);
446 if (!$userdata->data
->ID
) {
450 $uid = $userdata->data
->ID
;
451 wp_set_current_user($uid);
452 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
454 // lets store contact id and user id in session
455 $session = CRM_Core_Session
::singleton();
456 $session->set('ufID', $uid);
457 $session->set('userID', $contactID);
462 * FIXME: Use CMS-native approach
463 * @throws \CRM_Core_Exception
465 public function permissionDenied() {
466 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
470 * Determine the native ID of the CMS user.
472 * @param string $username
476 public function getUfId($username) {
477 $userdata = get_user_by('login', $username);
478 if (!$userdata->data
->ID
) {
481 return $userdata->data
->ID
;
487 public function logout() {
493 wp_redirect(wp_login_url());
499 public function getUFLocale() {
500 // Bail early if method is called when WordPress isn't bootstrapped.
501 // Additionally, the function checked here is located in pluggable.php
502 // and is required by wp_get_referer() - so this also bails early if it is
503 // called too early in the request lifecycle.
504 // @see https://core.trac.wordpress.org/ticket/25294
505 if (!function_exists('wp_validate_redirect')) {
509 // Default to WordPress User locale.
510 $locale = get_user_locale();
512 // Is this a "back-end" AJAX call?
514 if (wp_doing_ajax() && FALSE !== strpos(wp_get_referer(), admin_url())) {
518 // Ignore when in WordPress admin or it's a "back-end" AJAX call.
519 if (!(is_admin() ||
$is_backend)) {
521 // Reaching here means it is very likely to be a front-end context.
523 // Default to WordPress locale.
524 $locale = get_locale();
526 // Maybe override with the locale that Polylang reports.
527 if (function_exists('pll_current_language')) {
528 $pll_locale = pll_current_language('locale');
529 if (!empty($pll_locale)) {
530 $locale = $pll_locale;
534 // Maybe override with the locale that WPML reports.
535 elseif (defined('ICL_LANGUAGE_CODE')) {
536 $languages = apply_filters('wpml_active_languages', NULL);
537 foreach ($languages as $language) {
538 if ($language['active']) {
539 $locale = $language['default_locale'];
545 // TODO: Set locale for other WordPress plugins.
546 // @see https://wordpress.org/plugins/tags/multilingual/
547 // A hook would be nice here.
551 if (!empty($locale)) {
552 // If for some reason only we get a language code, convert it to a locale.
553 if (2 === strlen($locale)) {
554 $locale = CRM_Core_I18n_PseudoConstant
::longForShort($locale);
566 public function setUFLocale($civicrm_language) {
567 // TODO (probably not possible with WPML?)
572 * Load wordpress bootstrap.
574 * @param array $params
575 * Optional credentials
576 * - name: string, cms username
577 * - pass: string, cms password
578 * @param bool $loadUser
579 * @param bool $throwError
580 * @param mixed $realPath
583 * @throws \CRM_Core_Exception
585 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
586 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
588 $name = $params['name'] ??
NULL;
589 $pass = $params['pass'] ??
NULL;
591 if (!defined('WP_USE_THEMES')) {
592 define('WP_USE_THEMES', FALSE);
595 $cmsRootPath = $this->cmsRootPath();
597 throw new CRM_Core_Exception("Could not find the install directory for WordPress");
599 $path = Civi
::settings()->get('wpLoadPhp');
603 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
604 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
607 throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress");
609 $wpUserTimezone = get_option('timezone_string');
610 if ($wpUserTimezone) {
611 date_default_timezone_set($wpUserTimezone);
612 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
614 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
615 $uid = $params['uid'] ??
NULL;
617 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
618 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
620 $uid = wp_authenticate($name, $pass);
623 echo '<br />Sorry, unrecognized username or password.';
631 if ($uid instanceof WP_User
) {
632 $account = wp_set_current_user($uid->ID
);
635 $account = wp_set_current_user($uid);
637 if ($account && $account->data
->ID
) {
651 public function validInstallDir($dir) {
652 $includePath = "$dir/wp-includes";
653 if (@file_exists
("$includePath/version.php")) {
660 * Determine the location of the CMS root.
662 * @return string|NULL
663 * local file system path to CMS root, or NULL if it cannot be determined
665 public function cmsRootPath() {
667 // Return early if the path is already set.
668 global $civicrm_paths;
669 if (!empty($civicrm_paths['cms.root']['path'])) {
670 return $civicrm_paths['cms.root']['path'];
673 // Return early if constant has been defined.
674 if (defined('CIVICRM_CMSDIR')) {
675 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
676 return CIVICRM_CMSDIR
;
680 // Return early if path to wp-load.php can be retrieved from settings.
681 $setting = Civi
::settings()->get('wpLoadPhp');
682 if (!empty($setting)) {
683 $path = str_replace('wp-load.php', '', $setting);
684 $cmsRoot = rtrim($path, '/\\');
685 if ($this->validInstallDir($cmsRoot)) {
691 * Keep previous logic as fallback of last resort.
693 * At some point, it would be good to remove this because there are serious
694 * problems in correctly locating WordPress in this manner. In summary, it
695 * is impossible to do so reliably.
697 * @see https://github.com/civicrm/civicrm-wordpress/pull/63#issuecomment-61792328
698 * @see https://github.com/civicrm/civicrm-core/pull/11086#issuecomment-335454992
700 $cmsRoot = $valid = NULL;
702 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
704 // Might be Windows installation.
705 $firstVar = array_shift($pathVars);
707 $cmsRoot = $firstVar;
710 // Start with CMS dir search.
711 foreach ($pathVars as $var) {
713 if ($this->validInstallDir($cmsRoot)) {
714 // Stop as we found bootstrap.
720 return ($valid) ?
$cmsRoot : NULL;
726 public function createUser(&$params, $mail) {
729 'user_pass' => $params['cms_pass'],
730 'user_login' => $params['cms_name'],
731 'user_email' => $params[$mail],
732 'nickname' => $params['cms_name'],
733 'role' => get_option('default_role'),
735 if (isset($params['contactID'])) {
736 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
737 if ($contactType == 'Individual') {
738 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
739 $params['contactID'], 'first_name'
741 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
742 $params['contactID'], 'last_name'
747 $uid = wp_insert_user($user_data);
750 $creds['user_login'] = $params['cms_name'];
751 $creds['user_password'] = $params['cms_pass'];
752 $creds['remember'] = TRUE;
753 $user = wp_signon($creds, FALSE);
755 wp_new_user_notification($uid, $user_data['user_pass']);
762 public function updateCMSName($ufID, $ufName) {
764 if (function_exists('wp_update_user')) {
765 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
766 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
768 $values = ['ID' => $ufID, 'user_email' => $ufName];
770 wp_update_user($values);
776 * @param array $params
778 * @param string $emailName
780 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
781 $config = CRM_Core_Config
::singleton();
783 $dao = new CRM_Core_DAO();
784 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
785 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
787 if (!empty($params['name'])) {
788 if (!validate_username($params['name'])) {
789 $errors['cms_name'] = ts("Your username contains invalid characters");
791 elseif (username_exists(sanitize_user($params['name']))) {
792 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
796 if (!empty($params['mail'])) {
797 if (!is_email($params['mail'])) {
798 $errors[$emailName] = "Your email is invaid";
800 elseif (email_exists($params['mail'])) {
801 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
802 [1 => $params['mail'], 2 => wp_lostpassword_url()]
811 public function isUserLoggedIn() {
813 if (function_exists('is_user_logged_in')) {
814 $isloggedIn = is_user_logged_in();
823 public function isUserRegistrationPermitted() {
824 if (!get_option('users_can_register')) {
833 public function isPasswordUserGenerated() {
840 public function getLoggedInUserObject() {
841 if (function_exists('is_user_logged_in') &&
844 global $current_user;
846 return $current_user;
852 public function getLoggedInUfID() {
854 $current_user = $this->getLoggedInUserObject();
855 return $current_user->ID ??
NULL;
861 public function getLoggedInUniqueIdentifier() {
862 $user = $this->getLoggedInUserObject();
863 return $this->getUniqueIdentifierFromUserObject($user);
867 * Get User ID from UserFramework system (Joomla)
868 * @param object $user
869 * Object as described by the CMS.
873 public function getUserIDFromUserObject($user) {
874 return !empty($user->ID
) ?
$user->ID
: NULL;
880 public function getUniqueIdentifierFromUserObject($user) {
881 return empty($user->user_email
) ?
NULL : $user->user_email
;
887 public function getLoginURL($destination = '') {
888 $config = CRM_Core_Config
::singleton();
889 $loginURL = wp_login_url();
894 * FIXME: Do something.
896 * @param \CRM_Core_Form $form
898 * @return NULL|string
900 public function getLoginDestination(&$form) {
907 public function getVersion() {
908 if (function_exists('get_bloginfo')) {
909 return get_bloginfo('version', 'display');
919 public function getTimeZoneString() {
920 return get_option('timezone_string');
926 public function getUserRecordUrl($contactID) {
927 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
928 if (CRM_Core_Session
::singleton()
929 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(['cms:administer users'])
931 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
936 * Append WP js to coreResourcesList.
938 * @param \Civi\Core\Event\GenericHookEvent $e
940 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
941 $e->list[] = 'js/crm.wordpress.js';
947 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent
$e) {
948 // Set menubar breakpoint to match WP admin theme
949 if ($e->asset
== 'crm-menubar.css') {
950 $e->params
['breakpoint'] = 783;
957 public function synchronizeUsers() {
958 $config = CRM_Core_Config
::singleton();
959 if (PHP_SAPI
!= 'cli') {
963 $mail = 'user_email';
965 $uf = $config->userFramework
;
968 $contactMatching = 0;
970 // Previously used the $wpdb global - which means WordPress *must* be bootstrapped.
971 $wpUsers = get_users(array(
972 'blog_id' => get_current_blog_id(),
976 foreach ($wpUsers as $wpUserData) {
978 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
992 if (is_object($match)) {
998 'contactCount' => $contactCount,
999 'contactMatching' => $contactMatching,
1000 'contactCreated' => $contactCreated,
1005 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
1007 * @param \Psr\Http\Message\ResponseInterface $response
1009 public function sendResponse(\Psr\Http\Message\ResponseInterface
$response) {
1010 // use WordPress function status_header to ensure 404 response is sent
1011 status_header($response->getStatusCode());
1012 foreach ($response->getHeaders() as $name => $values) {
1013 CRM_Utils_System
::setHttpHeader($name, implode(', ', (array) $values));
1015 echo $response->getBody();
1016 CRM_Utils_System
::civiExit();