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
63 function setTitle($title, $pageTitle = NULL) {
68 // get civi-wordpress instance
71 // do we have functionality provided by plugin version 4.6+ present?
72 if (method_exists($civi, 'civicrm_context_get')) {
74 global $civicrm_wp_title;
75 $civicrm_wp_title = $pageTitle;
77 // yes, set page title, depending on context
78 $context = civi_wp()->civicrm_context_get();
82 $template = CRM_Core_Smarty
::singleton();
83 $template->assign('pageTitle', $pageTitle);
86 } elseif (civicrm_wp_in_civicrm()) {
88 // legacy pre-4.6 behaviour
89 global $civicrm_wp_title;
90 $civicrm_wp_title = $pageTitle;
91 $template = CRM_Core_Smarty
::singleton();
92 $template->assign('pageTitle', $pageTitle);
98 * Append an additional breadcrumb tag to the existing breadcrumb
100 * @param $breadCrumbs
102 * @internal param string $title
103 * @internal param string $url
109 function appendBreadCrumb($breadCrumbs) {
110 $breadCrumb = wp_get_breadcrumb();
112 if (is_array($breadCrumbs)) {
113 foreach ($breadCrumbs as $crumbs) {
114 if (stripos($crumbs['url'], 'id%%')) {
115 $args = array('cid', 'mid');
116 foreach ($args as $a) {
117 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
121 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
125 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
129 $template = CRM_Core_Smarty
::singleton();
130 $template->assign_by_ref('breadcrumb', $breadCrumb);
131 wp_set_breadcrumb($breadCrumb);
135 * Reset an additional breadcrumb tag to the existing breadcrumb
141 function resetBreadCrumb() {
143 wp_set_breadcrumb($bc);
147 * Append a string to the head of the html file
149 * @param string $head the new string to be appended
155 function addHTMLHead($head) {
156 static $registered = FALSE;
159 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
161 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
163 CRM_Core_Region
::instance('wp_head')->add(array(
168 static function _showHTMLHead() {
169 $region = CRM_Core_Region
::instance('wp_head', FALSE);
171 echo $region->render('');
178 * @param $url: string, absolute path to file
179 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
181 * Note: This function is not to be called directly
182 * @see CRM_Core_Region::render()
184 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
187 public function addScriptUrl($url, $region) {
192 * Add an inline script
194 * @param $code: string, javascript code
195 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
197 * Note: This function is not to be called directly
198 * @see CRM_Core_Region::render()
200 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
203 public function addScript($code, $region) {
210 * @param $url: string, absolute path to file
211 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
213 * Note: This function is not to be called directly
214 * @see CRM_Core_Region::render()
216 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
219 public function addStyleUrl($url, $region) {
224 * Add an inline style
226 * @param $code: string, css code
227 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
229 * Note: This function is not to be called directly
230 * @see CRM_Core_Region::render()
232 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
235 public function addStyle($code, $region) {
240 * Rewrite various system urls to https
248 function mapConfigToSSL() {
250 $base_url = str_replace('http://', 'https://', $base_url);
254 * Figure out the post url for the form
256 * @param mix $action the default action if one is pre-specified
258 * @return string the url to post the form
262 function postURL($action) {
263 if (!empty($action)) {
267 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
271 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
273 * @param $path string The path being linked to, such as "civicrm/add"
274 * @param $query string A query string to append to the link.
275 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
276 * Useful for links that will be displayed outside the site, such as in an
278 * @param $fragment string A fragment identifier (named anchor) to append to the link.
279 * @param $htmlize boolean whether to convert to html eqivalant
280 * @param $frontend boolean a gross joomla hack
282 * @param bool $forceBackend
284 * @return string an HTML string containing a link to the given path.
294 $forceBackend = FALSE
296 $config = CRM_Core_Config
::singleton();
298 $separator = $htmlize ?
'&' : '&';
300 $fragment = isset($fragment) ?
('#' . $fragment) : '';
302 $path = CRM_Utils_String
::stripPathChars($path);
304 //this means wp function we are trying to use is not available,
306 if (!function_exists('get_option')) {
307 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
309 if ($config->userFrameworkFrontend
) {
310 if (get_option('permalink_structure') != '') {
312 $script = get_permalink($post->ID
);
315 // when shortcode is included in page
316 // also make sure we have valid query object
318 if ( method_exists( $wp_query, 'get' ) ) {
319 if (get_query_var('page_id')) {
320 $wpPageParam = "page_id=" . get_query_var('page_id');
322 elseif (get_query_var('p')) {
323 // when shortcode is inserted in post
324 $wpPageParam = "p=" . get_query_var('p');
329 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
331 if (!isset($path) && !isset($query)) {
332 // FIXME: This short-circuited codepath is the same as the general one below, except
333 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
334 // why it's different (and I can only find two obvious use-cases for this codepath,
335 // of which at least one looks gratuitous). A more ambitious person would simply remove
337 return $base . $fragment;
340 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
344 $queryParts = array();
346 $queryParts[] = 'page=CiviCRM';
347 $queryParts[] = "q={$path}";
350 $queryParts[] = $wpPageParam;
353 $queryParts[] = $query;
356 return $base . '?' . implode($separator, $queryParts) . $fragment;
362 * @param $forceBackend
364 * @return mixed|null|string
366 private function getBaseUrl($absolute, $frontend, $forceBackend) {
367 $config = CRM_Core_Config
::singleton();
369 if (!isset($config->useFrameworkRelativeBase
)) {
370 $base = parse_url($config->userFrameworkBaseURL
);
371 $config->useFrameworkRelativeBase
= $base['path'];
374 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
376 if ((is_admin() && !$frontend) ||
$forceBackend) {
377 $base .= 'wp-admin/admin.php';
380 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
381 $base .= CIVICRM_UF_WP_BASEPAGE
;
384 elseif (isset($config->wpBasePage
)) {
385 $base .= $config->wpBasePage
;
392 * Authenticate the user against the wordpress db
394 * @param string $name the user name
395 * @param string $password the password for the above user name
397 * @param bool $loadCMSBootstrap
398 * @param null $realPath
400 * @return mixed false if no auth
402 * contactID, ufID, unique string ) if success
406 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
407 $config = CRM_Core_Config
::singleton();
409 if ($loadCMSBootstrap) {
410 $config->userSystem
->loadBootStrap($name, $password);
413 $user = wp_authenticate($name, $password);
414 if (is_a($user, 'WP_Error')) {
418 // need to change this to make sure we matched only one row
420 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
421 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
425 return array($contactID, $user->data
->ID
, mt_rand());
429 * Set a message in the UF to display to a user
431 * @param string $message the message to set
436 function setMessage($message) {
444 function loadUser( $user ) {
448 function permissionDenied() {
449 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
458 wp_redirect(wp_login_url());
461 function updateCategories() {}
464 * Get the locale set in the hosting CMS
466 * @return string with the locale or null for none
468 function getUFLocale() {
470 if (defined('ICL_LANGUAGE_CODE')) {
471 $language = ICL_LANGUAGE_CODE
;
474 // TODO: set language variable for others WordPress plugin
476 if (isset($language)) {
477 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
484 * Load wordpress bootstrap
486 * @param $name string optional username for login
487 * @param $pass string optional password for login
491 function loadBootStrap($name = NULL, $pass = NULL) {
492 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
494 $cmsRootPath = $this->cmsRootPath();
496 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
499 require_once ($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php');
500 $wpUserTimezone = get_option('timezone_string');
501 if ($wpUserTimezone) {
502 date_default_timezone_set($wpUserTimezone);
503 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
505 require_once ($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php');
506 $uid = CRM_Utils_Array
::value('uid', $name);
508 $account = wp_set_current_user($uid);
509 if ($account && $account->data
->ID
) {
523 function validInstallDir($dir) {
524 $includePath = "$dir/wp-includes";
526 @opendir
($includePath) &&
527 file_exists("$includePath/version.php")
535 * Determine the location of the CMS root.
537 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
540 * @return NULL|string
542 function cmsRootPath() {
543 $cmsRoot = $valid = NULL;
544 if (defined('CIVICRM_CMSDIR')) {
545 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
546 $cmsRoot = CIVICRM_CMSDIR
;
551 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
553 //might be windows installation.
554 $firstVar = array_shift($pathVars);
556 $cmsRoot = $firstVar;
559 //start w/ csm dir search.
560 foreach ($pathVars as $var) {
562 if ($this->validInstallDir($cmsRoot)) {
563 //stop as we found bootstrap.
570 return ($valid) ?
$cmsRoot : NULL;
574 * @param array $params
579 function createUser(&$params, $mail) {
582 'user_pass' => $params['cms_pass'],
583 'user_login' => $params['cms_name'],
584 'user_email' => $params[$mail],
585 'nickname' => $params['cms_name'],
586 'role' => get_option('default_role'),
588 if (isset($params['contactID'])) {
589 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
590 if ($contactType == 'Individual') {
591 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
592 $params['contactID'], 'first_name'
594 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
595 $params['contactID'], 'last_name'
600 $uid = wp_insert_user($user_data);
603 $creds['user_login'] = $params['cms_name'];
604 $creds['user_password'] = $params['cms_pass'];
605 $creds['remember'] = TRUE;
606 $user = wp_signon($creds, FALSE);
608 wp_new_user_notification($uid, $user_data['user_pass']);
613 * Change user name in host CMS
615 * @param integer $ufID User ID in CMS
616 * @param string $ufName User name
618 function updateCMSName($ufID, $ufName) {
620 if (function_exists('wp_update_user')) {
621 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
622 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
624 $values = array ('ID' => $ufID, 'user_email' => $ufName);
626 wp_update_user( $values ) ;
632 * @param array $params
634 * @param string $emailName
636 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
637 $config = CRM_Core_Config
::singleton();
639 $dao = new CRM_Core_DAO();
640 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
641 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
643 if (!empty($params['name'])) {
644 if (!validate_username($params['name'])) {
645 $errors['cms_name'] = ts("Your username contains invalid characters");
647 elseif (username_exists(sanitize_user($params['name']))) {
648 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
652 if (!empty($params['mail'])) {
653 if (!is_email($params['mail'])) {
654 $errors[$emailName] = "Your email is invaid";
656 elseif (email_exists($params['mail'])) {
657 $resetUrl = $config->userFrameworkBaseURL
. 'wp-login.php?action=lostpassword';
658 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
659 array(1 => $params['mail'], 2 => $resetUrl)
666 * Check is user logged in.
668 * @return boolean true/false.
670 public function isUserLoggedIn() {
672 if (function_exists('is_user_logged_in')) {
673 $isloggedIn = is_user_logged_in();
682 function getLoggedInUserObject() {
683 if (function_exists('is_user_logged_in') &&
684 is_user_logged_in()) {
685 global $current_user;
687 return $current_user;
690 * Get currently logged in user uf id.
692 * @return int $userID logged in user uf id.
694 public function getLoggedInUfID() {
696 $current_user = $this->getLoggedInUserObject();
697 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
701 * Get currently logged in user unique identifier - this tends to be the email address or user name.
703 * @return string $userID logged in user unique identifier
705 function getLoggedInUniqueIdentifier() {
706 $user = $this->getLoggedInUserObject();
707 return $this->getUniqueIdentifierFromUserObject($user);
711 * Get User ID from UserFramework system (Joomla)
712 * @param object $user object as described by the CMS
713 * @return mixed <NULL, number>
715 function getUserIDFromUserObject($user) {
716 return !empty($user->ID
) ?
$user->ID
: NULL;
720 * Get Unique Identifier from UserFramework system (CMS)
721 * @param object $user object as described by the User Framework
722 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
725 function getUniqueIdentifierFromUserObject($user) {
726 return empty($user->user_email
) ?
NULL : $user->user_email
;
730 * Get user login URL for hosting CMS (method declared in each CMS system class)
732 * @param string $destination - if present, add destination to querystring (works for Drupal only)
734 * @return string - loginURL for the current CMS
737 public function getLoginURL($destination = '') {
738 $config = CRM_Core_Config
::singleton();
739 $loginURL = $config->userFrameworkBaseURL
;
740 $loginURL .= 'wp-login.php';
745 * @param CRM_Core_Form $form
747 public function getLoginDestination(&$form) {
752 * Return the current WordPress version if relevant function exists
754 * @return string - version number
757 function getVersion() {
758 if (function_exists('get_bloginfo')) {
759 return get_bloginfo('version', 'display');
767 * Get timezone as a string
768 * @return string Timezone e.g. 'America/Los_Angeles'
770 function getTimeZoneString() {
771 return get_option('timezone_string');
775 * Get Url to view user record
776 * @param integer $contactID Contact ID
780 function getUserRecordUrl($contactID) {
781 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
782 if (CRM_Core_Session
::singleton()->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))) {
783 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;