3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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);
212 //this means wp function we are trying to use is not available,
214 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
215 if (!function_exists('get_option')) {
216 $this->loadBootStrap();
218 if ($config->userFrameworkFrontend
) {
219 if (get_option('permalink_structure') != '') {
221 $script = get_permalink($post->ID
);
224 // when shortcode is included in page
225 // also make sure we have valid query object
227 if (method_exists($wp_query, 'get')) {
228 if (get_query_var('page_id')) {
229 $wpPageParam = "page_id=" . get_query_var('page_id');
231 elseif (get_query_var('p')) {
232 // when shortcode is inserted in post
233 $wpPageParam = "p=" . get_query_var('p');
238 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
240 if (!isset($path) && !isset($query)) {
241 // FIXME: This short-circuited codepath is the same as the general one below, except
242 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
243 // why it's different (and I can only find two obvious use-cases for this codepath,
244 // of which at least one looks gratuitous). A more ambitious person would simply remove
246 return $base . $fragment;
249 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
253 $queryParts = array();
255 $queryParts[] = 'page=CiviCRM';
256 $queryParts[] = "q={$path}";
259 $queryParts[] = $wpPageParam;
262 $queryParts[] = $query;
265 return $base . '?' . implode($separator, $queryParts) . $fragment;
270 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
271 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
272 * For now leave hard coded wp-admin references.
273 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
277 * @param $forceBackend
279 * @return mixed|null|string
281 private function getBaseUrl($absolute, $frontend, $forceBackend) {
282 $config = CRM_Core_Config
::singleton();
283 if ((is_admin() && !$frontend) ||
$forceBackend) {
284 return Civi
::paths()->getUrl('[wp.backend]/.', $absolute ?
'absolute' : 'relative');
287 return Civi
::paths()->getUrl('[wp.frontend]/.', $absolute ?
'absolute' : 'relative');
294 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
295 $config = CRM_Core_Config
::singleton();
297 if ($loadCMSBootstrap) {
298 $config->userSystem
->loadBootStrap($name, $password);
301 $user = wp_authenticate($name, $password);
302 if (is_a($user, 'WP_Error')) {
306 // TODO: need to change this to make sure we matched only one row
308 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
309 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
313 return array($contactID, $user->data
->ID
, mt_rand());
317 * FIXME: Do something
319 * @param string $message
321 public function setMessage($message) {
325 * @param \string $user
329 public function loadUser($user) {
330 $userdata = get_user_by('login', $user);
331 if (!$userdata->data
->ID
) {
335 $uid = $userdata->data
->ID
;
336 wp_set_current_user($uid);
337 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
339 // lets store contact id and user id in session
340 $session = CRM_Core_Session
::singleton();
341 $session->set('ufID', $uid);
342 $session->set('userID', $contactID);
347 * FIXME: Use CMS-native approach
349 public function permissionDenied() {
350 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
354 * Determine the native ID of the CMS user.
356 * @param string $username
359 public function getUfId($username) {
360 $userdata = get_user_by('login', $username);
361 if (!$userdata->data
->ID
) {
364 return $userdata->data
->ID
;
370 public function logout() {
376 wp_redirect(wp_login_url());
382 public function getUFLocale() {
384 if (function_exists('pll_current_language')) {
385 $language = pll_current_language();
388 elseif (defined('ICL_LANGUAGE_CODE')) {
389 $language = ICL_LANGUAGE_CODE
;
392 // TODO: set language variable for others WordPress plugin
394 if (!empty($language)) {
395 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
405 public function setUFLocale($civicrm_language) {
406 // TODO (probably not possible with WPML?)
411 * Load wordpress bootstrap.
413 * @param string $name
414 * optional username for login.
415 * @param string $pass
416 * optional password for login.
420 public function loadBootStrap($name = NULL, $pass = NULL) {
421 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
423 if (!defined('WP_USE_THEMES')) {
424 define('WP_USE_THEMES', FALSE);
427 $cmsRootPath = $this->cmsRootPath();
429 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
431 $path = Civi
::settings()->get('wpLoadPhp');
435 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
436 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
439 CRM_Core_Error
::fatal("Could not find the bootstrap file for WordPress");
441 $wpUserTimezone = get_option('timezone_string');
442 if ($wpUserTimezone) {
443 date_default_timezone_set($wpUserTimezone);
444 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
446 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
447 $uid = CRM_Utils_Array
::value('uid', $name);
449 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
450 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
452 $uid = wp_authenticate($name, $pass);
455 echo '<br />Sorry, unrecognized username or password.';
463 if ($uid instanceof WP_User
) {
464 $account = wp_set_current_user($uid->ID
);
467 $account = wp_set_current_user($uid);
469 if ($account && $account->data
->ID
) {
483 public function validInstallDir($dir) {
484 $includePath = "$dir/wp-includes";
485 if (@file_exists
("$includePath/version.php")) {
492 * Determine the location of the CMS root.
494 * @return string|NULL
495 * local file system path to CMS root, or NULL if it cannot be determined
497 public function cmsRootPath() {
498 global $civicrm_paths;
499 if (!empty($civicrm_paths['cms.root']['path'])) {
500 return $civicrm_paths['cms.root']['path'];
503 $cmsRoot = $valid = NULL;
504 if (defined('CIVICRM_CMSDIR')) {
505 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
506 $cmsRoot = CIVICRM_CMSDIR
;
511 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
513 //might be windows installation.
514 $firstVar = array_shift($pathVars);
516 $cmsRoot = $firstVar;
519 //start w/ csm dir search.
520 foreach ($pathVars as $var) {
522 if ($this->validInstallDir($cmsRoot)) {
523 //stop as we found bootstrap.
530 return ($valid) ?
$cmsRoot : NULL;
536 public function createUser(&$params, $mail) {
539 'user_pass' => $params['cms_pass'],
540 'user_login' => $params['cms_name'],
541 'user_email' => $params[$mail],
542 'nickname' => $params['cms_name'],
543 'role' => get_option('default_role'),
545 if (isset($params['contactID'])) {
546 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
547 if ($contactType == 'Individual') {
548 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
549 $params['contactID'], 'first_name'
551 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
552 $params['contactID'], 'last_name'
557 $uid = wp_insert_user($user_data);
560 $creds['user_login'] = $params['cms_name'];
561 $creds['user_password'] = $params['cms_pass'];
562 $creds['remember'] = TRUE;
563 $user = wp_signon($creds, FALSE);
565 wp_new_user_notification($uid, $user_data['user_pass']);
572 public function updateCMSName($ufID, $ufName) {
574 if (function_exists('wp_update_user')) {
575 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
576 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
578 $values = array('ID' => $ufID, 'user_email' => $ufName);
580 wp_update_user($values);
586 * @param array $params
588 * @param string $emailName
590 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
591 $config = CRM_Core_Config
::singleton();
593 $dao = new CRM_Core_DAO();
594 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
595 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
597 if (!empty($params['name'])) {
598 if (!validate_username($params['name'])) {
599 $errors['cms_name'] = ts("Your username contains invalid characters");
601 elseif (username_exists(sanitize_user($params['name']))) {
602 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
606 if (!empty($params['mail'])) {
607 if (!is_email($params['mail'])) {
608 $errors[$emailName] = "Your email is invaid";
610 elseif (email_exists($params['mail'])) {
611 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
612 array(1 => $params['mail'], 2 => wp_lostpassword_url())
621 public function isUserLoggedIn() {
623 if (function_exists('is_user_logged_in')) {
624 $isloggedIn = is_user_logged_in();
633 public function isUserRegistrationPermitted() {
634 if (!get_option('users_can_register')) {
643 public function isPasswordUserGenerated() {
650 public function getLoggedInUserObject() {
651 if (function_exists('is_user_logged_in') &&
654 global $current_user;
656 return $current_user;
662 public function getLoggedInUfID() {
664 $current_user = $this->getLoggedInUserObject();
665 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
671 public function getLoggedInUniqueIdentifier() {
672 $user = $this->getLoggedInUserObject();
673 return $this->getUniqueIdentifierFromUserObject($user);
677 * Get User ID from UserFramework system (Joomla)
678 * @param object $user
679 * Object as described by the CMS.
683 public function getUserIDFromUserObject($user) {
684 return !empty($user->ID
) ?
$user->ID
: NULL;
690 public function getUniqueIdentifierFromUserObject($user) {
691 return empty($user->user_email
) ?
NULL : $user->user_email
;
697 public function getLoginURL($destination = '') {
698 $config = CRM_Core_Config
::singleton();
699 $loginURL = wp_login_url();
704 * FIXME: Do something.
706 * @param \CRM_Core_Form $form
708 * @return NULL|string
710 public function getLoginDestination(&$form) {
717 public function getVersion() {
718 if (function_exists('get_bloginfo')) {
719 return get_bloginfo('version', 'display');
729 public function getTimeZoneString() {
730 return get_option('timezone_string');
736 public function getUserRecordUrl($contactID) {
737 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
738 if (CRM_Core_Session
::singleton()
739 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))
741 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
746 * Append WP js to coreResourcesList.
750 public function appendCoreResources(&$list) {
751 $list[] = 'js/crm.wordpress.js';
757 public function synchronizeUsers() {
758 $config = CRM_Core_Config
::singleton();
759 if (PHP_SAPI
!= 'cli') {
763 $mail = 'user_email';
765 $uf = $config->userFramework
;
768 $contactMatching = 0;
771 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
773 foreach ($wpUserIds as $wpUserId) {
774 $wpUserData = get_userdata($wpUserId);
776 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
790 if (is_object($match)) {
796 'contactCount' => $contactCount,
797 'contactMatching' => $contactMatching,
798 'contactCreated' => $contactCreated,