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
{
42 public function __construct() {
44 * 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
45 * functions and leave the codebase oblivious to the type of CMS
49 $this->is_drupal
= FALSE;
50 $this->is_wordpress
= TRUE;
56 public function setTitle($title, $pageTitle = NULL) {
61 // FIXME: Why is this global?
62 global $civicrm_wp_title;
63 $civicrm_wp_title = $title;
65 // yes, set page title, depending on context
66 $context = civi_wp()->civicrm_context_get();
70 $template = CRM_Core_Smarty
::singleton();
71 $template->assign('pageTitle', $pageTitle);
76 * Moved from CRM_Utils_System_Base
78 public function getDefaultFileStorage() {
79 $config = CRM_Core_Config
::singleton();
80 $cmsUrl = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
81 $cmsPath = $this->cmsRootPath();
82 $filesPath = CRM_Utils_File
::baseFilePath();
83 $filesRelPath = CRM_Utils_File
::relativize($filesPath, $cmsPath);
84 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
86 'url' => CRM_Utils_File
::addTrailingSlash($filesURL, '/'),
87 'path' => CRM_Utils_File
::addTrailingSlash($filesPath),
92 * Determine the location of the CiviCRM source tree.
95 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
96 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
98 public function getCiviSourceStorage() {
101 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
102 // More generally, we shouldn't be using $config here.
103 if (!defined('CIVICRM_UF_BASEURL')) {
104 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
107 $cmsPath = $this->cmsRootPath();
109 // $config = CRM_Core_Config::singleton();
110 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
111 $cmsUrl = CIVICRM_UF_BASEURL
;
112 if (CRM_Utils_System
::isSSL()) {
113 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
115 $civiRelPath = CRM_Utils_File
::relativize(realpath($civicrm_root), realpath($cmsPath));
116 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
118 'url' => CRM_Utils_File
::addTrailingSlash($civiUrl, '/'),
119 'path' => CRM_Utils_File
::addTrailingSlash($civicrm_root),
126 public function appendBreadCrumb($breadCrumbs) {
127 $breadCrumb = wp_get_breadcrumb();
129 if (is_array($breadCrumbs)) {
130 foreach ($breadCrumbs as $crumbs) {
131 if (stripos($crumbs['url'], 'id%%')) {
132 $args = array('cid', 'mid');
133 foreach ($args as $a) {
134 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
138 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
142 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
146 $template = CRM_Core_Smarty
::singleton();
147 $template->assign_by_ref('breadcrumb', $breadCrumb);
148 wp_set_breadcrumb($breadCrumb);
154 public function resetBreadCrumb() {
156 wp_set_breadcrumb($bc);
162 public function addHTMLHead($head) {
163 static $registered = FALSE;
166 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
168 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
170 CRM_Core_Region
::instance('wp_head')->add(array(
176 * WP action callback.
178 public static function _showHTMLHead() {
179 $region = CRM_Core_Region
::instance('wp_head', FALSE);
181 echo $region->render('');
188 public function mapConfigToSSL() {
190 $base_url = str_replace('http://', 'https://', $base_url);
202 $forceBackend = FALSE
204 $config = CRM_Core_Config
::singleton();
208 $fragment = isset($fragment) ?
('#' . $fragment) : '';
210 $path = CRM_Utils_String
::stripPathChars($path);
213 //this means wp function we are trying to use is not available,
215 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
216 if (!function_exists('get_option')) {
217 $this->loadBootStrap();
220 if ($config->userFrameworkFrontend
) {
222 if (get_option('permalink_structure') != '') {
223 $script = get_permalink($post->ID
);
225 if ($config->wpBasePage
== $post->post_name
) {
228 // when shortcode is included in page
229 // also make sure we have valid query object
230 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
232 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
233 if (get_query_var('page_id')) {
234 $wpPageParam = "page_id=" . get_query_var('page_id');
236 elseif (get_query_var('p')) {
237 // when shortcode is inserted in post
238 $wpPageParam = "p=" . get_query_var('p');
243 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
245 if (!isset($path) && !isset($query)) {
246 // FIXME: This short-circuited codepath is the same as the general one below, except
247 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
248 // why it's different (and I can only find two obvious use-cases for this codepath,
249 // of which at least one looks gratuitous). A more ambitious person would simply remove
251 return $base . $fragment;
254 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
258 $queryParts = array();
261 // not using clean URLs
263 // requesting an admin URL
264 ||
((is_admin() && !$frontend) ||
$forceBackend)
266 ||
(!$basepage && $script != '')
269 // pre-existing logic
271 $queryParts[] = 'page=CiviCRM';
272 // Encode all but the *path* placeholder
273 if ($path !== '*path*') {
274 $path = rawurlencode($path);
276 $queryParts[] = "q={$path}";
279 $queryParts[] = $wpPageParam;
281 if (!empty($query)) {
282 $queryParts[] = $query;
285 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
292 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
295 $query = ltrim($query, '=?&');
296 $queryParts[] = $query;
299 if (!empty($queryParts)) {
300 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
303 $final = $base . $fragment;
313 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
314 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
315 * For now leave hard coded wp-admin references.
316 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
320 * @param $forceBackend
322 * @return mixed|null|string
324 private function getBaseUrl($absolute, $frontend, $forceBackend) {
325 $config = CRM_Core_Config
::singleton();
326 if ((is_admin() && !$frontend) ||
$forceBackend) {
327 return Civi
::paths()->getUrl('[wp.backend]/.', $absolute ?
'absolute' : 'relative');
330 return Civi
::paths()->getUrl('[wp.frontend]/.', $absolute ?
'absolute' : 'relative');
337 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
338 $config = CRM_Core_Config
::singleton();
340 if ($loadCMSBootstrap) {
341 $config->userSystem
->loadBootStrap([
347 $user = wp_authenticate($name, $password);
348 if (is_a($user, 'WP_Error')) {
352 // TODO: need to change this to make sure we matched only one row
354 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
355 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
359 return array($contactID, $user->data
->ID
, mt_rand());
363 * FIXME: Do something
365 * @param string $message
367 public function setMessage($message) {
371 * @param \string $user
375 public function loadUser($user) {
376 $userdata = get_user_by('login', $user);
377 if (!$userdata->data
->ID
) {
381 $uid = $userdata->data
->ID
;
382 wp_set_current_user($uid);
383 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
385 // lets store contact id and user id in session
386 $session = CRM_Core_Session
::singleton();
387 $session->set('ufID', $uid);
388 $session->set('userID', $contactID);
393 * FIXME: Use CMS-native approach
395 public function permissionDenied() {
396 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
400 * Determine the native ID of the CMS user.
402 * @param string $username
405 public function getUfId($username) {
406 $userdata = get_user_by('login', $username);
407 if (!$userdata->data
->ID
) {
410 return $userdata->data
->ID
;
416 public function logout() {
422 wp_redirect(wp_login_url());
428 public function getUFLocale() {
430 if (function_exists('pll_current_language')) {
431 $language = pll_current_language();
434 elseif (defined('ICL_LANGUAGE_CODE')) {
435 $language = ICL_LANGUAGE_CODE
;
438 // TODO: set language variable for others WordPress plugin
440 if (!empty($language)) {
441 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
451 public function setUFLocale($civicrm_language) {
452 // TODO (probably not possible with WPML?)
457 * Load wordpress bootstrap.
459 * @param array $params
460 * Optional credentials
461 * - name: string, cms username
462 * - pass: string, cms password
466 public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
467 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
469 $name = CRM_Utils_Array
::value('name', $params);
470 $pass = CRM_Utils_Array
::value('pass', $params);
471 if (isset($params['uid'])) {
472 throw new \
RuntimeException("Not implemented WordPress::loadBootStrap([uid=>\$num]))");
475 if (!defined('WP_USE_THEMES')) {
476 define('WP_USE_THEMES', FALSE);
479 $cmsRootPath = $this->cmsRootPath();
481 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
483 $path = Civi
::settings()->get('wpLoadPhp');
487 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
488 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
491 CRM_Core_Error
::fatal("Could not find the bootstrap file for WordPress");
493 $wpUserTimezone = get_option('timezone_string');
494 if ($wpUserTimezone) {
495 date_default_timezone_set($wpUserTimezone);
496 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
498 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
499 $uid = CRM_Utils_Array
::value('uid', $name);
501 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
502 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
504 $uid = wp_authenticate($name, $pass);
507 echo '<br />Sorry, unrecognized username or password.';
515 if ($uid instanceof WP_User
) {
516 $account = wp_set_current_user($uid->ID
);
519 $account = wp_set_current_user($uid);
521 if ($account && $account->data
->ID
) {
535 public function validInstallDir($dir) {
536 $includePath = "$dir/wp-includes";
537 if (@file_exists
("$includePath/version.php")) {
544 * Determine the location of the CMS root.
546 * @return string|NULL
547 * local file system path to CMS root, or NULL if it cannot be determined
549 public function cmsRootPath() {
550 global $civicrm_paths;
551 if (!empty($civicrm_paths['cms.root']['path'])) {
552 return $civicrm_paths['cms.root']['path'];
555 $cmsRoot = $valid = NULL;
556 if (defined('CIVICRM_CMSDIR')) {
557 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
558 $cmsRoot = CIVICRM_CMSDIR
;
563 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
565 //might be windows installation.
566 $firstVar = array_shift($pathVars);
568 $cmsRoot = $firstVar;
571 //start w/ csm dir search.
572 foreach ($pathVars as $var) {
574 if ($this->validInstallDir($cmsRoot)) {
575 //stop as we found bootstrap.
582 return ($valid) ?
$cmsRoot : NULL;
588 public function createUser(&$params, $mail) {
591 'user_pass' => $params['cms_pass'],
592 'user_login' => $params['cms_name'],
593 'user_email' => $params[$mail],
594 'nickname' => $params['cms_name'],
595 'role' => get_option('default_role'),
597 if (isset($params['contactID'])) {
598 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
599 if ($contactType == 'Individual') {
600 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
601 $params['contactID'], 'first_name'
603 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
604 $params['contactID'], 'last_name'
609 $uid = wp_insert_user($user_data);
612 $creds['user_login'] = $params['cms_name'];
613 $creds['user_password'] = $params['cms_pass'];
614 $creds['remember'] = TRUE;
615 $user = wp_signon($creds, FALSE);
617 wp_new_user_notification($uid, $user_data['user_pass']);
624 public function updateCMSName($ufID, $ufName) {
626 if (function_exists('wp_update_user')) {
627 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
628 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
630 $values = array('ID' => $ufID, 'user_email' => $ufName);
632 wp_update_user($values);
638 * @param array $params
640 * @param string $emailName
642 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
643 $config = CRM_Core_Config
::singleton();
645 $dao = new CRM_Core_DAO();
646 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
647 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
649 if (!empty($params['name'])) {
650 if (!validate_username($params['name'])) {
651 $errors['cms_name'] = ts("Your username contains invalid characters");
653 elseif (username_exists(sanitize_user($params['name']))) {
654 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
658 if (!empty($params['mail'])) {
659 if (!is_email($params['mail'])) {
660 $errors[$emailName] = "Your email is invaid";
662 elseif (email_exists($params['mail'])) {
663 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
664 array(1 => $params['mail'], 2 => wp_lostpassword_url())
673 public function isUserLoggedIn() {
675 if (function_exists('is_user_logged_in')) {
676 $isloggedIn = is_user_logged_in();
685 public function isUserRegistrationPermitted() {
686 if (!get_option('users_can_register')) {
695 public function isPasswordUserGenerated() {
702 public function getLoggedInUserObject() {
703 if (function_exists('is_user_logged_in') &&
706 global $current_user;
708 return $current_user;
714 public function getLoggedInUfID() {
716 $current_user = $this->getLoggedInUserObject();
717 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
723 public function getLoggedInUniqueIdentifier() {
724 $user = $this->getLoggedInUserObject();
725 return $this->getUniqueIdentifierFromUserObject($user);
729 * Get User ID from UserFramework system (Joomla)
730 * @param object $user
731 * Object as described by the CMS.
735 public function getUserIDFromUserObject($user) {
736 return !empty($user->ID
) ?
$user->ID
: NULL;
742 public function getUniqueIdentifierFromUserObject($user) {
743 return empty($user->user_email
) ?
NULL : $user->user_email
;
749 public function getLoginURL($destination = '') {
750 $config = CRM_Core_Config
::singleton();
751 $loginURL = wp_login_url();
756 * FIXME: Do something.
758 * @param \CRM_Core_Form $form
760 * @return NULL|string
762 public function getLoginDestination(&$form) {
769 public function getVersion() {
770 if (function_exists('get_bloginfo')) {
771 return get_bloginfo('version', 'display');
781 public function getTimeZoneString() {
782 return get_option('timezone_string');
788 public function getUserRecordUrl($contactID) {
789 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
790 if (CRM_Core_Session
::singleton()
791 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))
793 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
798 * Append WP js to coreResourcesList.
802 public function appendCoreResources(&$list) {
803 $list[] = 'js/crm.wordpress.js';
809 public function synchronizeUsers() {
810 $config = CRM_Core_Config
::singleton();
811 if (PHP_SAPI
!= 'cli') {
815 $mail = 'user_email';
817 $uf = $config->userFramework
;
820 $contactMatching = 0;
823 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
825 foreach ($wpUserIds as $wpUserId) {
826 $wpUserData = get_userdata($wpUserId);
828 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
842 if (is_object($match)) {
848 'contactCount' => $contactCount,
849 'contactMatching' => $contactMatching,
850 'contactCreated' => $contactCreated,