3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
37 * WordPress specific stuff goes here
39 class CRM_Utils_System_WordPress
extends CRM_Utils_System_Base
{
43 public function __construct() {
45 * 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
46 * functions and leave the codebase oblivious to the type of CMS
50 $this->is_drupal
= FALSE;
51 $this->is_wordpress
= TRUE;
57 public function setTitle($title, $pageTitle = NULL) {
62 // FIXME: Why is this global?
63 global $civicrm_wp_title;
64 $civicrm_wp_title = $title;
66 // yes, set page title, depending on context
67 $context = civi_wp()->civicrm_context_get();
71 $template = CRM_Core_Smarty
::singleton();
72 $template->assign('pageTitle', $pageTitle);
77 * Moved from CRM_Utils_System_Base
79 public function getDefaultFileStorage() {
80 $config = CRM_Core_Config
::singleton();
81 $cmsUrl = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
82 $cmsPath = $this->cmsRootPath();
83 $filesPath = CRM_Utils_File
::baseFilePath();
84 $filesRelPath = CRM_Utils_File
::relativize($filesPath, $cmsPath);
85 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
87 'url' => CRM_Utils_File
::addTrailingSlash($filesURL, '/'),
88 'path' => CRM_Utils_File
::addTrailingSlash($filesPath),
93 * Determine the location of the CiviCRM source tree.
96 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
97 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
99 public function getCiviSourceStorage() {
100 global $civicrm_root;
102 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
103 // More generally, we shouldn't be using $config here.
104 if (!defined('CIVICRM_UF_BASEURL')) {
105 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
108 $cmsPath = $this->cmsRootPath();
110 // $config = CRM_Core_Config::singleton();
111 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
112 $cmsUrl = CIVICRM_UF_BASEURL
;
113 if (CRM_Utils_System
::isSSL()) {
114 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
116 $civiRelPath = CRM_Utils_File
::relativize(realpath($civicrm_root), realpath($cmsPath));
117 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
119 'url' => CRM_Utils_File
::addTrailingSlash($civiUrl, '/'),
120 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
127 public function appendBreadCrumb($breadCrumbs) {
128 $breadCrumb = wp_get_breadcrumb();
130 if (is_array($breadCrumbs)) {
131 foreach ($breadCrumbs as $crumbs) {
132 if (stripos($crumbs['url'], 'id%%')) {
133 $args = ['cid', 'mid'];
134 foreach ($args as $a) {
135 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
139 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
143 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
147 $template = CRM_Core_Smarty
::singleton();
148 $template->assign_by_ref('breadcrumb', $breadCrumb);
149 wp_set_breadcrumb($breadCrumb);
155 public function resetBreadCrumb() {
157 wp_set_breadcrumb($bc);
163 public function addHTMLHead($head) {
164 static $registered = FALSE;
167 add_action('wp_head', [__CLASS__
, '_showHTMLHead']);
169 add_action('admin_head', [__CLASS__
, '_showHTMLHead']);
171 CRM_Core_Region
::instance('wp_head')->add([
177 * WP action callback.
179 public static function _showHTMLHead() {
180 $region = CRM_Core_Region
::instance('wp_head', FALSE);
182 echo $region->render('');
189 public function mapConfigToSSL() {
191 $base_url = str_replace('http://', 'https://', $base_url);
203 $forceBackend = FALSE
205 $config = CRM_Core_Config
::singleton();
209 $fragment = isset($fragment) ?
('#' . $fragment) : '';
211 $path = CRM_Utils_String
::stripPathChars($path);
214 //this means wp function we are trying to use is not available,
216 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
217 if (!function_exists('get_option')) {
218 $this->loadBootStrap();
221 if ($config->userFrameworkFrontend
) {
223 if (get_option('permalink_structure') != '') {
224 $script = get_permalink($post->ID
);
226 if ($config->wpBasePage
== $post->post_name
) {
229 // when shortcode is included in page
230 // also make sure we have valid query object
231 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
233 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
234 if (get_query_var('page_id')) {
235 $wpPageParam = "page_id=" . get_query_var('page_id');
237 elseif (get_query_var('p')) {
238 // when shortcode is inserted in post
239 $wpPageParam = "p=" . get_query_var('p');
244 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
246 if (!isset($path) && !isset($query)) {
247 // FIXME: This short-circuited codepath is the same as the general one below, except
248 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
249 // why it's different (and I can only find two obvious use-cases for this codepath,
250 // of which at least one looks gratuitous). A more ambitious person would simply remove
252 return $base . $fragment;
255 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
262 // not using clean URLs
264 // requesting an admin URL
265 ||
((is_admin() && !$frontend) ||
$forceBackend)
267 ||
(!$basepage && $script != '')
270 // pre-existing logic
272 $queryParts[] = 'page=CiviCRM';
273 // Encode all but the *path* placeholder
274 if ($path !== '*path*') {
275 $path = rawurlencode($path);
277 $queryParts[] = "q={$path}";
280 $queryParts[] = $wpPageParam;
282 if (!empty($query)) {
283 $queryParts[] = $query;
286 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
293 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
296 $query = ltrim($query, '=?&');
297 $queryParts[] = $query;
300 if (!empty($queryParts)) {
301 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
304 $final = $base . $fragment;
314 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
315 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
316 * For now leave hard coded wp-admin references.
317 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
321 * @param $forceBackend
323 * @return mixed|null|string
325 private function getBaseUrl($absolute, $frontend, $forceBackend) {
326 $config = CRM_Core_Config
::singleton();
327 if ((is_admin() && !$frontend) ||
$forceBackend) {
328 return Civi
::paths()->getUrl('[wp.backend]/.', $absolute ?
'absolute' : 'relative');
331 return Civi
::paths()->getUrl('[wp.frontend]/.', $absolute ?
'absolute' : 'relative');
338 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
339 $config = CRM_Core_Config
::singleton();
341 if ($loadCMSBootstrap) {
342 $config->userSystem
->loadBootStrap([
348 $user = wp_authenticate($name, $password);
349 if (is_a($user, 'WP_Error')) {
353 // TODO: need to change this to make sure we matched only one row
355 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
356 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
360 return [$contactID, $user->data
->ID
, mt_rand()];
364 * FIXME: Do something
366 * @param string $message
368 public function setMessage($message) {
372 * @param \string $user
376 public function loadUser($user) {
377 $userdata = get_user_by('login', $user);
378 if (!$userdata->data
->ID
) {
382 $uid = $userdata->data
->ID
;
383 wp_set_current_user($uid);
384 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
386 // lets store contact id and user id in session
387 $session = CRM_Core_Session
::singleton();
388 $session->set('ufID', $uid);
389 $session->set('userID', $contactID);
394 * FIXME: Use CMS-native approach
396 public function permissionDenied() {
397 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
401 * Determine the native ID of the CMS user.
403 * @param string $username
406 public function getUfId($username) {
407 $userdata = get_user_by('login', $username);
408 if (!$userdata->data
->ID
) {
411 return $userdata->data
->ID
;
417 public function logout() {
423 wp_redirect(wp_login_url());
429 public function getUFLocale() {
431 if (function_exists('pll_current_language')) {
432 $language = pll_current_language();
435 elseif (defined('ICL_LANGUAGE_CODE')) {
436 $language = ICL_LANGUAGE_CODE
;
439 // TODO: set language variable for others WordPress plugin
441 if (!empty($language)) {
442 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
452 public function setUFLocale($civicrm_language) {
453 // TODO (probably not possible with WPML?)
458 * Load wordpress bootstrap.
460 * @param array $params
461 * Optional credentials
462 * - name: string, cms username
463 * - pass: string, cms password
464 * @param bool $loadUser
465 * @param bool $throwError
466 * @param mixed $realPath
470 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
471 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
473 $name = CRM_Utils_Array
::value('name', $params);
474 $pass = CRM_Utils_Array
::value('pass', $params);
475 if (isset($params['uid'])) {
476 throw new \
RuntimeException("Not implemented WordPress::loadBootStrap([uid=>\$num]))");
479 if (!defined('WP_USE_THEMES')) {
480 define('WP_USE_THEMES', FALSE);
483 $cmsRootPath = $this->cmsRootPath();
485 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
487 $path = Civi
::settings()->get('wpLoadPhp');
491 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
492 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
495 CRM_Core_Error
::fatal("Could not find the bootstrap file for WordPress");
497 $wpUserTimezone = get_option('timezone_string');
498 if ($wpUserTimezone) {
499 date_default_timezone_set($wpUserTimezone);
500 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
502 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
503 $uid = CRM_Utils_Array
::value('uid', $name);
505 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
506 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
508 $uid = wp_authenticate($name, $pass);
511 echo '<br />Sorry, unrecognized username or password.';
519 if ($uid instanceof WP_User
) {
520 $account = wp_set_current_user($uid->ID
);
523 $account = wp_set_current_user($uid);
525 if ($account && $account->data
->ID
) {
539 public function validInstallDir($dir) {
540 $includePath = "$dir/wp-includes";
541 if (@file_exists
("$includePath/version.php")) {
548 * Determine the location of the CMS root.
550 * @return string|NULL
551 * local file system path to CMS root, or NULL if it cannot be determined
553 public function cmsRootPath() {
554 global $civicrm_paths;
555 if (!empty($civicrm_paths['cms.root']['path'])) {
556 return $civicrm_paths['cms.root']['path'];
559 $cmsRoot = $valid = NULL;
560 if (defined('CIVICRM_CMSDIR')) {
561 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
562 $cmsRoot = CIVICRM_CMSDIR
;
567 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
569 //might be windows installation.
570 $firstVar = array_shift($pathVars);
572 $cmsRoot = $firstVar;
575 //start w/ csm dir search.
576 foreach ($pathVars as $var) {
578 if ($this->validInstallDir($cmsRoot)) {
579 //stop as we found bootstrap.
586 return ($valid) ?
$cmsRoot : NULL;
592 public function createUser(&$params, $mail) {
595 'user_pass' => $params['cms_pass'],
596 'user_login' => $params['cms_name'],
597 'user_email' => $params[$mail],
598 'nickname' => $params['cms_name'],
599 'role' => get_option('default_role'),
601 if (isset($params['contactID'])) {
602 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
603 if ($contactType == 'Individual') {
604 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
605 $params['contactID'], 'first_name'
607 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
608 $params['contactID'], 'last_name'
613 $uid = wp_insert_user($user_data);
616 $creds['user_login'] = $params['cms_name'];
617 $creds['user_password'] = $params['cms_pass'];
618 $creds['remember'] = TRUE;
619 $user = wp_signon($creds, FALSE);
621 wp_new_user_notification($uid, $user_data['user_pass']);
628 public function updateCMSName($ufID, $ufName) {
630 if (function_exists('wp_update_user')) {
631 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
632 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
634 $values = ['ID' => $ufID, 'user_email' => $ufName];
636 wp_update_user($values);
642 * @param array $params
644 * @param string $emailName
646 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
647 $config = CRM_Core_Config
::singleton();
649 $dao = new CRM_Core_DAO();
650 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
651 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
653 if (!empty($params['name'])) {
654 if (!validate_username($params['name'])) {
655 $errors['cms_name'] = ts("Your username contains invalid characters");
657 elseif (username_exists(sanitize_user($params['name']))) {
658 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
662 if (!empty($params['mail'])) {
663 if (!is_email($params['mail'])) {
664 $errors[$emailName] = "Your email is invaid";
666 elseif (email_exists($params['mail'])) {
667 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
668 [1 => $params['mail'], 2 => wp_lostpassword_url()]
677 public function isUserLoggedIn() {
679 if (function_exists('is_user_logged_in')) {
680 $isloggedIn = is_user_logged_in();
689 public function isUserRegistrationPermitted() {
690 if (!get_option('users_can_register')) {
699 public function isPasswordUserGenerated() {
706 public function getLoggedInUserObject() {
707 if (function_exists('is_user_logged_in') &&
710 global $current_user;
712 return $current_user;
718 public function getLoggedInUfID() {
720 $current_user = $this->getLoggedInUserObject();
721 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
727 public function getLoggedInUniqueIdentifier() {
728 $user = $this->getLoggedInUserObject();
729 return $this->getUniqueIdentifierFromUserObject($user);
733 * Get User ID from UserFramework system (Joomla)
734 * @param object $user
735 * Object as described by the CMS.
739 public function getUserIDFromUserObject($user) {
740 return !empty($user->ID
) ?
$user->ID
: NULL;
746 public function getUniqueIdentifierFromUserObject($user) {
747 return empty($user->user_email
) ?
NULL : $user->user_email
;
753 public function getLoginURL($destination = '') {
754 $config = CRM_Core_Config
::singleton();
755 $loginURL = wp_login_url();
760 * FIXME: Do something.
762 * @param \CRM_Core_Form $form
764 * @return NULL|string
766 public function getLoginDestination(&$form) {
773 public function getVersion() {
774 if (function_exists('get_bloginfo')) {
775 return get_bloginfo('version', 'display');
785 public function getTimeZoneString() {
786 return get_option('timezone_string');
792 public function getUserRecordUrl($contactID) {
793 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
794 if (CRM_Core_Session
::singleton()
795 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(['cms:administer users'])
797 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
802 * Append WP js to coreResourcesList.
804 * @param \Civi\Core\Event\GenericHookEvent $e
806 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent
$e) {
807 $e->list[] = 'js/crm.wordpress.js';
813 public function synchronizeUsers() {
814 $config = CRM_Core_Config
::singleton();
815 if (PHP_SAPI
!= 'cli') {
819 $mail = 'user_email';
821 $uf = $config->userFramework
;
824 $contactMatching = 0;
827 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
829 foreach ($wpUserIds as $wpUserId) {
830 $wpUserData = get_userdata($wpUserId);
832 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
846 if (is_object($match)) {
852 'contactCount' => $contactCount,
853 'contactMatching' => $contactMatching,
854 'contactCreated' => $contactCreated,