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() {
80 $config = CRM_Core_Config
::singleton();
81 $baseURL = CRM_Utils_System
::languageNegotiationURL($config->userFrameworkBaseURL
, FALSE, TRUE);
85 $upload_dir = wp_upload_dir();
86 $settingsDir = $upload_dir['basedir'] . DIRECTORY_SEPARATOR
. 'civicrm' . DIRECTORY_SEPARATOR
;
87 $settingsURL = $upload_dir['baseurl'] . DIRECTORY_SEPARATOR
. 'civicrm' . DIRECTORY_SEPARATOR
;
88 if (is_dir(WP_PLUGIN_DIR
. '/files/civicrm/')) {
90 $filesURL = WP_PLUGIN_URL
. "/files/civicrm/";
92 elseif (is_dir($settingsDir)) {
93 $filesURL = $settingsURL;
96 throw new CRM_Core_Exception("Failed to locate default file storage ($config->userFramework)");
101 'path' => CRM_Utils_File
::baseFilePath(),
108 public function appendBreadCrumb($breadCrumbs) {
109 $breadCrumb = wp_get_breadcrumb();
111 if (is_array($breadCrumbs)) {
112 foreach ($breadCrumbs as $crumbs) {
113 if (stripos($crumbs['url'], 'id%%')) {
114 $args = array('cid', 'mid');
115 foreach ($args as $a) {
116 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
120 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
124 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
128 $template = CRM_Core_Smarty
::singleton();
129 $template->assign_by_ref('breadcrumb', $breadCrumb);
130 wp_set_breadcrumb($breadCrumb);
136 public function resetBreadCrumb() {
138 wp_set_breadcrumb($bc);
144 public function addHTMLHead($head) {
145 static $registered = FALSE;
148 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
150 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
152 CRM_Core_Region
::instance('wp_head')->add(array(
158 * WP action callback.
160 public static function _showHTMLHead() {
161 $region = CRM_Core_Region
::instance('wp_head', FALSE);
163 echo $region->render('');
170 public function mapConfigToSSL() {
172 $base_url = str_replace('http://', 'https://', $base_url);
185 $forceBackend = FALSE
187 $config = CRM_Core_Config
::singleton();
189 $separator = $htmlize ?
'&' : '&';
191 $fragment = isset($fragment) ?
('#' . $fragment) : '';
193 $path = CRM_Utils_String
::stripPathChars($path);
195 //this means wp function we are trying to use is not available,
197 if (!function_exists('get_option')) {
198 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
200 if ($config->userFrameworkFrontend
) {
201 if (get_option('permalink_structure') != '') {
203 $script = get_permalink($post->ID
);
206 // when shortcode is included in page
207 // also make sure we have valid query object
209 if (method_exists($wp_query, 'get')) {
210 if (get_query_var('page_id')) {
211 $wpPageParam = "page_id=" . get_query_var('page_id');
213 elseif (get_query_var('p')) {
214 // when shortcode is inserted in post
215 $wpPageParam = "p=" . get_query_var('p');
220 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
222 if (!isset($path) && !isset($query)) {
223 // FIXME: This short-circuited codepath is the same as the general one below, except
224 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
225 // why it's different (and I can only find two obvious use-cases for this codepath,
226 // of which at least one looks gratuitous). A more ambitious person would simply remove
228 return $base . $fragment;
231 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
235 $queryParts = array();
237 $queryParts[] = 'page=CiviCRM';
238 $queryParts[] = "q={$path}";
241 $queryParts[] = $wpPageParam;
244 $queryParts[] = $query;
247 return $base . '?' . implode($separator, $queryParts) . $fragment;
253 * @param $forceBackend
255 * @return mixed|null|string
257 private function getBaseUrl($absolute, $frontend, $forceBackend) {
258 $config = CRM_Core_Config
::singleton();
260 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
262 if ((is_admin() && !$frontend) ||
$forceBackend) {
263 $base .= 'wp-admin/admin.php';
266 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
267 $base .= CIVICRM_UF_WP_BASEPAGE
;
270 elseif (isset($config->wpBasePage
)) {
271 $base .= $config->wpBasePage
;
280 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
281 $config = CRM_Core_Config
::singleton();
283 if ($loadCMSBootstrap) {
284 $config->userSystem
->loadBootStrap($name, $password);
287 $user = wp_authenticate($name, $password);
288 if (is_a($user, 'WP_Error')) {
292 // TODO: need to change this to make sure we matched only one row
294 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
295 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
299 return array($contactID, $user->data
->ID
, mt_rand());
303 * FIXME: Do something
305 * @param string $message
307 public function setMessage($message) {
311 * FIXME: Do something
317 public function loadUser($user) {
322 * FIXME: Use CMS-native approach
324 public function permissionDenied() {
325 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
331 public function logout() {
337 wp_redirect(wp_login_url());
343 public function getUFLocale() {
345 if (defined('ICL_LANGUAGE_CODE')) {
346 $language = ICL_LANGUAGE_CODE
;
349 // TODO: set language variable for others WordPress plugin
351 if (isset($language)) {
352 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
362 public function setUFLocale($civicrm_language) {
363 // TODO (probably not possible with WPML?)
368 * Load wordpress bootstrap.
370 * @param string $name
371 * optional username for login.
372 * @param string $pass
373 * optional password for login.
377 public function loadBootStrap($name = NULL, $pass = NULL) {
378 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
380 if (!defined('WP_USE_THEMES')) {
381 define('WP_USE_THEMES', FALSE);
384 $cmsRootPath = $this->cmsRootPath();
386 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
388 $path = Civi
::settings()->get('wpLoadPhp');
392 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php')) {
393 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
396 CRM_Core_Error
::fatal("Could not find the bootstrap file for WordPress");
398 $wpUserTimezone = get_option('timezone_string');
399 if ($wpUserTimezone) {
400 date_default_timezone_set($wpUserTimezone);
401 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
403 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
404 $uid = CRM_Utils_Array
::value('uid', $name);
406 $name = $name ?
$name : trim(CRM_Utils_Array
::value('name', $_REQUEST));
407 $pass = $pass ?
$pass : trim(CRM_Utils_Array
::value('pass', $_REQUEST));
409 $uid = wp_authenticate($name, $pass); // this returns a WP_User object if successful
412 echo '<br />Sorry, unrecognized username or password.';
420 if ($uid instanceof WP_User
) {
421 $account = wp_set_current_user($uid->ID
);
424 $account = wp_set_current_user($uid);
426 if ($account && $account->data
->ID
) {
440 public function validInstallDir($dir) {
441 $includePath = "$dir/wp-includes";
442 if (file_exists("$includePath/version.php")) {
449 * Determine the location of the CMS root.
451 * @return string|NULL
452 * local file system path to CMS root, or NULL if it cannot be determined
454 public function cmsRootPath() {
455 $cmsRoot = $valid = NULL;
456 if (defined('CIVICRM_CMSDIR')) {
457 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
458 $cmsRoot = CIVICRM_CMSDIR
;
463 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
465 //might be windows installation.
466 $firstVar = array_shift($pathVars);
468 $cmsRoot = $firstVar;
471 //start w/ csm dir search.
472 foreach ($pathVars as $var) {
474 if ($this->validInstallDir($cmsRoot)) {
475 //stop as we found bootstrap.
482 return ($valid) ?
$cmsRoot : NULL;
488 public function createUser(&$params, $mail) {
491 'user_pass' => $params['cms_pass'],
492 'user_login' => $params['cms_name'],
493 'user_email' => $params[$mail],
494 'nickname' => $params['cms_name'],
495 'role' => get_option('default_role'),
497 if (isset($params['contactID'])) {
498 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
499 if ($contactType == 'Individual') {
500 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
501 $params['contactID'], 'first_name'
503 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
504 $params['contactID'], 'last_name'
509 $uid = wp_insert_user($user_data);
512 $creds['user_login'] = $params['cms_name'];
513 $creds['user_password'] = $params['cms_pass'];
514 $creds['remember'] = TRUE;
515 $user = wp_signon($creds, FALSE);
517 wp_new_user_notification($uid, $user_data['user_pass']);
524 public function updateCMSName($ufID, $ufName) {
526 if (function_exists('wp_update_user')) {
527 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
528 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
530 $values = array('ID' => $ufID, 'user_email' => $ufName);
532 wp_update_user($values);
538 * @param array $params
540 * @param string $emailName
542 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
543 $config = CRM_Core_Config
::singleton();
545 $dao = new CRM_Core_DAO();
546 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
547 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
549 if (!empty($params['name'])) {
550 if (!validate_username($params['name'])) {
551 $errors['cms_name'] = ts("Your username contains invalid characters");
553 elseif (username_exists(sanitize_user($params['name']))) {
554 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
558 if (!empty($params['mail'])) {
559 if (!is_email($params['mail'])) {
560 $errors[$emailName] = "Your email is invaid";
562 elseif (email_exists($params['mail'])) {
563 $resetUrl = $config->userFrameworkBaseURL
. 'wp-login.php?action=lostpassword';
564 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
565 array(1 => $params['mail'], 2 => $resetUrl)
574 public function isUserLoggedIn() {
576 if (function_exists('is_user_logged_in')) {
577 $isloggedIn = is_user_logged_in();
586 public function getLoggedInUserObject() {
587 if (function_exists('is_user_logged_in') &&
590 global $current_user;
592 return $current_user;
598 public function getLoggedInUfID() {
600 $current_user = $this->getLoggedInUserObject();
601 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
607 public function getLoggedInUniqueIdentifier() {
608 $user = $this->getLoggedInUserObject();
609 return $this->getUniqueIdentifierFromUserObject($user);
613 * Get User ID from UserFramework system (Joomla)
614 * @param object $user
615 * Object as described by the CMS.
619 public function getUserIDFromUserObject($user) {
620 return !empty($user->ID
) ?
$user->ID
: NULL;
626 public function getUniqueIdentifierFromUserObject($user) {
627 return empty($user->user_email
) ?
NULL : $user->user_email
;
633 public function getLoginURL($destination = '') {
634 $config = CRM_Core_Config
::singleton();
635 $loginURL = $config->userFrameworkBaseURL
;
636 $loginURL .= 'wp-login.php';
641 * FIXME: Do something.
643 * @param \CRM_Core_Form $form
645 * @return NULL|string
647 public function getLoginDestination(&$form) {
654 public function getVersion() {
655 if (function_exists('get_bloginfo')) {
656 return get_bloginfo('version', 'display');
666 public function getTimeZoneString() {
667 return get_option('timezone_string');
673 public function getUserRecordUrl($contactID) {
674 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
675 if (CRM_Core_Session
::singleton()
676 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))
678 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;
683 * Append WP js to coreResourcesList.
687 public function appendCoreResources(&$list) {
688 $list[] = 'js/crm.wordpress.js';
694 public function synchronizeUsers() {
695 $config = CRM_Core_Config
::singleton();
696 if (PHP_SAPI
!= 'cli') {
700 $mail = 'user_email';
702 $uf = $config->userFramework
;
705 $contactMatching = 0;
708 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
710 foreach ($wpUserIds as $wpUserId) {
711 $wpUserData = get_userdata($wpUserId);
713 if ($match = CRM_Core_BAO_UFMatch
::synchronizeUFMatch($wpUserData,
727 if (is_object($match)) {
733 'contactCount' => $contactCount,
734 'contactMatching' => $contactMatching,
735 'contactCreated' => $contactCreated,