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);
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
108 public function appendBreadCrumb($breadCrumbs) {
109 $breadCrumb = wp_get_breadcrumb();
111 if (is_array($breadCrumbs)) {
112 foreach ($breadCrumbs as $crumbs) {
113 if (stripos($crumbs['url'], 'id%%')) {
114 $args = array('cid', 'mid');
115 foreach ($args as $a) {
116 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
120 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
124 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
128 $template = CRM_Core_Smarty
::singleton();
129 $template->assign_by_ref('breadcrumb', $breadCrumb);
130 wp_set_breadcrumb($breadCrumb);
134 * Reset an additional breadcrumb tag to the existing breadcrumb
139 public function resetBreadCrumb() {
141 wp_set_breadcrumb($bc);
145 * Append a string to the head of the html file
147 * @param string $head
148 * The new string to be appended.
153 public function addHTMLHead($head) {
154 static $registered = FALSE;
157 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
159 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
161 CRM_Core_Region
::instance('wp_head')->add(array(
166 public static function _showHTMLHead() {
167 $region = CRM_Core_Region
::instance('wp_head', FALSE);
169 echo $region->render('');
176 * @param $url: string, absolute path to file
178 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
180 * Note: This function is not to be called directly
181 * @see CRM_Core_Region::render()
183 * @return bool 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
194 * String, 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()
199 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
201 public function addScript($code, $region) {
208 * @param $url: string, absolute path to file
210 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
212 * Note: This function is not to be called directly
213 * @see CRM_Core_Region::render()
215 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
217 public function addStyleUrl($url, $region) {
222 * Add an inline style
224 * @param $code: string, css code
226 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
228 * Note: This function is not to be called directly
229 * @see CRM_Core_Region::render()
231 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
233 public function addStyle($code, $region) {
238 * Rewrite various system urls to https
245 public function mapConfigToSSL() {
247 $base_url = str_replace('http://', 'https://', $base_url);
251 * Figure out the post url for the form
254 * The default action if one is pre-specified.
256 * @return string the url to post the form
259 public function postURL($action) {
260 if (!empty($action)) {
264 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
268 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
271 * String The path being linked to, such as "civicrm/add".
273 * String A query string to append to the link.
275 * 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
279 * String A fragment identifier (named anchor) to append to the link.
281 * Boolean whether to convert to html eqivalant.
283 * Boolean a gross joomla hack.
285 * @param bool $forceBackend
287 * @return string 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
404 * @return mixed false if no auth
406 * contactID, ufID, unique string ) if success
409 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
410 $config = CRM_Core_Config
::singleton();
412 if ($loadCMSBootstrap) {
413 $config->userSystem
->loadBootStrap($name, $password);
416 $user = wp_authenticate($name, $password);
417 if (is_a($user, 'WP_Error')) {
421 // need to change this to make sure we matched only one row
423 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
424 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
428 return array($contactID, $user->data
->ID
, mt_rand());
432 * Set a message in the UF to display to a user
434 * @param string $message
435 * The message to set.
439 public function setMessage($message) {
447 public function loadUser($user) {
451 public function permissionDenied() {
452 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
455 public function logout() {
461 wp_redirect(wp_login_url());
464 public function updateCategories() {
468 * Get the locale set in the hosting CMS
470 * @return string with the locale or null for none
472 public function getUFLocale() {
474 if (defined('ICL_LANGUAGE_CODE')) {
475 $language = ICL_LANGUAGE_CODE
;
478 // TODO: set language variable for others WordPress plugin
480 if (isset($language)) {
481 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
489 * Load wordpress bootstrap
492 * String optional username for login.
494 * String optional password for login.
498 public function loadBootStrap($name = NULL, $pass = NULL) {
499 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
501 $cmsRootPath = $this->cmsRootPath();
503 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
506 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php';
507 $wpUserTimezone = get_option('timezone_string');
508 if ($wpUserTimezone) {
509 date_default_timezone_set($wpUserTimezone);
510 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
512 require_once $cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-includes/pluggable.php';
513 $uid = CRM_Utils_Array
::value('uid', $name);
515 $account = wp_set_current_user($uid);
516 if ($account && $account->data
->ID
) {
530 public function validInstallDir($dir) {
531 $includePath = "$dir/wp-includes";
532 if (file_exists("$includePath/version.php")) {
539 * Determine the location of the CMS root.
541 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
544 * @return NULL|string
546 public function cmsRootPath() {
547 $cmsRoot = $valid = NULL;
548 if (defined('CIVICRM_CMSDIR')) {
549 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
550 $cmsRoot = CIVICRM_CMSDIR
;
555 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
557 //might be windows installation.
558 $firstVar = array_shift($pathVars);
560 $cmsRoot = $firstVar;
563 //start w/ csm dir search.
564 foreach ($pathVars as $var) {
566 if ($this->validInstallDir($cmsRoot)) {
567 //stop as we found bootstrap.
574 return ($valid) ?
$cmsRoot : NULL;
578 * @param array $params
583 public function createUser(&$params, $mail) {
586 'user_pass' => $params['cms_pass'],
587 'user_login' => $params['cms_name'],
588 'user_email' => $params[$mail],
589 'nickname' => $params['cms_name'],
590 'role' => get_option('default_role'),
592 if (isset($params['contactID'])) {
593 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
594 if ($contactType == 'Individual') {
595 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
596 $params['contactID'], 'first_name'
598 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
599 $params['contactID'], 'last_name'
604 $uid = wp_insert_user($user_data);
607 $creds['user_login'] = $params['cms_name'];
608 $creds['user_password'] = $params['cms_pass'];
609 $creds['remember'] = TRUE;
610 $user = wp_signon($creds, FALSE);
612 wp_new_user_notification($uid, $user_data['user_pass']);
617 * Change user name in host CMS
621 * @param string $ufName
624 public function updateCMSName($ufID, $ufName) {
626 if (function_exists('wp_update_user')) {
627 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
628 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
630 $values = array('ID' => $ufID, 'user_email' => $ufName);
632 wp_update_user($values);
638 * @param array $params
640 * @param string $emailName
642 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
643 $config = CRM_Core_Config
::singleton();
645 $dao = new CRM_Core_DAO();
646 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
647 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
649 if (!empty($params['name'])) {
650 if (!validate_username($params['name'])) {
651 $errors['cms_name'] = ts("Your username contains invalid characters");
653 elseif (username_exists(sanitize_user($params['name']))) {
654 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
658 if (!empty($params['mail'])) {
659 if (!is_email($params['mail'])) {
660 $errors[$emailName] = "Your email is invaid";
662 elseif (email_exists($params['mail'])) {
663 $resetUrl = $config->userFrameworkBaseURL
. 'wp-login.php?action=lostpassword';
664 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
665 array(1 => $params['mail'], 2 => $resetUrl)
672 * Check is user logged in.
674 * @return boolean true/false.
676 public function isUserLoggedIn() {
678 if (function_exists('is_user_logged_in')) {
679 $isloggedIn = is_user_logged_in();
688 public function getLoggedInUserObject() {
689 if (function_exists('is_user_logged_in') &&
690 is_user_logged_in()) {
691 global $current_user;
693 return $current_user;
696 * Get currently logged in user uf id.
698 * @return int $userID logged in user uf id.
700 public function getLoggedInUfID() {
702 $current_user = $this->getLoggedInUserObject();
703 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
707 * Get currently logged in user unique identifier - this tends to be the email address or user name.
709 * @return string $userID 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.
720 * @return mixed <NULL, number>
722 public function getUserIDFromUserObject($user) {
723 return !empty($user->ID
) ?
$user->ID
: NULL;
727 * Get Unique Identifier from UserFramework system (CMS)
728 * @param object $user
729 * Object as described by the User Framework.
730 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
733 public function getUniqueIdentifierFromUserObject($user) {
734 return empty($user->user_email
) ?
NULL : $user->user_email
;
738 * Get user login URL for hosting CMS (method declared in each CMS system class)
740 * @param string $destination
741 * If present, add destination to querystring (works for Drupal only).
743 * @return string - loginURL for the current CMS
746 public function getLoginURL($destination = '') {
747 $config = CRM_Core_Config
::singleton();
748 $loginURL = $config->userFrameworkBaseURL
;
749 $loginURL .= 'wp-login.php';
754 * @param CRM_Core_Form $form
756 public function getLoginDestination(&$form) {
761 * Return the current WordPress version if relevant function exists
763 * @return string - version number
766 public function getVersion() {
767 if (function_exists('get_bloginfo')) {
768 return get_bloginfo('version', 'display');
776 * Get timezone as a string
777 * @return string Timezone e.g. 'America/Los_Angeles'
779 public function getTimeZoneString() {
780 return get_option('timezone_string');
784 * Get Url to view user record
785 * @param int $contactID
790 public function getUserRecordUrl($contactID) {
791 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
792 if (CRM_Core_Session
::singleton()->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))) {
793 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;