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
{
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;
54 * Sets the title of the page
56 * @param string $title
57 * @param null $pageTitle
61 public function setTitle($title, $pageTitle = NULL) {
66 // get civi-wordpress instance
69 // do we have functionality provided by plugin version 4.6+ present?
70 if (method_exists($civi, 'civicrm_context_get')) {
72 global $civicrm_wp_title;
73 $civicrm_wp_title = $pageTitle;
75 // yes, set page title, depending on context
76 $context = civi_wp()->civicrm_context_get();
80 $template = CRM_Core_Smarty
::singleton();
81 $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
147 * The new string to be appended.
152 public function addHTMLHead($head) {
153 static $registered = FALSE;
156 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
158 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
160 CRM_Core_Region
::instance('wp_head')->add(array(
165 public static function _showHTMLHead() {
166 $region = CRM_Core_Region
::instance('wp_head', FALSE);
168 echo $region->render('');
175 * @param $url: string, absolute path to file
176 * @param string $region
177 * location within the document: 'html-header', 'page-header', 'page-footer'.
179 * Note: This function is not to be called directly
180 * @see CRM_Core_Region::render()
183 * TRUE if we support this operation in this CMS, FALSE otherwise
185 public function addScriptUrl($url, $region) {
190 * Add an inline script
192 * @param $code: string, javascript code
193 * @param string $region
194 * location within the document: 'html-header', 'page-header', 'page-footer'.
196 * Note: This function is not to be called directly
197 * @see CRM_Core_Region::render()
200 * TRUE if we support this operation in this CMS, FALSE otherwise
202 public function addScript($code, $region) {
209 * @param $url: string, absolute path to file
210 * @param string $region
211 * 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()
217 * 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 string $region
228 * location within the document: 'html-header', 'page-header', 'page-footer'.
230 * Note: This function is not to be called directly
231 * @see CRM_Core_Region::render()
234 * TRUE if we support this operation in this CMS, FALSE otherwise
236 public function addStyle($code, $region) {
241 * Rewrite various system urls to https
248 public function mapConfigToSSL() {
250 $base_url = str_replace('http://', 'https://', $base_url);
254 * Figure out the post url for the form
257 * The default action if one is pre-specified.
260 * the url to post the form
263 public function postURL($action) {
264 if (!empty($action)) {
268 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
272 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
274 * @param string $path
275 * The path being linked to, such as "civicrm/add".
276 * @param string $query
277 * A query string to append to the link.
278 * @param bool $absolute
279 * Whether to force the output to be an absolute link (beginning with http:).
280 * Useful for links that will be displayed outside the site, such as in an
282 * @param string $fragment
283 * A fragment identifier (named anchor) to append to the link.
284 * @param bool $htmlize
285 * whether to convert to html eqivalant.
286 * @param bool $frontend
287 * a gross joomla hack.
289 * @param bool $forceBackend
292 * an HTML string containing a link to the given path.
301 $forceBackend = FALSE
303 $config = CRM_Core_Config
::singleton();
305 $separator = $htmlize ?
'&' : '&';
307 $fragment = isset($fragment) ?
('#' . $fragment) : '';
309 $path = CRM_Utils_String
::stripPathChars($path);
311 //this means wp function we are trying to use is not available,
313 if (!function_exists('get_option')) {
314 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
316 if ($config->userFrameworkFrontend
) {
317 if (get_option('permalink_structure') != '') {
319 $script = get_permalink($post->ID
);
322 // when shortcode is included in page
323 // also make sure we have valid query object
325 if (method_exists($wp_query, 'get')) {
326 if (get_query_var('page_id')) {
327 $wpPageParam = "page_id=" . get_query_var('page_id');
329 elseif (get_query_var('p')) {
330 // when shortcode is inserted in post
331 $wpPageParam = "p=" . get_query_var('p');
336 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
338 if (!isset($path) && !isset($query)) {
339 // FIXME: This short-circuited codepath is the same as the general one below, except
340 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
341 // why it's different (and I can only find two obvious use-cases for this codepath,
342 // of which at least one looks gratuitous). A more ambitious person would simply remove
344 return $base . $fragment;
347 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
351 $queryParts = array();
353 $queryParts[] = 'page=CiviCRM';
354 $queryParts[] = "q={$path}";
357 $queryParts[] = $wpPageParam;
360 $queryParts[] = $query;
363 return $base . '?' . implode($separator, $queryParts) . $fragment;
369 * @param $forceBackend
371 * @return mixed|null|string
373 private function getBaseUrl($absolute, $frontend, $forceBackend) {
374 $config = CRM_Core_Config
::singleton();
376 if (!isset($config->useFrameworkRelativeBase
)) {
377 $base = parse_url($config->userFrameworkBaseURL
);
378 $config->useFrameworkRelativeBase
= $base['path'];
381 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
383 if ((is_admin() && !$frontend) ||
$forceBackend) {
384 $base .= 'wp-admin/admin.php';
387 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
388 $base .= CIVICRM_UF_WP_BASEPAGE
;
391 elseif (isset($config->wpBasePage
)) {
392 $base .= $config->wpBasePage
;
399 * Authenticate the user against the wordpress db
401 * @param string $name
403 * @param string $password
404 * The password for the above user name.
406 * @param bool $loadCMSBootstrap
407 * @param null $realPath
409 * @return mixed false if no auth
411 * contactID, ufID, unique string ) if success
414 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
415 $config = CRM_Core_Config
::singleton();
417 if ($loadCMSBootstrap) {
418 $config->userSystem
->loadBootStrap($name, $password);
421 $user = wp_authenticate($name, $password);
422 if (is_a($user, 'WP_Error')) {
426 // need to change this to make sure we matched only one row
428 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
429 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
433 return array($contactID, $user->data
->ID
, mt_rand());
437 * Set a message in the UF to display to a user
439 * @param string $message
440 * The message to set.
444 public function setMessage($message) {
452 public function loadUser($user) {
456 public function permissionDenied() {
457 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
460 public function logout() {
466 wp_redirect(wp_login_url());
469 public function updateCategories() {
473 * Get the locale set in the hosting CMS
476 * with the locale or null for none
478 public function getUFLocale() {
480 if (defined('ICL_LANGUAGE_CODE')) {
481 $language = ICL_LANGUAGE_CODE
;
484 // TODO: set language variable for others WordPress plugin
486 if (isset($language)) {
487 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
495 * Load wordpress bootstrap
497 * @param string $name
498 * optional username for login.
499 * @param string $pass
500 * optional password for login.
504 public function loadBootStrap($name = NULL, $pass = NULL) {
505 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
507 $cmsRootPath = $this->cmsRootPath();
509 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
512 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
513 $wpUserTimezone = get_option('timezone_string');
514 if ($wpUserTimezone) {
515 date_default_timezone_set($wpUserTimezone);
516 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
518 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
519 $uid = CRM_Utils_Array
::value('uid', $name);
521 $account = wp_set_current_user($uid);
522 if ($account && $account->data
->ID
) {
536 public function validInstallDir($dir) {
537 $includePath = "$dir/wp-includes";
538 if (file_exists("$includePath/version.php")) {
545 * Determine the location of the CMS root.
547 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
550 * @return NULL|string
552 public function cmsRootPath() {
553 $cmsRoot = $valid = NULL;
554 if (defined('CIVICRM_CMSDIR')) {
555 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
556 $cmsRoot = CIVICRM_CMSDIR
;
561 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
563 //might be windows installation.
564 $firstVar = array_shift($pathVars);
566 $cmsRoot = $firstVar;
569 //start w/ csm dir search.
570 foreach ($pathVars as $var) {
572 if ($this->validInstallDir($cmsRoot)) {
573 //stop as we found bootstrap.
580 return ($valid) ?
$cmsRoot : NULL;
584 * @param array $params
589 public function createUser(&$params, $mail) {
592 'user_pass' => $params['cms_pass'],
593 'user_login' => $params['cms_name'],
594 'user_email' => $params[$mail],
595 'nickname' => $params['cms_name'],
596 'role' => get_option('default_role'),
598 if (isset($params['contactID'])) {
599 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
600 if ($contactType == 'Individual') {
601 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
602 $params['contactID'], 'first_name'
604 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
605 $params['contactID'], 'last_name'
610 $uid = wp_insert_user($user_data);
613 $creds['user_login'] = $params['cms_name'];
614 $creds['user_password'] = $params['cms_pass'];
615 $creds['remember'] = TRUE;
616 $user = wp_signon($creds, FALSE);
618 wp_new_user_notification($uid, $user_data['user_pass']);
623 * Change user name in host CMS
627 * @param string $ufName
630 public function updateCMSName($ufID, $ufName) {
632 if (function_exists('wp_update_user')) {
633 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
634 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
636 $values = array('ID' => $ufID, 'user_email' => $ufName);
638 wp_update_user($values);
644 * @param array $params
646 * @param string $emailName
648 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
649 $config = CRM_Core_Config
::singleton();
651 $dao = new CRM_Core_DAO();
652 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
653 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
655 if (!empty($params['name'])) {
656 if (!validate_username($params['name'])) {
657 $errors['cms_name'] = ts("Your username contains invalid characters");
659 elseif (username_exists(sanitize_user($params['name']))) {
660 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
664 if (!empty($params['mail'])) {
665 if (!is_email($params['mail'])) {
666 $errors[$emailName] = "Your email is invaid";
668 elseif (email_exists($params['mail'])) {
669 $resetUrl = $config->userFrameworkBaseURL
. 'wp-login.php?action=lostpassword';
670 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
671 array(1 => $params['mail'], 2 => $resetUrl)
678 * Check is user logged in.
682 public function isUserLoggedIn() {
684 if (function_exists('is_user_logged_in')) {
685 $isloggedIn = is_user_logged_in();
694 public function getLoggedInUserObject() {
695 if (function_exists('is_user_logged_in') &&
696 is_user_logged_in()) {
697 global $current_user;
699 return $current_user;
702 * Get currently logged in user uf id.
705 * $userID logged in user uf id.
707 public function getLoggedInUfID() {
709 $current_user = $this->getLoggedInUserObject();
710 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
714 * Get currently logged in user unique identifier - this tends to be the email address or user name.
717 * logged in user unique identifier
719 public function getLoggedInUniqueIdentifier() {
720 $user = $this->getLoggedInUserObject();
721 return $this->getUniqueIdentifierFromUserObject($user);
725 * Get User ID from UserFramework system (Joomla)
726 * @param object $user
727 * Object as described by the CMS.
728 * @return mixed <NULL, number>
730 public function getUserIDFromUserObject($user) {
731 return !empty($user->ID
) ?
$user->ID
: NULL;
735 * Get Unique Identifier from UserFramework system (CMS)
736 * @param object $user
737 * Object as described by the User Framework.
738 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
740 public function getUniqueIdentifierFromUserObject($user) {
741 return empty($user->user_email
) ?
NULL : $user->user_email
;
745 * Get user login URL for hosting CMS (method declared in each CMS system class)
747 * @param string $destination
748 * If present, add destination to querystring (works for Drupal only).
751 * loginURL for the current CMS
753 public function getLoginURL($destination = '') {
754 $config = CRM_Core_Config
::singleton();
755 $loginURL = $config->userFrameworkBaseURL
;
756 $loginURL .= 'wp-login.php';
761 * @param CRM_Core_Form $form
763 public function getLoginDestination(&$form) {
768 * Return the current WordPress version if relevant function exists
773 public function getVersion() {
774 if (function_exists('get_bloginfo')) {
775 return get_bloginfo('version', 'display');
783 * Get timezone as a string
785 * Timezone e.g. 'America/Los_Angeles'
787 public function getTimeZoneString() {
788 return get_option('timezone_string');
792 * Get Url to view user record
793 * @param int $contactID
798 public function getUserRecordUrl($contactID) {
799 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
800 if (CRM_Core_Session
::singleton()->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))) {
801 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;