3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 public 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
62 public function setTitle($title, $pageTitle = NULL) {
67 // get civi-wordpress instance
70 // do we have functionality provided by plugin version 4.6+ present?
71 if (method_exists($civi, 'civicrm_context_get')) {
73 global $civicrm_wp_title;
74 $civicrm_wp_title = $pageTitle;
76 // yes, set page title, depending on context
77 $context = civi_wp()->civicrm_context_get();
81 $template = CRM_Core_Smarty
::singleton();
82 $template->assign('pageTitle', $pageTitle);
85 } elseif (civicrm_wp_in_civicrm()) {
87 // legacy pre-4.6 behaviour
88 global $civicrm_wp_title;
89 $civicrm_wp_title = $pageTitle;
90 $template = CRM_Core_Smarty
::singleton();
91 $template->assign('pageTitle', $pageTitle);
97 * Append an additional breadcrumb tag to the existing breadcrumb
101 * @internal param string $title
102 * @internal param string $url
107 public function appendBreadCrumb($breadCrumbs) {
108 $breadCrumb = wp_get_breadcrumb();
110 if (is_array($breadCrumbs)) {
111 foreach ($breadCrumbs as $crumbs) {
112 if (stripos($crumbs['url'], 'id%%')) {
113 $args = array('cid', 'mid');
114 foreach ($args as $a) {
115 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
119 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
123 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
127 $template = CRM_Core_Smarty
::singleton();
128 $template->assign_by_ref('breadcrumb', $breadCrumb);
129 wp_set_breadcrumb($breadCrumb);
133 * Reset an additional breadcrumb tag to the existing breadcrumb
138 public function resetBreadCrumb() {
140 wp_set_breadcrumb($bc);
144 * Append a string to the head of the html file
146 * @param string $head the new string to be appended
151 public function addHTMLHead($head) {
152 static $registered = FALSE;
155 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
157 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
159 CRM_Core_Region
::instance('wp_head')->add(array(
164 public static function _showHTMLHead() {
165 $region = CRM_Core_Region
::instance('wp_head', FALSE);
167 echo $region->render('');
174 * @param $url: string, absolute path to file
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
182 public function addScriptUrl($url, $region) {
187 * Add an inline script
189 * @param $code: string, javascript code
190 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
192 * Note: This function is not to be called directly
193 * @see CRM_Core_Region::render()
195 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
197 public function addScript($code, $region) {
204 * @param $url: string, absolute path to file
205 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
207 * Note: This function is not to be called directly
208 * @see CRM_Core_Region::render()
210 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
212 public function addStyleUrl($url, $region) {
217 * Add an inline style
219 * @param $code: string, css code
220 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
222 * Note: This function is not to be called directly
223 * @see CRM_Core_Region::render()
225 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
227 public function addStyle($code, $region) {
232 * Rewrite various system urls to https
239 public function mapConfigToSSL() {
241 $base_url = str_replace('http://', 'https://', $base_url);
245 * Figure out the post url for the form
247 * @param mix $action the default action if one is pre-specified
249 * @return string the url to post the form
252 public function postURL($action) {
253 if (!empty($action)) {
257 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
261 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
263 * @param $path string The path being linked to, such as "civicrm/add"
264 * @param $query string A query string to append to the link.
265 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
266 * Useful for links that will be displayed outside the site, such as in an
268 * @param $fragment string A fragment identifier (named anchor) to append to the link.
269 * @param $htmlize boolean whether to convert to html eqivalant
270 * @param $frontend boolean a gross joomla hack
272 * @param bool $forceBackend
274 * @return string an HTML string containing a link to the given path.
283 $forceBackend = FALSE
285 $config = CRM_Core_Config
::singleton();
287 $separator = $htmlize ?
'&' : '&';
289 $fragment = isset($fragment) ?
('#' . $fragment) : '';
291 $path = CRM_Utils_String
::stripPathChars($path);
293 //this means wp function we are trying to use is not available,
295 if (!function_exists('get_option')) {
296 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
298 if ($config->userFrameworkFrontend
) {
299 if (get_option('permalink_structure') != '') {
301 $script = get_permalink($post->ID
);
304 // when shortcode is included in page
305 // also make sure we have valid query object
307 if ( method_exists( $wp_query, 'get' ) ) {
308 if (get_query_var('page_id')) {
309 $wpPageParam = "page_id=" . get_query_var('page_id');
311 elseif (get_query_var('p')) {
312 // when shortcode is inserted in post
313 $wpPageParam = "p=" . get_query_var('p');
318 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
320 if (!isset($path) && !isset($query)) {
321 // FIXME: This short-circuited codepath is the same as the general one below, except
322 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
323 // why it's different (and I can only find two obvious use-cases for this codepath,
324 // of which at least one looks gratuitous). A more ambitious person would simply remove
326 return $base . $fragment;
329 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
333 $queryParts = array();
335 $queryParts[] = 'page=CiviCRM';
336 $queryParts[] = "q={$path}";
339 $queryParts[] = $wpPageParam;
342 $queryParts[] = $query;
345 return $base . '?' . implode($separator, $queryParts) . $fragment;
351 * @param $forceBackend
353 * @return mixed|null|string
355 private function getBaseUrl($absolute, $frontend, $forceBackend) {
356 $config = CRM_Core_Config
::singleton();
358 if (!isset($config->useFrameworkRelativeBase
)) {
359 $base = parse_url($config->userFrameworkBaseURL
);
360 $config->useFrameworkRelativeBase
= $base['path'];
363 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
365 if ((is_admin() && !$frontend) ||
$forceBackend) {
366 $base .= 'wp-admin/admin.php';
369 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
370 $base .= CIVICRM_UF_WP_BASEPAGE
;
373 elseif (isset($config->wpBasePage
)) {
374 $base .= $config->wpBasePage
;
381 * Authenticate the user against the wordpress db
383 * @param string $name the user name
384 * @param string $password the password for the above user name
386 * @param bool $loadCMSBootstrap
387 * @param null $realPath
389 * @return mixed false if no auth
391 * contactID, ufID, unique string ) if success
394 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
395 $config = CRM_Core_Config
::singleton();
397 if ($loadCMSBootstrap) {
398 $config->userSystem
->loadBootStrap($name, $password);
401 $user = wp_authenticate($name, $password);
402 if (is_a($user, 'WP_Error')) {
406 // need to change this to make sure we matched only one row
408 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
409 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
413 return array($contactID, $user->data
->ID
, mt_rand());
417 * Set a message in the UF to display to a user
419 * @param string $message the message to set
423 public function setMessage($message) {
431 public function loadUser( $user ) {
435 public function permissionDenied() {
436 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
439 public function logout() {
445 wp_redirect(wp_login_url());
448 public function updateCategories() {}
451 * Get the locale set in the hosting CMS
453 * @return string with the locale or null for none
455 public function getUFLocale() {
457 if (defined('ICL_LANGUAGE_CODE')) {
458 $language = ICL_LANGUAGE_CODE
;
461 // TODO: set language variable for others WordPress plugin
463 if (isset($language)) {
464 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
471 * Load wordpress bootstrap
473 * @param $name string optional username for login
474 * @param $pass string optional password for login
478 public function loadBootStrap($name = NULL, $pass = NULL) {
479 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
481 $cmsRootPath = $this->cmsRootPath();
483 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
486 require_once ($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php');
487 $wpUserTimezone = get_option('timezone_string');
488 if ($wpUserTimezone) {
489 date_default_timezone_set($wpUserTimezone);
490 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
492 require_once ($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php');
493 $uid = CRM_Utils_Array
::value('uid', $name);
495 $account = wp_set_current_user($uid);
496 if ($account && $account->data
->ID
) {
510 public function validInstallDir($dir) {
511 $includePath = "$dir/wp-includes";
512 if (file_exists("$includePath/version.php")) {
519 * Determine the location of the CMS root.
521 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
524 * @return NULL|string
526 public function cmsRootPath() {
527 $cmsRoot = $valid = NULL;
528 if (defined('CIVICRM_CMSDIR')) {
529 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
530 $cmsRoot = CIVICRM_CMSDIR
;
535 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
537 //might be windows installation.
538 $firstVar = array_shift($pathVars);
540 $cmsRoot = $firstVar;
543 //start w/ csm dir search.
544 foreach ($pathVars as $var) {
546 if ($this->validInstallDir($cmsRoot)) {
547 //stop as we found bootstrap.
554 return ($valid) ?
$cmsRoot : NULL;
558 * @param array $params
563 public function createUser(&$params, $mail) {
566 'user_pass' => $params['cms_pass'],
567 'user_login' => $params['cms_name'],
568 'user_email' => $params[$mail],
569 'nickname' => $params['cms_name'],
570 'role' => get_option('default_role'),
572 if (isset($params['contactID'])) {
573 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
574 if ($contactType == 'Individual') {
575 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
576 $params['contactID'], 'first_name'
578 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
579 $params['contactID'], 'last_name'
584 $uid = wp_insert_user($user_data);
587 $creds['user_login'] = $params['cms_name'];
588 $creds['user_password'] = $params['cms_pass'];
589 $creds['remember'] = TRUE;
590 $user = wp_signon($creds, FALSE);
592 wp_new_user_notification($uid, $user_data['user_pass']);
597 * Change user name in host CMS
599 * @param integer $ufID User ID in CMS
600 * @param string $ufName User name
602 public function updateCMSName($ufID, $ufName) {
604 if (function_exists('wp_update_user')) {
605 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
606 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
608 $values = array ('ID' => $ufID, 'user_email' => $ufName);
610 wp_update_user( $values ) ;
616 * @param array $params
618 * @param string $emailName
620 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
621 $config = CRM_Core_Config
::singleton();
623 $dao = new CRM_Core_DAO();
624 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
625 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
627 if (!empty($params['name'])) {
628 if (!validate_username($params['name'])) {
629 $errors['cms_name'] = ts("Your username contains invalid characters");
631 elseif (username_exists(sanitize_user($params['name']))) {
632 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
636 if (!empty($params['mail'])) {
637 if (!is_email($params['mail'])) {
638 $errors[$emailName] = "Your email is invaid";
640 elseif (email_exists($params['mail'])) {
641 $resetUrl = $config->userFrameworkBaseURL
. 'wp-login.php?action=lostpassword';
642 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
643 array(1 => $params['mail'], 2 => $resetUrl)
650 * Check is user logged in.
652 * @return boolean true/false.
654 public function isUserLoggedIn() {
656 if (function_exists('is_user_logged_in')) {
657 $isloggedIn = is_user_logged_in();
666 public function getLoggedInUserObject() {
667 if (function_exists('is_user_logged_in') &&
668 is_user_logged_in()) {
669 global $current_user;
671 return $current_user;
674 * Get currently logged in user uf id.
676 * @return int $userID logged in user uf id.
678 public function getLoggedInUfID() {
680 $current_user = $this->getLoggedInUserObject();
681 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
685 * Get currently logged in user unique identifier - this tends to be the email address or user name.
687 * @return string $userID logged in user unique identifier
689 public function getLoggedInUniqueIdentifier() {
690 $user = $this->getLoggedInUserObject();
691 return $this->getUniqueIdentifierFromUserObject($user);
695 * Get User ID from UserFramework system (Joomla)
696 * @param object $user object as described by the CMS
697 * @return mixed <NULL, number>
699 public function getUserIDFromUserObject($user) {
700 return !empty($user->ID
) ?
$user->ID
: NULL;
704 * Get Unique Identifier from UserFramework system (CMS)
705 * @param object $user object as described by the User Framework
706 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
709 public function getUniqueIdentifierFromUserObject($user) {
710 return empty($user->user_email
) ?
NULL : $user->user_email
;
714 * Get user login URL for hosting CMS (method declared in each CMS system class)
716 * @param string $destination - if present, add destination to querystring (works for Drupal only)
718 * @return string - loginURL for the current CMS
721 public function getLoginURL($destination = '') {
722 $config = CRM_Core_Config
::singleton();
723 $loginURL = $config->userFrameworkBaseURL
;
724 $loginURL .= 'wp-login.php';
729 * @param CRM_Core_Form $form
731 public function getLoginDestination(&$form) {
736 * Return the current WordPress version if relevant function exists
738 * @return string - version number
741 public function getVersion() {
742 if (function_exists('get_bloginfo')) {
743 return get_bloginfo('version', 'display');
751 * Get timezone as a string
752 * @return string Timezone e.g. 'America/Los_Angeles'
754 public function getTimeZoneString() {
755 return get_option('timezone_string');
759 * Get Url to view user record
760 * @param integer $contactID Contact ID
764 public function getUserRecordUrl($contactID) {
765 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
766 if (CRM_Core_Session
::singleton()->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))) {
767 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;