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() {
44 $this->is_drupal
= FALSE;
48 * sets the title of the page
50 * @param string $title
51 * @param null $pageTitle
53 * @paqram string $pageTitle
58 function setTitle($title, $pageTitle = NULL) {
62 if (civicrm_wp_in_civicrm()) {
63 global $civicrm_wp_title;
64 $civicrm_wp_title = $pageTitle;
65 $template = CRM_Core_Smarty
::singleton();
66 $template->assign('pageTitle', $pageTitle);
71 * Append an additional breadcrumb tag to the existing breadcrumb
75 * @internal param string $title
76 * @internal param string $url
82 function appendBreadCrumb($breadCrumbs) {
83 $breadCrumb = wp_get_breadcrumb();
85 if (is_array($breadCrumbs)) {
86 foreach ($breadCrumbs as $crumbs) {
87 if (stripos($crumbs['url'], 'id%%')) {
88 $args = array('cid', 'mid');
89 foreach ($args as $a) {
90 $val = CRM_Utils_Request
::retrieve($a, 'Positive', CRM_Core_DAO
::$_nullObject,
94 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
98 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
102 $template = CRM_Core_Smarty
::singleton();
103 $template->assign_by_ref('breadcrumb', $breadCrumb);
104 wp_set_breadcrumb($breadCrumb);
108 * Reset an additional breadcrumb tag to the existing breadcrumb
114 function resetBreadCrumb() {
116 wp_set_breadcrumb($bc);
120 * Append a string to the head of the html file
122 * @param string $head the new string to be appended
128 function addHTMLHead($head) {
129 static $registered = FALSE;
132 add_action('wp_head', array(__CLASS__
, '_showHTMLHead'));
134 add_action('admin_head', array(__CLASS__
, '_showHTMLHead'));
136 CRM_Core_Region
::instance('wp_head')->add(array(
141 static function _showHTMLHead() {
142 $region = CRM_Core_Region
::instance('wp_head', FALSE);
144 echo $region->render('');
151 * @param $url: string, absolute path to file
152 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
154 * Note: This function is not to be called directly
155 * @see CRM_Core_Region::render()
157 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
160 public function addScriptUrl($url, $region) {
165 * Add an inline script
167 * @param $code: string, javascript code
168 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
170 * Note: This function is not to be called directly
171 * @see CRM_Core_Region::render()
173 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
176 public function addScript($code, $region) {
183 * @param $url: string, absolute path to file
184 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
186 * Note: This function is not to be called directly
187 * @see CRM_Core_Region::render()
189 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
192 public function addStyleUrl($url, $region) {
197 * Add an inline style
199 * @param $code: string, css code
200 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
202 * Note: This function is not to be called directly
203 * @see CRM_Core_Region::render()
205 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
208 public function addStyle($code, $region) {
213 * rewrite various system urls to https
221 function mapConfigToSSL() {
223 $base_url = str_replace('http://', 'https://', $base_url);
227 * figure out the post url for the form
229 * @param mix $action the default action if one is pre-specified
231 * @return string the url to post the form
235 function postURL($action) {
236 if (!empty($action)) {
240 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
244 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
246 * @param $path string The path being linked to, such as "civicrm/add"
247 * @param $query string A query string to append to the link.
248 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
249 * Useful for links that will be displayed outside the site, such as in an
251 * @param $fragment string A fragment identifier (named anchor) to append to the link.
252 * @param $htmlize boolean whether to convert to html eqivalant
253 * @param $frontend boolean a gross joomla hack
255 * @param bool $forceBackend
257 * @return string an HTML string containing a link to the given path.
267 $forceBackend = FALSE
269 $config = CRM_Core_Config
::singleton();
271 $separator = $htmlize ?
'&' : '&';
273 $fragment = isset($fragment) ?
('#' . $fragment) : '';
275 $path = CRM_Utils_String
::stripPathChars($path);
277 //this means wp function we are trying to use is not available,
279 if (!function_exists('get_option')) {
280 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
282 if ($config->userFrameworkFrontend
) {
283 if (get_option('permalink_structure') != '') {
285 $script = get_permalink($post->ID
);
288 // when shortcode is included in page
289 // also make sure we have valid query object
291 if ( method_exists( $wp_query, 'get' ) ) {
292 if (get_query_var('page_id')) {
293 $wpPageParam = "page_id=" . get_query_var('page_id');
295 elseif (get_query_var('p')) {
296 // when shortcode is inserted in post
297 $wpPageParam = "p=" . get_query_var('p');
302 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
304 if (!isset($path) && !isset($query)) {
305 // FIXME: This short-circuited codepath is the same as the general one below, except
306 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
307 // why it's different (and I can only find two obvious use-cases for this codepath,
308 // of which at least one looks gratuitous). A more ambitious person would simply remove
310 return $base . $fragment;
313 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam ||
$script != '')) {
317 $queryParts = array();
319 $queryParts[] = 'page=CiviCRM';
320 $queryParts[] = "q={$path}";
323 $queryParts[] = $wpPageParam;
326 $queryParts[] = $query;
329 return $base . '?' . implode($separator, $queryParts) . $fragment;
335 * @param $forceBackend
337 * @return mixed|null|string
339 private function getBaseUrl($absolute, $frontend, $forceBackend) {
340 $config = CRM_Core_Config
::singleton();
342 if (!isset($config->useFrameworkRelativeBase
)) {
343 $base = parse_url($config->userFrameworkBaseURL
);
344 $config->useFrameworkRelativeBase
= $base['path'];
347 $base = $absolute ?
$config->userFrameworkBaseURL
: $config->useFrameworkRelativeBase
;
349 if ((is_admin() && !$frontend) ||
$forceBackend) {
350 $base .= 'wp-admin/admin.php';
353 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
354 $base .= CIVICRM_UF_WP_BASEPAGE
;
357 elseif (isset($config->wpBasePage
)) {
358 $base .= $config->wpBasePage
;
365 * Authenticate the user against the wordpress db
367 * @param string $name the user name
368 * @param string $password the password for the above user name
370 * @param bool $loadCMSBootstrap
371 * @param null $realPath
373 * @return mixed false if no auth
375 * contactID, ufID, unique string ) if success
379 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
380 $config = CRM_Core_Config
::singleton();
382 if ($loadCMSBootstrap) {
383 $config->userSystem
->loadBootStrap($name, $password);
386 $user = wp_authenticate($name, $password);
387 if (is_a($user, 'WP_Error')) {
391 // need to change this to make sure we matched only one row
393 CRM_Core_BAO_UFMatch
::synchronizeUFMatch($user->data
, $user->data
->ID
, $user->data
->user_email
, 'WordPress');
394 $contactID = CRM_Core_BAO_UFMatch
::getContactId($user->data
->ID
);
398 return array($contactID, $user->data
->ID
, mt_rand());
402 * Set a message in the UF to display to a user
404 * @param string $message the message to set
409 function setMessage($message) {
417 function loadUser( $user ) {
421 function permissionDenied() {
422 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
431 wp_redirect(wp_login_url());
434 function updateCategories() {}
437 * Get the locale set in the hosting CMS
439 * @return string with the locale or null for none
441 function getUFLocale() {
443 if (defined('ICL_LANGUAGE_CODE')) {
444 $language = ICL_LANGUAGE_CODE
;
447 // TODO: set language variable for others WordPress plugin
449 if (isset($language)) {
450 return CRM_Core_I18n_PseudoConstant
::longForShort(substr($language, 0, 2));
457 * load wordpress bootstrap
459 * @param $name string optional username for login
460 * @param $pass string optional password for login
464 function loadBootStrap($name = NULL, $pass = NULL) {
465 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
467 $cmsRootPath = $this->cmsRootPath();
469 CRM_Core_Error
::fatal("Could not find the install directory for WordPress");
472 require_once ($cmsRootPath . DIRECTORY_SEPARATOR
. 'wp-load.php');
473 $wpUserTimezone = get_option('timezone_string');
474 if ($wpUserTimezone) {
475 date_default_timezone_set($wpUserTimezone);
476 CRM_Core_Config
::singleton()->userSystem
->setMySQLTimeZone();
486 function validInstallDir($dir) {
487 $includePath = "$dir/wp-includes";
489 @opendir
($includePath) &&
490 file_exists("$includePath/version.php")
498 * Determine the location of the CMS root.
500 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
503 * @return NULL|string
505 function cmsRootPath() {
506 $cmsRoot = $valid = NULL;
507 if (defined('CIVICRM_CMSDIR')) {
508 if ($this->validInstallDir(CIVICRM_CMSDIR
)) {
509 $cmsRoot = CIVICRM_CMSDIR
;
514 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
516 //might be windows installation.
517 $firstVar = array_shift($pathVars);
519 $cmsRoot = $firstVar;
522 //start w/ csm dir search.
523 foreach ($pathVars as $var) {
525 if ($this->validInstallDir($cmsRoot)) {
526 //stop as we found bootstrap.
533 return ($valid) ?
$cmsRoot : NULL;
542 function createUser(&$params, $mail) {
545 'user_pass' => $params['cms_pass'],
546 'user_login' => $params['cms_name'],
547 'user_email' => $params[$mail],
548 'nickname' => $params['cms_name'],
549 'role' => get_option('default_role'),
551 if (isset($params['contactID'])) {
552 $contactType = CRM_Contact_BAO_Contact
::getContactType($params['contactID']);
553 if ($contactType == 'Individual') {
554 $user_data['first_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
555 $params['contactID'], 'first_name'
557 $user_data['last_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
558 $params['contactID'], 'last_name'
563 $uid = wp_insert_user($user_data);
566 $creds['user_login'] = $params['cms_name'];
567 $creds['user_password'] = $params['cms_pass'];
568 $creds['remember'] = TRUE;
569 $user = wp_signon($creds, FALSE);
571 wp_new_user_notification($uid, $user_data['user_pass']);
576 * Change user name in host CMS
578 * @param integer $ufID User ID in CMS
579 * @param string $ufName User name
581 function updateCMSName($ufID, $ufName) {
583 if (function_exists('wp_update_user')) {
584 $ufID = CRM_Utils_Type
::escape($ufID, 'Integer');
585 $ufName = CRM_Utils_Type
::escape($ufName, 'String');
587 $values = array ('ID' => $ufID, 'user_email' => $ufName);
589 wp_update_user( $values ) ;
597 * @param string $emailName
599 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
600 $config = CRM_Core_Config
::singleton();
602 $dao = new CRM_Core_DAO();
603 $name = $dao->escape(CRM_Utils_Array
::value('name', $params));
604 $email = $dao->escape(CRM_Utils_Array
::value('mail', $params));
606 if (!empty($params['name'])) {
607 if (!validate_username($params['name'])) {
608 $errors['cms_name'] = ts("Your username contains invalid characters");
610 elseif (username_exists(sanitize_user($params['name']))) {
611 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
615 if (!empty($params['mail'])) {
616 if (!is_email($params['mail'])) {
617 $errors[$emailName] = "Your email is invaid";
619 elseif (email_exists($params['mail'])) {
620 $resetUrl = $config->userFrameworkBaseURL
. 'wp-login.php?action=lostpassword';
621 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
622 array(1 => $params['mail'], 2 => $resetUrl)
629 * check is user logged in.
631 * @return boolean true/false.
633 public function isUserLoggedIn() {
635 if (function_exists('is_user_logged_in')) {
636 $isloggedIn = is_user_logged_in();
645 function getLoggedInUserObject() {
646 if (function_exists('is_user_logged_in') &&
647 is_user_logged_in()) {
648 global $current_user;
650 return $current_user;
653 * Get currently logged in user uf id.
655 * @return int $userID logged in user uf id.
657 public function getLoggedInUfID() {
659 $current_user = $this->getLoggedInUserObject();
660 return isset($current_user->ID
) ?
$current_user->ID
: NULL;
664 * Get currently logged in user unique identifier - this tends to be the email address or user name.
666 * @return string $userID logged in user unique identifier
668 function getLoggedInUniqueIdentifier() {
669 $user = $this->getLoggedInUserObject();
670 return $this->getUniqueIdentifierFromUserObject($user);
674 * Get User ID from UserFramework system (Joomla)
675 * @param object $user object as described by the CMS
676 * @return mixed <NULL, number>
678 function getUserIDFromUserObject($user) {
679 return !empty($user->ID
) ?
$user->ID
: NULL;
683 * Get Unique Identifier from UserFramework system (CMS)
684 * @param object $user object as described by the User Framework
685 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
688 function getUniqueIdentifierFromUserObject($user) {
689 return empty($user->user_email
) ?
NULL : $user->user_email
;
693 * Get user login URL for hosting CMS (method declared in each CMS system class)
695 * @param string $destination - if present, add destination to querystring (works for Drupal only)
697 * @return string - loginURL for the current CMS
700 public function getLoginURL($destination = '') {
701 $config = CRM_Core_Config
::singleton();
702 $loginURL = $config->userFrameworkBaseURL
;
703 $loginURL .= 'wp-login.php';
710 public function getLoginDestination(&$form) {
715 * Return the current WordPress version if relevant function exists
717 * @return string - version number
720 function getVersion() {
721 if (function_exists('get_bloginfo')) {
722 return get_bloginfo('version', 'display');
730 * get timezone as a string
731 * @return string Timezone e.g. 'America/Los_Angeles'
733 function getTimeZoneString() {
734 return get_option('timezone_string');
738 * Get Url to view user record
739 * @param integer $contactID Contact ID
743 function getUserRecordUrl($contactID) {
744 $uid = CRM_Core_BAO_UFMatch
::getUFId($contactID);
745 if (CRM_Core_Session
::singleton()->get('userID') == $contactID || CRM_Core_Permission
::checkAnyPerm(array('cms:administer users'))) {
746 return CRM_Core_Config
::singleton()->userFrameworkBaseURL
. "wp-admin/user-edit.php?user_id=" . $uid;