3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * WordPress specific stuff goes here
39 class CRM_Utils_System_WordPress
extends CRM_Utils_System_Base
{
43 function __construct() {
45 * 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
46 * functions and leave the codebase oblivious to the type of CMS
50 $this->is_drupal
= FALSE;
51 $this->is_wordpress
= TRUE;
55 * sets the title of the page
57 * @param string $title
58 * @param null $pageTitle
60 * @paqram string $pageTitle
65 function setTitle($title, $pageTitle = NULL) {
69 if (civicrm_wp_in_civicrm()) {
70 global $civicrm_wp_title;
71 $civicrm_wp_title = $pageTitle;
72 $template = CRM_Core_Smarty
::singleton();
73 $template->assign('pageTitle', $pageTitle);
78 * Append an additional breadcrumb tag to the existing breadcrumb
82 * @internal param string $title
83 * @internal param string $url
89 function appendBreadCrumb($breadCrumbs) {
90 $breadCrumb = wp_get_breadcrumb();
92 if (is_array($breadCrumbs)) {
93 foreach ($breadCrumbs as $crumbs) {
94 if (stripos($crumbs['url'], 'id%%')) {
95 $args = array('cid', 'mid');
96 foreach ($args as $a) {
97 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
101 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
105 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
109 $template = CRM_Core_Smarty
::singleton();
110 $template->assign_by_ref('breadcrumb', $breadCrumb);
111 wp_set_breadcrumb($breadCrumb);
115 * Reset an additional breadcrumb tag to the existing breadcrumb
121 function resetBreadCrumb() {
123 wp_set_breadcrumb($bc);
127 * Append a string to the head of the html file
129 * @param string $head the new string to be appended
135 function addHTMLHead($head) {
136 static $registered = FALSE;
139 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
141 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
143 CRM_Core_Region
::instance('wp_head')->add(array(
148 static function _showHTMLHead() {
149 $region = CRM_Core_Region
::instance('wp_head', FALSE);
151 echo $region->render('');
158 * @param $url: string, absolute path to file
159 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
161 * Note: This function is not to be called directly
162 * @see CRM_Core_Region::render()
164 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
167 public function addScriptUrl($url, $region) {
172 * Add an inline script
174 * @param $code: string, javascript code
175 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
177 * Note: This function is not to be called directly
178 * @see CRM_Core_Region::render()
180 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
183 public function addScript($code, $region) {
190 * @param $url: string, absolute path to file
191 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
193 * Note: This function is not to be called directly
194 * @see CRM_Core_Region::render()
196 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
199 public function addStyleUrl($url, $region) {
204 * Add an inline style
206 * @param $code: string, css code
207 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
209 * Note: This function is not to be called directly
210 * @see CRM_Core_Region::render()
212 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
215 public function addStyle($code, $region) {
220 * rewrite various system urls to https
228 function mapConfigToSSL() {
230 $base_url = str_replace('http://', 'https://', $base_url);
234 * figure out the post url for the form
236 * @param mix $action the default action if one is pre-specified
238 * @return string the url to post the form
242 function postURL($action) {
243 if (!empty($action)) {
247 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
251 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
253 * @param $path string The path being linked to, such as "civicrm/add"
254 * @param $query string A query string to append to the link.
255 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
256 * Useful for links that will be displayed outside the site, such as in an
258 * @param $fragment string A fragment identifier (named anchor) to append to the link.
259 * @param $htmlize boolean whether to convert to html eqivalant
260 * @param $frontend boolean a gross joomla hack
262 * @param bool $forceBackend
264 * @return string an HTML string containing a link to the given path.
274 $forceBackend = FALSE
276 $config = CRM_Core_Config
::singleton();
278 $separator = $htmlize ?
'&' : '&';
280 $fragment = isset($fragment) ?
('#' . $fragment) : '';
282 $path = CRM_Utils_String
::stripPathChars($path);
284 //this means wp function we are trying to use is not available,
286 if (!function_exists('get_option')) {
287 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
289 if ($config->userFrameworkFrontend
) {
290 if (get_option('permalink_structure') != '') {
292 $script = get_permalink($post->ID
);
295 // when shortcode is included in page
296 // also make sure we have valid query object
298 if ( method_exists( $wp_query, 'get' ) ) {
299 if (get_query_var('page_id')) {
300 $wpPageParam = "page_id=" . get_query_var('page_id');
302 elseif (get_query_var('p')) {
303 // when shortcode is inserted in post
304 $wpPageParam = "p=" . get_query_var('p');
309 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
311 if (!isset($path) && !isset($query)) {
312 // FIXME: This short-circuited codepath is the same as the general one below, except
313 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
314 // why it's different (and I can only find two obvious use-cases for this codepath,
315 // of which at least one looks gratuitous). A more ambitious person would simply remove
317 return $base . $fragment;
320 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
324 $queryParts = array();
326 $queryParts[] = 'page=CiviCRM';
327 $queryParts[] = "q={$path}";
330 $queryParts[] = $wpPageParam;
333 $queryParts[] = $query;
336 return $base . '?' . implode($separator, $queryParts) . $fragment;
342 * @param $forceBackend
344 * @return mixed|null|string
346 private function getBaseUrl($absolute, $frontend, $forceBackend) {
347 $config = CRM_Core_Config
::singleton();
349 if (!isset($config->useFrameworkRelativeBase
)) {
350 $base = parse_url($config->userFrameworkBaseURL
);
351 $config->useFrameworkRelativeBase
= $base['path'];
354 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
356 if ((is_admin() && !$frontend) ||
$forceBackend) {
357 $base .= 'wp-admin/admin.php';
360 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
361 $base .= CIVICRM_UF_WP_BASEPAGE
;
364 elseif (isset($config->wpBasePage
)) {
365 $base .= $config->wpBasePage
;
372 * Authenticate the user against the wordpress db
374 * @param string $name the user name
375 * @param string $password the password for the above user name
377 * @param bool $loadCMSBootstrap
378 * @param null $realPath
380 * @return mixed false if no auth
382 * contactID, ufID, unique string ) if success
386 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
387 $config = CRM_Core_Config
::singleton();
389 if ($loadCMSBootstrap) {
390 $config->userSystem
->loadBootStrap($name, $password);
393 $user = wp_authenticate($name, $password);
394 if (is_a($user, 'WP_Error')) {
398 // need to change this to make sure we matched only one row
400 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
401 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
405 return array($contactID, $user->data
->ID
, mt_rand());
409 * Set a message in the UF to display to a user
411 * @param string $message the message to set
416 function setMessage($message) {
424 function loadUser( $user ) {
428 function permissionDenied() {
429 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
438 wp_redirect(wp_login_url());
441 function updateCategories() {}
444 * Get the locale set in the hosting CMS
446 * @return string with the locale or null for none
448 function getUFLocale() {
450 if (defined('ICL_LANGUAGE_CODE')) {
451 $language = ICL_LANGUAGE_CODE
;
454 // TODO: set language variable for others WordPress plugin
456 if (isset($language)) {
457 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
464 * load wordpress bootstrap
466 * @param $name string optional username for login
467 * @param $pass string optional password for login
471 function loadBootStrap($name = NULL, $pass = NULL) {
472 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
474 $cmsRootPath = $this->cmsRootPath();
476 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
479 require_once ($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php');
480 $wpUserTimezone = get_option('timezone_string');
481 if ($wpUserTimezone) {
482 date_default_timezone_set($wpUserTimezone);
483 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
485 require_once ($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php');
486 $uid = CRM_Utils_Array
::value('uid', $name);
488 $account = wp_set_current_user($uid);
489 if ($account && $account->data
->ID
) {
503 function validInstallDir($dir) {
504 $includePath = "$dir/wp-includes";
506 @opendir
($includePath) &&
507 file_exists("$includePath/version.php")
515 * Determine the location of the CMS root.
517 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
520 * @return NULL|string
522 function cmsRootPath() {
523 $cmsRoot = $valid = NULL;
524 if (defined('CIVICRM_CMSDIR')) {
525 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
526 $cmsRoot = CIVICRM_CMSDIR
;
531 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
533 //might be windows installation.
534 $firstVar = array_shift($pathVars);
536 $cmsRoot = $firstVar;
539 //start w/ csm dir search.
540 foreach ($pathVars as $var) {
542 if ($this->validInstallDir($cmsRoot)) {
543 //stop as we found bootstrap.
550 return ($valid) ?
$cmsRoot : NULL;
559 function createUser(&$params, $mail) {
562 'user_pass' => $params['cms_pass'],
563 'user_login' => $params['cms_name'],
564 'user_email' => $params[$mail],
565 'nickname' => $params['cms_name'],
566 'role' => get_option('default_role'),
568 if (isset($params['contactID'])) {
569 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
570 if ($contactType == 'Individual') {
571 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
572 $params['contactID'], 'first_name'
574 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
575 $params['contactID'], 'last_name'
580 $uid = wp_insert_user($user_data);
583 $creds['user_login'] = $params['cms_name'];
584 $creds['user_password'] = $params['cms_pass'];
585 $creds['remember'] = TRUE;
586 $user = wp_signon($creds, FALSE);
588 wp_new_user_notification($uid, $user_data['user_pass']);
593 * Change user name in host CMS
595 * @param integer $ufID User ID in CMS
596 * @param string $ufName User name
598 function updateCMSName($ufID, $ufName) {
600 if (function_exists('wp_update_user')) {
601 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
602 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
604 $values = array ('ID' => $ufID, 'user_email' => $ufName);
606 wp_update_user( $values ) ;
614 * @param string $emailName
616 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
617 $config = CRM_Core_Config
::singleton();
619 $dao = new CRM_Core_DAO();
620 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
621 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
623 if (!empty($params['name'])) {
624 if (!validate_username($params['name'])) {
625 $errors['cms_name'] = ts("Your username contains invalid characters");
627 elseif (username_exists(sanitize_user($params['name']))) {
628 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
632 if (!empty($params['mail'])) {
633 if (!is_email($params['mail'])) {
634 $errors[$emailName] = "Your email is invaid";
636 elseif (email_exists($params['mail'])) {
637 $resetUrl = $config->userFrameworkBaseURL
. 'wp-login.php?action=lostpassword';
638 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
639 array(1 => $params['mail'], 2 => $resetUrl)
646 * check is user logged in.
648 * @return boolean true/false.
650 public function isUserLoggedIn() {
652 if (function_exists('is_user_logged_in')) {
653 $isloggedIn = is_user_logged_in();
662 function getLoggedInUserObject() {
663 if (function_exists('is_user_logged_in') &&
664 is_user_logged_in()) {
665 global $current_user;
667 return $current_user;
670 * Get currently logged in user uf id.
672 * @return int $userID logged in user uf id.
674 public function getLoggedInUfID() {
676 $current_user = $this->getLoggedInUserObject();
677 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
681 * Get currently logged in user unique identifier - this tends to be the email address or user name.
683 * @return string $userID logged in user unique identifier
685 function getLoggedInUniqueIdentifier() {
686 $user = $this->getLoggedInUserObject();
687 return $this->getUniqueIdentifierFromUserObject($user);
691 * Get User ID from UserFramework system (Joomla)
692 * @param object $user object as described by the CMS
693 * @return mixed <NULL, number>
695 function getUserIDFromUserObject($user) {
696 return !empty($user->ID
) ?
$user->ID
: NULL;
700 * Get Unique Identifier from UserFramework system (CMS)
701 * @param object $user object as described by the User Framework
702 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
705 function getUniqueIdentifierFromUserObject($user) {
706 return empty($user->user_email
) ?
NULL : $user->user_email
;
710 * Get user login URL for hosting CMS (method declared in each CMS system class)
712 * @param string $destination - if present, add destination to querystring (works for Drupal only)
714 * @return string - loginURL for the current CMS
717 public function getLoginURL($destination = '') {
718 $config = CRM_Core_Config
::singleton();
719 $loginURL = $config->userFrameworkBaseURL
;
720 $loginURL .= 'wp-login.php';
727 public function getLoginDestination(&$form) {
732 * Return the current WordPress version if relevant function exists
734 * @return string - version number
737 function getVersion() {
738 if (function_exists('get_bloginfo')) {
739 return get_bloginfo('version', 'display');
747 * get timezone as a string
748 * @return string Timezone e.g. 'America/Los_Angeles'
750 function getTimeZoneString() {
751 return get_option('timezone_string');
755 * Get Url to view user record
756 * @param integer $contactID Contact ID
760 function getUserRecordUrl($contactID) {
761 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
762 if (CRM_Core_Session
::singleton()->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))) {
763 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;