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;
54 * sets the title of the page
56 * @param string $title
57 * @param null $pageTitle
59 * @paqram string $pageTitle
64 function setTitle($title, $pageTitle = NULL) {
68 if (civicrm_wp_in_civicrm()) {
69 global $civicrm_wp_title;
70 $civicrm_wp_title = $pageTitle;
71 $template = CRM_Core_Smarty
::singleton();
72 $template->assign('pageTitle', $pageTitle);
77 * Append an additional breadcrumb tag to the existing breadcrumb
81 * @internal param string $title
82 * @internal param string $url
88 function appendBreadCrumb($breadCrumbs) {
89 $breadCrumb = wp_get_breadcrumb();
91 if (is_array($breadCrumbs)) {
92 foreach ($breadCrumbs as $crumbs) {
93 if (stripos($crumbs['url'], 'id%%')) {
94 $args = array('cid', 'mid');
95 foreach ($args as $a) {
96 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
100 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
104 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
108 $template = CRM_Core_Smarty
::singleton();
109 $template->assign_by_ref('breadcrumb', $breadCrumb);
110 wp_set_breadcrumb($breadCrumb);
114 * Reset an additional breadcrumb tag to the existing breadcrumb
120 function resetBreadCrumb() {
122 wp_set_breadcrumb($bc);
126 * Append a string to the head of the html file
128 * @param string $head the new string to be appended
134 function addHTMLHead($head) {
135 static $registered = FALSE;
138 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
140 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
142 CRM_Core_Region
::instance('wp_head')->add(array(
147 static function _showHTMLHead() {
148 $region = CRM_Core_Region
::instance('wp_head', FALSE);
150 echo $region->render('');
157 * @param $url: string, absolute path to file
158 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
160 * Note: This function is not to be called directly
161 * @see CRM_Core_Region::render()
163 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
166 public function addScriptUrl($url, $region) {
171 * Add an inline script
173 * @param $code: string, javascript code
174 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
176 * Note: This function is not to be called directly
177 * @see CRM_Core_Region::render()
179 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
182 public function addScript($code, $region) {
189 * @param $url: string, absolute path to file
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
198 public function addStyleUrl($url, $region) {
203 * Add an inline style
205 * @param $code: string, css code
206 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
208 * Note: This function is not to be called directly
209 * @see CRM_Core_Region::render()
211 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
214 public function addStyle($code, $region) {
219 * rewrite various system urls to https
227 function mapConfigToSSL() {
229 $base_url = str_replace('http://', 'https://', $base_url);
233 * figure out the post url for the form
235 * @param mix $action the default action if one is pre-specified
237 * @return string the url to post the form
241 function postURL($action) {
242 if (!empty($action)) {
246 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
250 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
252 * @param $path string The path being linked to, such as "civicrm/add"
253 * @param $query string A query string to append to the link.
254 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
255 * Useful for links that will be displayed outside the site, such as in an
257 * @param $fragment string A fragment identifier (named anchor) to append to the link.
258 * @param $htmlize boolean whether to convert to html eqivalant
259 * @param $frontend boolean a gross joomla hack
261 * @param bool $forceBackend
263 * @return string an HTML string containing a link to the given path.
273 $forceBackend = FALSE
275 $config = CRM_Core_Config
::singleton();
277 $separator = $htmlize ?
'&' : '&';
279 $fragment = isset($fragment) ?
('#' . $fragment) : '';
281 $path = CRM_Utils_String
::stripPathChars($path);
283 //this means wp function we are trying to use is not available,
285 if (!function_exists('get_option')) {
286 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
288 if ($config->userFrameworkFrontend
) {
289 if (get_option('permalink_structure') != '') {
291 $script = get_permalink($post->ID
);
294 // when shortcode is included in page
295 // also make sure we have valid query object
297 if ( method_exists( $wp_query, 'get' ) ) {
298 if (get_query_var('page_id')) {
299 $wpPageParam = "page_id=" . get_query_var('page_id');
301 elseif (get_query_var('p')) {
302 // when shortcode is inserted in post
303 $wpPageParam = "p=" . get_query_var('p');
308 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
310 if (!isset($path) && !isset($query)) {
311 // FIXME: This short-circuited codepath is the same as the general one below, except
312 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
313 // why it's different (and I can only find two obvious use-cases for this codepath,
314 // of which at least one looks gratuitous). A more ambitious person would simply remove
316 return $base . $fragment;
319 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
323 $queryParts = array();
325 $queryParts[] = 'page=CiviCRM';
326 $queryParts[] = "q={$path}";
329 $queryParts[] = $wpPageParam;
332 $queryParts[] = $query;
335 return $base . '?' . implode($separator, $queryParts) . $fragment;
341 * @param $forceBackend
343 * @return mixed|null|string
345 private function getBaseUrl($absolute, $frontend, $forceBackend) {
346 $config = CRM_Core_Config
::singleton();
348 if (!isset($config->useFrameworkRelativeBase
)) {
349 $base = parse_url($config->userFrameworkBaseURL
);
350 $config->useFrameworkRelativeBase
= $base['path'];
353 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
355 if ((is_admin() && !$frontend) ||
$forceBackend) {
356 $base .= 'wp-admin/admin.php';
359 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
360 $base .= CIVICRM_UF_WP_BASEPAGE
;
363 elseif (isset($config->wpBasePage
)) {
364 $base .= $config->wpBasePage
;
371 * Authenticate the user against the wordpress db
373 * @param string $name the user name
374 * @param string $password the password for the above user name
376 * @param bool $loadCMSBootstrap
377 * @param null $realPath
379 * @return mixed false if no auth
381 * contactID, ufID, unique string ) if success
385 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
386 $config = CRM_Core_Config
::singleton();
388 if ($loadCMSBootstrap) {
389 $config->userSystem
->loadBootStrap($name, $password);
392 $user = wp_authenticate($name, $password);
393 if (is_a($user, 'WP_Error')) {
397 // need to change this to make sure we matched only one row
399 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
400 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
404 return array($contactID, $user->data
->ID
, mt_rand());
408 * Set a message in the UF to display to a user
410 * @param string $message the message to set
415 function setMessage($message) {
423 function loadUser( $user ) {
427 function permissionDenied() {
428 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
437 wp_redirect(wp_login_url());
440 function updateCategories() {}
443 * Get the locale set in the hosting CMS
445 * @return string with the locale or null for none
447 function getUFLocale() {
449 if (defined('ICL_LANGUAGE_CODE')) {
450 $language = ICL_LANGUAGE_CODE
;
453 // TODO: set language variable for others WordPress plugin
455 if (isset($language)) {
456 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
463 * load wordpress bootstrap
465 * @param $name string optional username for login
466 * @param $pass string optional password for login
470 function loadBootStrap($name = NULL, $pass = NULL) {
471 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
473 $cmsRootPath = $this->cmsRootPath();
475 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
478 require_once ($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php');
479 $wpUserTimezone = get_option('timezone_string');
480 if ($wpUserTimezone) {
481 date_default_timezone_set($wpUserTimezone);
482 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
492 function validInstallDir($dir) {
493 $includePath = "$dir/wp-includes";
495 @opendir
($includePath) &&
496 file_exists("$includePath/version.php")
504 * Determine the location of the CMS root.
506 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
509 * @return NULL|string
511 function cmsRootPath() {
512 $cmsRoot = $valid = NULL;
513 if (defined('CIVICRM_CMSDIR')) {
514 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
515 $cmsRoot = CIVICRM_CMSDIR
;
520 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
522 //might be windows installation.
523 $firstVar = array_shift($pathVars);
525 $cmsRoot = $firstVar;
528 //start w/ csm dir search.
529 foreach ($pathVars as $var) {
531 if ($this->validInstallDir($cmsRoot)) {
532 //stop as we found bootstrap.
539 return ($valid) ?
$cmsRoot : NULL;
548 function createUser(&$params, $mail) {
551 'user_pass' => $params['cms_pass'],
552 'user_login' => $params['cms_name'],
553 'user_email' => $params[$mail],
554 'nickname' => $params['cms_name'],
555 'role' => get_option('default_role'),
557 if (isset($params['contactID'])) {
558 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
559 if ($contactType == 'Individual') {
560 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
561 $params['contactID'], 'first_name'
563 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
564 $params['contactID'], 'last_name'
569 $uid = wp_insert_user($user_data);
572 $creds['user_login'] = $params['cms_name'];
573 $creds['user_password'] = $params['cms_pass'];
574 $creds['remember'] = TRUE;
575 $user = wp_signon($creds, FALSE);
577 wp_new_user_notification($uid, $user_data['user_pass']);
582 * Change user name in host CMS
584 * @param integer $ufID User ID in CMS
585 * @param string $ufName User name
587 function updateCMSName($ufID, $ufName) {
589 if (function_exists('wp_update_user')) {
590 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
591 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
593 $values = array ('ID' => $ufID, 'user_email' => $ufName);
595 wp_update_user( $values ) ;
603 * @param string $emailName
605 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
606 $config = CRM_Core_Config
::singleton();
608 $dao = new CRM_Core_DAO();
609 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
610 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
612 if (!empty($params['name'])) {
613 if (!validate_username($params['name'])) {
614 $errors['cms_name'] = ts("Your username contains invalid characters");
616 elseif (username_exists(sanitize_user($params['name']))) {
617 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
621 if (!empty($params['mail'])) {
622 if (!is_email($params['mail'])) {
623 $errors[$emailName] = "Your email is invaid";
625 elseif (email_exists($params['mail'])) {
626 $resetUrl = $config->userFrameworkBaseURL
. 'wp-login.php?action=lostpassword';
627 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
628 array(1 => $params['mail'], 2 => $resetUrl)
635 * check is user logged in.
637 * @return boolean true/false.
639 public function isUserLoggedIn() {
641 if (function_exists('is_user_logged_in')) {
642 $isloggedIn = is_user_logged_in();
651 function getLoggedInUserObject() {
652 if (function_exists('is_user_logged_in') &&
653 is_user_logged_in()) {
654 global $current_user;
656 return $current_user;
659 * Get currently logged in user uf id.
661 * @return int $userID logged in user uf id.
663 public function getLoggedInUfID() {
665 $current_user = $this->getLoggedInUserObject();
666 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
670 * Get currently logged in user unique identifier - this tends to be the email address or user name.
672 * @return string $userID logged in user unique identifier
674 function getLoggedInUniqueIdentifier() {
675 $user = $this->getLoggedInUserObject();
676 return $this->getUniqueIdentifierFromUserObject($user);
680 * Get User ID from UserFramework system (Joomla)
681 * @param object $user object as described by the CMS
682 * @return mixed <NULL, number>
684 function getUserIDFromUserObject($user) {
685 return !empty($user->ID
) ?
$user->ID
: NULL;
689 * Get Unique Identifier from UserFramework system (CMS)
690 * @param object $user object as described by the User Framework
691 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
694 function getUniqueIdentifierFromUserObject($user) {
695 return empty($user->user_email
) ?
NULL : $user->user_email
;
699 * Get user login URL for hosting CMS (method declared in each CMS system class)
701 * @param string $destination - if present, add destination to querystring (works for Drupal only)
703 * @return string - loginURL for the current CMS
706 public function getLoginURL($destination = '') {
707 $config = CRM_Core_Config
::singleton();
708 $loginURL = $config->userFrameworkBaseURL
;
709 $loginURL .= 'wp-login.php';
716 public function getLoginDestination(&$form) {
721 * Return the current WordPress version if relevant function exists
723 * @return string - version number
726 function getVersion() {
727 if (function_exists('get_bloginfo')) {
728 return get_bloginfo('version', 'display');
736 * get timezone as a string
737 * @return string Timezone e.g. 'America/Los_Angeles'
739 function getTimeZoneString() {
740 return get_option('timezone_string');
744 * Get Url to view user record
745 * @param integer $contactID Contact ID
749 function getUserRecordUrl($contactID) {
750 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
751 if (CRM_Core_Session
::singleton()->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))) {
752 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;