3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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);
116 $civiRelPath = CRM_Utils_File
::relativize($civicrm_root, $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 = array('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', array(__CLASS__
, '_showHTMLHead'));
169 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
171 CRM_Core_Region
::instance('wp_head')->add(array(
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);
213 //this means wp function we are trying to use is not available,
215 if (!function_exists('get_option')) {
216 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
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;
271 * @param $forceBackend
273 * @return mixed|null|string
275 private function getBaseUrl($absolute, $frontend, $forceBackend) {
276 $config = CRM_Core_Config
::singleton();
278 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
280 if ((is_admin() && !$frontend) ||
$forceBackend) {
281 $base .= 'wp-admin/admin.php';
284 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
285 $base .= CIVICRM_UF_WP_BASEPAGE
;
288 elseif (isset($config->wpBasePage
)) {
289 $base .= $config->wpBasePage
;
298 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
299 $config = CRM_Core_Config
::singleton();
301 if ($loadCMSBootstrap) {
302 $config->userSystem
->loadBootStrap($name, $password);
305 $user = wp_authenticate($name, $password);
306 if (is_a($user, 'WP_Error')) {
310 // TODO: need to change this to make sure we matched only one row
312 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
313 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
317 return array($contactID, $user->data
->ID
, mt_rand());
321 * FIXME: Do something
323 * @param string $message
325 public function setMessage($message) {
329 * @param \string $user
333 public function loadUser($user) {
334 $userdata = get_user_by('login', $user);
335 if (!$userdata->data
->ID
) {
339 $uid = $userdata->data
->ID
;
340 wp_set_current_user($uid);
341 $contactID = CRM_Core_BAO_UFMatch
::getContactId($uid);
343 // lets store contact id and user id in session
344 $session = CRM_Core_Session
::singleton();
345 $session->set('ufID', $uid);
346 $session->set('userID', $contactID);
351 * FIXME: Use CMS-native approach
353 public function permissionDenied() {
354 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
360 public function logout() {
366 wp_redirect(wp_login_url());
372 public function getUFLocale() {
374 if (defined('ICL_LANGUAGE_CODE')) {
375 $language = ICL_LANGUAGE_CODE
;
378 // TODO: set language variable for others WordPress plugin
380 if (isset($language)) {
381 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
391 public function setUFLocale($civicrm_language) {
392 // TODO (probably not possible with WPML?)
397 * Load wordpress bootstrap.
399 * @param string $name
400 * optional username for login.
401 * @param string $pass
402 * optional password for login.
406 public function loadBootStrap($name = NULL, $pass = NULL) {
407 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
409 if (!defined('WP_USE_THEMES')) {
410 define('WP_USE_THEMES', FALSE);
413 $cmsRootPath = $this->cmsRootPath();
415 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
417 $path = Civi
::settings()->get('wpLoadPhp');
421 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
422 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
425 CRM_Core_Error
::fatal("Could not find the bootstrap file for WordPress");
427 $wpUserTimezone = get_option('timezone_string');
428 if ($wpUserTimezone) {
429 date_default_timezone_set($wpUserTimezone);
430 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
432 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
433 $uid = CRM_Utils_Array
::value('uid', $name);
435 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
436 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
438 $uid = wp_authenticate($name, $pass); // this returns a WP_User object if successful
441 echo '<br />Sorry, unrecognized username or password.';
449 if ($uid instanceof WP_User
) {
450 $account = wp_set_current_user($uid->ID
);
453 $account = wp_set_current_user($uid);
455 if ($account && $account->data
->ID
) {
469 public function validInstallDir($dir) {
470 $includePath = "$dir/wp-includes";
471 if (file_exists("$includePath/version.php")) {
478 * Determine the location of the CMS root.
480 * @return string|NULL
481 * local file system path to CMS root, or NULL if it cannot be determined
483 public function cmsRootPath() {
484 $cmsRoot = $valid = NULL;
485 if (defined('CIVICRM_CMSDIR')) {
486 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
487 $cmsRoot = CIVICRM_CMSDIR
;
492 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
494 //might be windows installation.
495 $firstVar = array_shift($pathVars);
497 $cmsRoot = $firstVar;
500 //start w/ csm dir search.
501 foreach ($pathVars as $var) {
503 if ($this->validInstallDir($cmsRoot)) {
504 //stop as we found bootstrap.
511 return ($valid) ?
$cmsRoot : NULL;
517 public function createUser(&$params, $mail) {
520 'user_pass' => $params['cms_pass'],
521 'user_login' => $params['cms_name'],
522 'user_email' => $params[$mail],
523 'nickname' => $params['cms_name'],
524 'role' => get_option('default_role'),
526 if (isset($params['contactID'])) {
527 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
528 if ($contactType == 'Individual') {
529 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
530 $params['contactID'], 'first_name'
532 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
533 $params['contactID'], 'last_name'
538 $uid = wp_insert_user($user_data);
541 $creds['user_login'] = $params['cms_name'];
542 $creds['user_password'] = $params['cms_pass'];
543 $creds['remember'] = TRUE;
544 $user = wp_signon($creds, FALSE);
546 wp_new_user_notification($uid, $user_data['user_pass']);
553 public function updateCMSName($ufID, $ufName) {
555 if (function_exists('wp_update_user')) {
556 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
557 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
559 $values = array('ID' => $ufID, 'user_email' => $ufName);
561 wp_update_user($values);
567 * @param array $params
569 * @param string $emailName
571 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
572 $config = CRM_Core_Config
::singleton();
574 $dao = new CRM_Core_DAO();
575 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
576 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
578 if (!empty($params['name'])) {
579 if (!validate_username($params['name'])) {
580 $errors['cms_name'] = ts("Your username contains invalid characters");
582 elseif (username_exists(sanitize_user($params['name']))) {
583 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
587 if (!empty($params['mail'])) {
588 if (!is_email($params['mail'])) {
589 $errors[$emailName] = "Your email is invaid";
591 elseif (email_exists($params['mail'])) {
592 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
593 array(1 => $params['mail'], 2 => wp_lostpassword_url())
602 public function isUserLoggedIn() {
604 if (function_exists('is_user_logged_in')) {
605 $isloggedIn = is_user_logged_in();
614 public function getLoggedInUserObject() {
615 if (function_exists('is_user_logged_in') &&
618 global $current_user;
620 return $current_user;
626 public function getLoggedInUfID() {
628 $current_user = $this->getLoggedInUserObject();
629 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
635 public function getLoggedInUniqueIdentifier() {
636 $user = $this->getLoggedInUserObject();
637 return $this->getUniqueIdentifierFromUserObject($user);
641 * Get User ID from UserFramework system (Joomla)
642 * @param object $user
643 * Object as described by the CMS.
647 public function getUserIDFromUserObject($user) {
648 return !empty($user->ID
) ?
$user->ID
: NULL;
654 public function getUniqueIdentifierFromUserObject($user) {
655 return empty($user->user_email
) ?
NULL : $user->user_email
;
661 public function getLoginURL($destination = '') {
662 $config = CRM_Core_Config
::singleton();
663 $loginURL = wp_login_url();
668 * FIXME: Do something.
670 * @param \CRM_Core_Form $form
672 * @return NULL|string
674 public function getLoginDestination(&$form) {
681 public function getVersion() {
682 if (function_exists('get_bloginfo')) {
683 return get_bloginfo('version', 'display');
693 public function getTimeZoneString() {
694 return get_option('timezone_string');
700 public function getUserRecordUrl($contactID) {
701 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
702 if (CRM_Core_Session
::singleton()
703 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))
705 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
710 * Append WP js to coreResourcesList.
714 public function appendCoreResources(&$list) {
715 $list[] = 'js/crm.wordpress.js';
721 public function synchronizeUsers() {
722 $config = CRM_Core_Config
::singleton();
723 if (PHP_SAPI
!= 'cli') {
727 $mail = 'user_email';
729 $uf = $config->userFramework
;
732 $contactMatching = 0;
735 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
737 foreach ($wpUserIds as $wpUserId) {
738 $wpUserData = get_userdata($wpUserId);
740 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
754 if (is_object($match)) {
760 'contactCount' => $contactCount,
761 'contactMatching' => $contactMatching,
762 'contactCreated' => $contactCreated,