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;
41 public function setTitle($title, $pageTitle = NULL) {
46 // FIXME: Why is this global?
47 global $civicrm_wp_title;
48 $civicrm_wp_title = $title;
50 // yes, set page title, depending on context
51 $context = civi_wp()->civicrm_context_get();
55 $template = CRM_Core_Smarty
::singleton();
56 $template->assign('pageTitle', $pageTitle);
61 * Moved from CRM_Utils_System_Base
63 public function getDefaultFileStorage() {
64 $config = CRM_Core_Config
::singleton();
65 $cmsUrl = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
66 $cmsPath = $this->cmsRootPath();
67 $filesPath = CRM_Utils_File
::baseFilePath();
68 $filesRelPath = CRM_Utils_File
::relativize($filesPath, $cmsPath);
69 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
71 'url' => CRM_Utils_File
::addTrailingSlash($filesURL, '/'),
72 'path' => CRM_Utils_File
::addTrailingSlash($filesPath),
77 * Determine the location of the CiviCRM source tree.
80 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
81 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
83 public function getCiviSourceStorage() {
86 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
87 // More generally, we shouldn't be using $config here.
88 if (!defined('CIVICRM_UF_BASEURL')) {
89 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
92 $cmsPath = $this->cmsRootPath();
94 // $config = CRM_Core_Config::singleton();
95 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
96 $cmsUrl = CIVICRM_UF_BASEURL
;
97 if (CRM_Utils_System
::isSSL()) {
98 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
100 $civiRelPath = CRM_Utils_File
::relativize(realpath($civicrm_root), realpath($cmsPath));
101 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
103 'url' => CRM_Utils_File
::addTrailingSlash($civiUrl, '/'),
104 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
111 public function appendBreadCrumb($breadCrumbs) {
112 $breadCrumb = wp_get_breadcrumb();
114 if (is_array($breadCrumbs)) {
115 foreach ($breadCrumbs as $crumbs) {
116 if (stripos($crumbs['url'], 'id%%')) {
117 $args = ['cid', 'mid'];
118 foreach ($args as $a) {
119 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
123 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
127 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
131 $template = CRM_Core_Smarty
::singleton();
132 $template->assign_by_ref('breadcrumb', $breadCrumb);
133 wp_set_breadcrumb($breadCrumb);
139 public function resetBreadCrumb() {
141 wp_set_breadcrumb($bc);
147 public function addHTMLHead($head) {
148 static $registered = FALSE;
151 add_action('wp_head', [__CLASS__
, '_showHTMLHead']);
153 add_action('admin_head', [__CLASS__
, '_showHTMLHead']);
155 CRM_Core_Region
::instance('wp_head')->add([
161 * WP action callback.
163 public static function _showHTMLHead() {
164 $region = CRM_Core_Region
::instance('wp_head', FALSE);
166 echo $region->render('');
173 public function mapConfigToSSL() {
175 $base_url = str_replace('http://', 'https://', $base_url);
187 $forceBackend = FALSE
189 $config = CRM_Core_Config
::singleton();
193 $fragment = isset($fragment) ?
('#' . $fragment) : '';
195 $path = CRM_Utils_String
::stripPathChars($path);
198 //this means wp function we are trying to use is not available,
200 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
201 if (!function_exists('get_option')) {
202 $this->loadBootStrap();
205 if ($config->userFrameworkFrontend
) {
207 if (get_option('permalink_structure') != '') {
208 $script = get_permalink($post->ID
);
210 if ($config->wpBasePage
== $post->post_name
) {
213 // when shortcode is included in page
214 // also make sure we have valid query object
215 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
217 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
218 if (get_query_var('page_id')) {
219 $wpPageParam = "page_id=" . get_query_var('page_id');
221 elseif (get_query_var('p')) {
222 // when shortcode is inserted in post
223 $wpPageParam = "p=" . get_query_var('p');
228 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
230 if (!isset($path) && !isset($query)) {
231 // FIXME: This short-circuited codepath is the same as the general one below, except
232 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
233 // why it's different (and I can only find two obvious use-cases for this codepath,
234 // of which at least one looks gratuitous). A more ambitious person would simply remove
236 return $base . $fragment;
239 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
246 // not using clean URLs
248 // requesting an admin URL
249 ||
((is_admin() && !$frontend) ||
$forceBackend)
251 ||
(!$basepage && $script != '')
254 // pre-existing logic
256 $queryParts[] = 'page=CiviCRM';
257 $queryParts[] = 'q=' . rawurlencode($path);
260 $queryParts[] = $wpPageParam;
262 if (!empty($query)) {
263 $queryParts[] = $query;
266 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
273 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
276 $query = ltrim($query, '=?&');
277 $queryParts[] = $query;
280 if (!empty($queryParts)) {
281 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
284 $final = $base . $fragment;
294 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
295 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
296 * For now leave hard coded wp-admin references.
297 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
301 * @param $forceBackend
303 * @return mixed|null|string
305 private function getBaseUrl($absolute, $frontend, $forceBackend) {
306 $config = CRM_Core_Config
::singleton();
307 if ((is_admin() && !$frontend) ||
$forceBackend) {
308 return Civi
::paths()->getUrl('[wp.backend]/.', $absolute ?
'absolute' : 'relative');
311 return Civi
::paths()->getUrl('[wp.frontend]/.', $absolute ?
'absolute' : 'relative');
318 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
319 $config = CRM_Core_Config
::singleton();
321 if ($loadCMSBootstrap) {
322 $config->userSystem
->loadBootStrap([
328 $user = wp_authenticate($name, $password);
329 if (is_a($user, 'WP_Error')) {
333 // TODO: need to change this to make sure we matched only one row
335 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
336 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
340 return [$contactID, $user->data
->ID
, mt_rand()];
344 * FIXME: Do something
346 * @param string $message
348 public function setMessage($message) {
352 * @param \string $user
356 public function loadUser($user) {
357 $userdata = get_user_by('login', $user);
358 if (!$userdata->data
->ID
) {
362 $uid = $userdata->data
->ID
;
363 wp_set_current_user($uid);
364 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
366 // lets store contact id and user id in session
367 $session = CRM_Core_Session
::singleton();
368 $session->set('ufID', $uid);
369 $session->set('userID', $contactID);
374 * FIXME: Use CMS-native approach
375 * @throws \CRM_Core_Exception
377 public function permissionDenied() {
378 throw new CRM_Core_Exception(ts('You do not have permission to access this page.'));
382 * Determine the native ID of the CMS user.
384 * @param string $username
388 public function getUfId($username) {
389 $userdata = get_user_by('login', $username);
390 if (!$userdata->data
->ID
) {
393 return $userdata->data
->ID
;
399 public function logout() {
405 wp_redirect(wp_login_url());
411 public function getUFLocale() {
413 if (function_exists('pll_current_language')) {
414 $language = pll_current_language();
417 elseif (defined('ICL_LANGUAGE_CODE')) {
418 $language = ICL_LANGUAGE_CODE
;
421 // TODO: set language variable for others WordPress plugin
423 if (!empty($language)) {
424 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
434 public function setUFLocale($civicrm_language) {
435 // TODO (probably not possible with WPML?)
440 * Load wordpress bootstrap.
442 * @param array $params
443 * Optional credentials
444 * - name: string, cms username
445 * - pass: string, cms password
446 * @param bool $loadUser
447 * @param bool $throwError
448 * @param mixed $realPath
451 * @throws \CRM_Core_Exception
453 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
454 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
456 $name = CRM_Utils_Array
::value('name', $params);
457 $pass = CRM_Utils_Array
::value('pass', $params);
459 if (!defined('WP_USE_THEMES')) {
460 define('WP_USE_THEMES', FALSE);
463 $cmsRootPath = $this->cmsRootPath();
465 throw new CRM_Core_Exception("Could not find the install directory for WordPress");
467 $path = Civi
::settings()->get('wpLoadPhp');
471 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
472 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
475 throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress");
477 $wpUserTimezone = get_option('timezone_string');
478 if ($wpUserTimezone) {
479 date_default_timezone_set($wpUserTimezone);
480 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
482 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
483 $uid = CRM_Utils_Array
::value('uid', $params);
485 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
486 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
488 $uid = wp_authenticate($name, $pass);
491 echo '<br />Sorry, unrecognized username or password.';
499 if ($uid instanceof WP_User
) {
500 $account = wp_set_current_user($uid->ID
);
503 $account = wp_set_current_user($uid);
505 if ($account && $account->data
->ID
) {
519 public function validInstallDir($dir) {
520 $includePath = "$dir/wp-includes";
521 if (@file_exists
("$includePath/version.php")) {
528 * Determine the location of the CMS root.
530 * @return string|NULL
531 * local file system path to CMS root, or NULL if it cannot be determined
533 public function cmsRootPath() {
534 global $civicrm_paths;
535 if (!empty($civicrm_paths['cms.root']['path'])) {
536 return $civicrm_paths['cms.root']['path'];
539 $cmsRoot = $valid = NULL;
540 if (defined('CIVICRM_CMSDIR')) {
541 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
542 $cmsRoot = CIVICRM_CMSDIR
;
547 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
549 //might be windows installation.
550 $firstVar = array_shift($pathVars);
552 $cmsRoot = $firstVar;
555 //start w/ csm dir search.
556 foreach ($pathVars as $var) {
558 if ($this->validInstallDir($cmsRoot)) {
559 //stop as we found bootstrap.
566 return ($valid) ?
$cmsRoot : NULL;
572 public function createUser(&$params, $mail) {
575 'user_pass' => $params['cms_pass'],
576 'user_login' => $params['cms_name'],
577 'user_email' => $params[$mail],
578 'nickname' => $params['cms_name'],
579 'role' => get_option('default_role'),
581 if (isset($params['contactID'])) {
582 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
583 if ($contactType == 'Individual') {
584 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
585 $params['contactID'], 'first_name'
587 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
588 $params['contactID'], 'last_name'
593 $uid = wp_insert_user($user_data);
596 $creds['user_login'] = $params['cms_name'];
597 $creds['user_password'] = $params['cms_pass'];
598 $creds['remember'] = TRUE;
599 $user = wp_signon($creds, FALSE);
601 wp_new_user_notification($uid, $user_data['user_pass']);
608 public function updateCMSName($ufID, $ufName) {
610 if (function_exists('wp_update_user')) {
611 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
612 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
614 $values = ['ID' => $ufID, 'user_email' => $ufName];
616 wp_update_user($values);
622 * @param array $params
624 * @param string $emailName
626 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
627 $config = CRM_Core_Config
::singleton();
629 $dao = new CRM_Core_DAO();
630 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
631 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
633 if (!empty($params['name'])) {
634 if (!validate_username($params['name'])) {
635 $errors['cms_name'] = ts("Your username contains invalid characters");
637 elseif (username_exists(sanitize_user($params['name']))) {
638 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
642 if (!empty($params['mail'])) {
643 if (!is_email($params['mail'])) {
644 $errors[$emailName] = "Your email is invaid";
646 elseif (email_exists($params['mail'])) {
647 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
648 [1 => $params['mail'], 2 => wp_lostpassword_url()]
657 public function isUserLoggedIn() {
659 if (function_exists('is_user_logged_in')) {
660 $isloggedIn = is_user_logged_in();
669 public function isUserRegistrationPermitted() {
670 if (!get_option('users_can_register')) {
679 public function isPasswordUserGenerated() {
686 public function getLoggedInUserObject() {
687 if (function_exists('is_user_logged_in') &&
690 global $current_user;
692 return $current_user;
698 public function getLoggedInUfID() {
700 $current_user = $this->getLoggedInUserObject();
701 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
707 public function getLoggedInUniqueIdentifier() {
708 $user = $this->getLoggedInUserObject();
709 return $this->getUniqueIdentifierFromUserObject($user);
713 * Get User ID from UserFramework system (Joomla)
714 * @param object $user
715 * Object as described by the CMS.
719 public function getUserIDFromUserObject($user) {
720 return !empty($user->ID
) ?
$user->ID
: NULL;
726 public function getUniqueIdentifierFromUserObject($user) {
727 return empty($user->user_email
) ?
NULL : $user->user_email
;
733 public function getLoginURL($destination = '') {
734 $config = CRM_Core_Config
::singleton();
735 $loginURL = wp_login_url();
740 * FIXME: Do something.
742 * @param \CRM_Core_Form $form
744 * @return NULL|string
746 public function getLoginDestination(&$form) {
753 public function getVersion() {
754 if (function_exists('get_bloginfo')) {
755 return get_bloginfo('version', 'display');
765 public function getTimeZoneString() {
766 return get_option('timezone_string');
772 public function getUserRecordUrl($contactID) {
773 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
774 if (CRM_Core_Session
::singleton()
775 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(['cms:administer users'])
777 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
782 * Append WP js to coreResourcesList.
784 * @param \Civi\Core\Event\GenericHookEvent $e
786 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
787 $e->list[] = 'js/crm.wordpress.js';
793 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent
$e) {
794 // Set menubar breakpoint to match WP admin theme
795 if ($e->asset
== 'crm-menubar.css') {
796 $e->params
['breakpoint'] = 783;
803 public function synchronizeUsers() {
804 $config = CRM_Core_Config
::singleton();
805 if (PHP_SAPI
!= 'cli') {
809 $mail = 'user_email';
811 $uf = $config->userFramework
;
814 $contactMatching = 0;
817 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
819 foreach ($wpUserIds as $wpUserId) {
820 $wpUserData = get_userdata($wpUserId);
822 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
839 'contactCount' => $contactCount,
840 'contactMatching' => $contactMatching,
841 'contactCreated' => $contactCreated,
846 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
848 * @param \Psr\Http\Message\ResponseInterface $response
850 public function sendResponse(\Psr\Http\Message\ResponseInterface
$response) {
851 // use WordPress function status_header to ensure 404 response is sent
852 status_header($response->getStatusCode());
853 foreach ($response->getHeaders() as $name => $values) {
854 CRM_Utils_System
::setHttpHeader($name, implode(', ', (array) $values));
856 echo $response->getBody();
857 CRM_Utils_System
::civiExit();