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($name, $password);
344 $user = wp_authenticate($name, $password);
345 if (is_a($user, 'WP_Error')) {
349 // TODO: need to change this to make sure we matched only one row
351 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
352 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
356 return array($contactID, $user->data
->ID
, mt_rand());
360 * FIXME: Do something
362 * @param string $message
364 public function setMessage($message) {
368 * @param \string $user
372 public function loadUser($user) {
373 $userdata = get_user_by('login', $user);
374 if (!$userdata->data
->ID
) {
378 $uid = $userdata->data
->ID
;
379 wp_set_current_user($uid);
380 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
382 // lets store contact id and user id in session
383 $session = CRM_Core_Session
::singleton();
384 $session->set('ufID', $uid);
385 $session->set('userID', $contactID);
390 * FIXME: Use CMS-native approach
392 public function permissionDenied() {
393 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
397 * Determine the native ID of the CMS user.
399 * @param string $username
402 public function getUfId($username) {
403 $userdata = get_user_by('login', $username);
404 if (!$userdata->data
->ID
) {
407 return $userdata->data
->ID
;
413 public function logout() {
419 wp_redirect(wp_login_url());
425 public function getUFLocale() {
427 if (function_exists('pll_current_language')) {
428 $language = pll_current_language();
431 elseif (defined('ICL_LANGUAGE_CODE')) {
432 $language = ICL_LANGUAGE_CODE
;
435 // TODO: set language variable for others WordPress plugin
437 if (!empty($language)) {
438 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
448 public function setUFLocale($civicrm_language) {
449 // TODO (probably not possible with WPML?)
454 * Load wordpress bootstrap.
456 * @param string $name
457 * optional username for login.
458 * @param string $pass
459 * optional password for login.
463 public function loadBootStrap($name = NULL, $pass = NULL) {
464 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
466 if (!defined('WP_USE_THEMES')) {
467 define('WP_USE_THEMES', FALSE);
470 $cmsRootPath = $this->cmsRootPath();
472 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
474 $path = Civi
::settings()->get('wpLoadPhp');
478 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
479 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
482 CRM_Core_Error
::fatal("Could not find the bootstrap file for WordPress");
484 $wpUserTimezone = get_option('timezone_string');
485 if ($wpUserTimezone) {
486 date_default_timezone_set($wpUserTimezone);
487 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
489 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
490 $uid = CRM_Utils_Array
::value('uid', $name);
492 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
493 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
495 $uid = wp_authenticate($name, $pass);
498 echo '<br />Sorry, unrecognized username or password.';
506 if ($uid instanceof WP_User
) {
507 $account = wp_set_current_user($uid->ID
);
510 $account = wp_set_current_user($uid);
512 if ($account && $account->data
->ID
) {
526 public function validInstallDir($dir) {
527 $includePath = "$dir/wp-includes";
528 if (@file_exists
("$includePath/version.php")) {
535 * Determine the location of the CMS root.
537 * @return string|NULL
538 * local file system path to CMS root, or NULL if it cannot be determined
540 public function cmsRootPath() {
541 global $civicrm_paths;
542 if (!empty($civicrm_paths['cms.root']['path'])) {
543 return $civicrm_paths['cms.root']['path'];
546 $cmsRoot = $valid = NULL;
547 if (defined('CIVICRM_CMSDIR')) {
548 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
549 $cmsRoot = CIVICRM_CMSDIR
;
554 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
556 //might be windows installation.
557 $firstVar = array_shift($pathVars);
559 $cmsRoot = $firstVar;
562 //start w/ csm dir search.
563 foreach ($pathVars as $var) {
565 if ($this->validInstallDir($cmsRoot)) {
566 //stop as we found bootstrap.
573 return ($valid) ?
$cmsRoot : NULL;
579 public function createUser(&$params, $mail) {
582 'user_pass' => $params['cms_pass'],
583 'user_login' => $params['cms_name'],
584 'user_email' => $params[$mail],
585 'nickname' => $params['cms_name'],
586 'role' => get_option('default_role'),
588 if (isset($params['contactID'])) {
589 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
590 if ($contactType == 'Individual') {
591 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
592 $params['contactID'], 'first_name'
594 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
595 $params['contactID'], 'last_name'
600 $uid = wp_insert_user($user_data);
603 $creds['user_login'] = $params['cms_name'];
604 $creds['user_password'] = $params['cms_pass'];
605 $creds['remember'] = TRUE;
606 $user = wp_signon($creds, FALSE);
608 wp_new_user_notification($uid, $user_data['user_pass']);
615 public function updateCMSName($ufID, $ufName) {
617 if (function_exists('wp_update_user')) {
618 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
619 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
621 $values = array('ID' => $ufID, 'user_email' => $ufName);
623 wp_update_user($values);
629 * @param array $params
631 * @param string $emailName
633 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
634 $config = CRM_Core_Config
::singleton();
636 $dao = new CRM_Core_DAO();
637 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
638 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
640 if (!empty($params['name'])) {
641 if (!validate_username($params['name'])) {
642 $errors['cms_name'] = ts("Your username contains invalid characters");
644 elseif (username_exists(sanitize_user($params['name']))) {
645 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
649 if (!empty($params['mail'])) {
650 if (!is_email($params['mail'])) {
651 $errors[$emailName] = "Your email is invaid";
653 elseif (email_exists($params['mail'])) {
654 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
655 array(1 => $params['mail'], 2 => wp_lostpassword_url())
664 public function isUserLoggedIn() {
666 if (function_exists('is_user_logged_in')) {
667 $isloggedIn = is_user_logged_in();
676 public function isUserRegistrationPermitted() {
677 if (!get_option('users_can_register')) {
686 public function isPasswordUserGenerated() {
693 public function getLoggedInUserObject() {
694 if (function_exists('is_user_logged_in') &&
697 global $current_user;
699 return $current_user;
705 public function getLoggedInUfID() {
707 $current_user = $this->getLoggedInUserObject();
708 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
714 public function getLoggedInUniqueIdentifier() {
715 $user = $this->getLoggedInUserObject();
716 return $this->getUniqueIdentifierFromUserObject($user);
720 * Get User ID from UserFramework system (Joomla)
721 * @param object $user
722 * Object as described by the CMS.
726 public function getUserIDFromUserObject($user) {
727 return !empty($user->ID
) ?
$user->ID
: NULL;
733 public function getUniqueIdentifierFromUserObject($user) {
734 return empty($user->user_email
) ?
NULL : $user->user_email
;
740 public function getLoginURL($destination = '') {
741 $config = CRM_Core_Config
::singleton();
742 $loginURL = wp_login_url();
747 * FIXME: Do something.
749 * @param \CRM_Core_Form $form
751 * @return NULL|string
753 public function getLoginDestination(&$form) {
760 public function getVersion() {
761 if (function_exists('get_bloginfo')) {
762 return get_bloginfo('version', 'display');
772 public function getTimeZoneString() {
773 return get_option('timezone_string');
779 public function getUserRecordUrl($contactID) {
780 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
781 if (CRM_Core_Session
::singleton()
782 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))
784 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
789 * Append WP js to coreResourcesList.
793 public function appendCoreResources(&$list) {
794 $list[] = 'js/crm.wordpress.js';
800 public function synchronizeUsers() {
801 $config = CRM_Core_Config
::singleton();
802 if (PHP_SAPI
!= 'cli') {
806 $mail = 'user_email';
808 $uf = $config->userFramework
;
811 $contactMatching = 0;
814 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
816 foreach ($wpUserIds as $wpUserId) {
817 $wpUserData = get_userdata($wpUserId);
819 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
833 if (is_object($match)) {
839 'contactCount' => $contactCount,
840 'contactMatching' => $contactMatching,
841 'contactCreated' => $contactCreated,