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
106 public function appendBreadCrumb($breadCrumbs) {
107 $breadCrumb = wp_get_breadcrumb();
109 if (is_array($breadCrumbs)) {
110 foreach ($breadCrumbs as $crumbs) {
111 if (stripos($crumbs['url'], 'id%%')) {
112 $args = array('cid', 'mid');
113 foreach ($args as $a) {
114 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
118 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
122 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
126 $template = CRM_Core_Smarty
::singleton();
127 $template->assign_by_ref('breadcrumb', $breadCrumb);
128 wp_set_breadcrumb($breadCrumb);
132 * Reset an additional breadcrumb tag to the existing breadcrumb
136 public function resetBreadCrumb() {
138 wp_set_breadcrumb($bc);
142 * Append a string to the head of the html file
144 * @param string $head
145 * The new string to be appended.
149 public function addHTMLHead($head) {
150 static $registered = FALSE;
153 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
155 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
157 CRM_Core_Region
::instance('wp_head')->add(array(
162 public static function _showHTMLHead() {
163 $region = CRM_Core_Region
::instance('wp_head', FALSE);
165 echo $region->render('');
172 * @param $url : string, absolute path to file
173 * @param string $region
174 * 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()
180 * 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 string $region
191 * 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()
197 * TRUE if we support this operation in this CMS, FALSE otherwise
199 public function addScript($code, $region) {
206 * @param $url : string, absolute path to file
207 * @param string $region
208 * location within the document: 'html-header', 'page-header', 'page-footer'.
210 * Note: This function is not to be called directly
211 * @see CRM_Core_Region::render()
214 * TRUE if we support this operation in this CMS, FALSE otherwise
216 public function addStyleUrl($url, $region) {
221 * Add an inline style
223 * @param $code : string, css code
224 * @param string $region
225 * location within the document: 'html-header', 'page-header', 'page-footer'.
227 * Note: This function is not to be called directly
228 * @see CRM_Core_Region::render()
231 * TRUE if we support this operation in this CMS, FALSE otherwise
233 public function addStyle($code, $region) {
238 * Rewrite various system urls to https
244 public function mapConfigToSSL() {
246 $base_url = str_replace('http://', 'https://', $base_url);
250 * Figure out the post url for the form
253 * The default action if one is pre-specified.
256 * the url to post the form
258 public function postURL($action) {
259 if (!empty($action)) {
263 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
267 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
269 * @param string $path
270 * The path being linked to, such as "civicrm/add".
271 * @param string $query
272 * A query string to append to the link.
273 * @param bool $absolute
274 * Whether to force the output to be an absolute link (beginning with http:).
275 * Useful for links that will be displayed outside the site, such as in an
277 * @param string $fragment
278 * A fragment identifier (named anchor) to append to the link.
279 * @param bool $htmlize
280 * whether to convert to html eqivalant.
281 * @param bool $frontend
282 * a gross joomla hack.
284 * @param bool $forceBackend
287 * an HTML string containing a link to the given path.
296 $forceBackend = FALSE
298 $config = CRM_Core_Config
::singleton();
300 $separator = $htmlize ?
'&' : '&';
302 $fragment = isset($fragment) ?
('#' . $fragment) : '';
304 $path = CRM_Utils_String
::stripPathChars($path);
306 //this means wp function we are trying to use is not available,
308 if (!function_exists('get_option')) {
309 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
311 if ($config->userFrameworkFrontend
) {
312 if (get_option('permalink_structure') != '') {
314 $script = get_permalink($post->ID
);
317 // when shortcode is included in page
318 // also make sure we have valid query object
320 if (method_exists($wp_query, 'get')) {
321 if (get_query_var('page_id')) {
322 $wpPageParam = "page_id=" . get_query_var('page_id');
324 elseif (get_query_var('p')) {
325 // when shortcode is inserted in post
326 $wpPageParam = "p=" . get_query_var('p');
331 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
333 if (!isset($path) && !isset($query)) {
334 // FIXME: This short-circuited codepath is the same as the general one below, except
335 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
336 // why it's different (and I can only find two obvious use-cases for this codepath,
337 // of which at least one looks gratuitous). A more ambitious person would simply remove
339 return $base . $fragment;
342 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
346 $queryParts = array();
348 $queryParts[] = 'page=CiviCRM';
349 $queryParts[] = "q={$path}";
352 $queryParts[] = $wpPageParam;
355 $queryParts[] = $query;
358 return $base . '?' . implode($separator, $queryParts) . $fragment;
364 * @param $forceBackend
366 * @return mixed|null|string
368 private function getBaseUrl($absolute, $frontend, $forceBackend) {
369 $config = CRM_Core_Config
::singleton();
371 if (!isset($config->useFrameworkRelativeBase
)) {
372 $base = parse_url($config->userFrameworkBaseURL
);
373 $config->useFrameworkRelativeBase
= $base['path'];
376 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
378 if ((is_admin() && !$frontend) ||
$forceBackend) {
379 $base .= 'wp-admin/admin.php';
382 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
383 $base .= CIVICRM_UF_WP_BASEPAGE
;
386 elseif (isset($config->wpBasePage
)) {
387 $base .= $config->wpBasePage
;
394 * Authenticate the user against the wordpress db
396 * @param string $name
398 * @param string $password
399 * The password for the above user name.
401 * @param bool $loadCMSBootstrap
402 * @param null $realPath
405 * [contactID, ufID, uniqueString] if success else false if no auth
407 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
408 $config = CRM_Core_Config
::singleton();
410 if ($loadCMSBootstrap) {
411 $config->userSystem
->loadBootStrap($name, $password);
414 $user = wp_authenticate($name, $password);
415 if (is_a($user, 'WP_Error')) {
419 // need to change this to make sure we matched only one row
421 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
422 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
426 return array($contactID, $user->data
->ID
, mt_rand());
430 * Set a message in the UF to display to a user
432 * @param string $message
433 * The message to set.
436 public function setMessage($message) {
444 public function loadUser($user) {
448 public function permissionDenied() {
449 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
452 public function logout() {
458 wp_redirect(wp_login_url());
461 public function updateCategories() {
465 * Get the locale set in the hosting CMS
468 * with the locale or null for none
470 public function getUFLocale() {
472 if (defined('ICL_LANGUAGE_CODE')) {
473 $language = ICL_LANGUAGE_CODE
;
476 // TODO: set language variable for others WordPress plugin
478 if (isset($language)) {
479 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
487 * Load wordpress bootstrap
489 * @param string $name
490 * optional username for login.
491 * @param string $pass
492 * optional password for login.
496 public function loadBootStrap($name = NULL, $pass = NULL) {
497 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
499 $cmsRootPath = $this->cmsRootPath();
501 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
504 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
505 $wpUserTimezone = get_option('timezone_string');
506 if ($wpUserTimezone) {
507 date_default_timezone_set($wpUserTimezone);
508 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
510 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
511 $uid = CRM_Utils_Array
::value('uid', $name);
513 $account = wp_set_current_user($uid);
514 if ($account && $account->data
->ID
) {
528 public function validInstallDir($dir) {
529 $includePath = "$dir/wp-includes";
530 if (file_exists("$includePath/version.php")) {
537 * Determine the location of the CMS root.
539 * @return string|NULL
540 * local file system path to CMS root, or NULL if it cannot be determined
542 public 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 public 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
617 * @param string $ufName
620 public function updateCMSName($ufID, $ufName) {
622 if (function_exists('wp_update_user')) {
623 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
624 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
626 $values = array('ID' => $ufID, 'user_email' => $ufName);
628 wp_update_user($values);
634 * @param array $params
636 * @param string $emailName
638 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
639 $config = CRM_Core_Config
::singleton();
641 $dao = new CRM_Core_DAO();
642 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
643 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
645 if (!empty($params['name'])) {
646 if (!validate_username($params['name'])) {
647 $errors['cms_name'] = ts("Your username contains invalid characters");
649 elseif (username_exists(sanitize_user($params['name']))) {
650 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
654 if (!empty($params['mail'])) {
655 if (!is_email($params['mail'])) {
656 $errors[$emailName] = "Your email is invaid";
658 elseif (email_exists($params['mail'])) {
659 $resetUrl = $config->userFrameworkBaseURL
. 'wp-login.php?action=lostpassword';
660 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
661 array(1 => $params['mail'], 2 => $resetUrl)
668 * Check is user logged in.
672 public function isUserLoggedIn() {
674 if (function_exists('is_user_logged_in')) {
675 $isloggedIn = is_user_logged_in();
684 public function getLoggedInUserObject() {
685 if (function_exists('is_user_logged_in') &&
688 global $current_user;
690 return $current_user;
694 * Get currently logged in user uf id.
697 * $userID logged in user uf id.
699 public function getLoggedInUfID() {
701 $current_user = $this->getLoggedInUserObject();
702 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
706 * Get currently logged in user unique identifier - this tends to be the email address or user name.
709 * logged in user unique identifier
711 public function getLoggedInUniqueIdentifier() {
712 $user = $this->getLoggedInUserObject();
713 return $this->getUniqueIdentifierFromUserObject($user);
717 * Get User ID from UserFramework system (Joomla)
718 * @param object $user
719 * Object as described by the CMS.
723 public function getUserIDFromUserObject($user) {
724 return !empty($user->ID
) ?
$user->ID
: NULL;
728 * Get Unique Identifier from UserFramework system (CMS)
729 * @param object $user
730 * Object as described by the User Framework.
732 * Unique identifier from the user Framework system
734 public function getUniqueIdentifierFromUserObject($user) {
735 return empty($user->user_email
) ?
NULL : $user->user_email
;
739 * Get user login URL for hosting CMS (method declared in each CMS system class)
741 * @param string $destination
742 * If present, add destination to querystring (works for Drupal only).
745 * loginURL for the current CMS
747 public function getLoginURL($destination = '') {
748 $config = CRM_Core_Config
::singleton();
749 $loginURL = $config->userFrameworkBaseURL
;
750 $loginURL .= 'wp-login.php';
755 * @param CRM_Core_Form $form
757 public function getLoginDestination(&$form) {
762 * Return the current WordPress version if relevant function exists
767 public function getVersion() {
768 if (function_exists('get_bloginfo')) {
769 return get_bloginfo('version', 'display');
777 * Get timezone as a string
779 * Timezone e.g. 'America/Los_Angeles'
781 public function getTimeZoneString() {
782 return get_option('timezone_string');
786 * Get Url to view user record
787 * @param int $contactID
792 public function getUserRecordUrl($contactID) {
793 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
794 if (CRM_Core_Session
::singleton()
795 ->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))
797 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;