Merge pull request #4252 from civicrm/4.4
[civicrm-core.git] / CRM / Utils / System / WordPress.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * WordPress specific stuff goes here
38 */
39 class CRM_Utils_System_WordPress extends CRM_Utils_System_Base {
40 /**
41 *
42 */
43 function __construct() {
44 /**
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
47 * @deprecated
48 * @var bool
49 */
50 $this->is_drupal = FALSE;
51 $this->is_wordpress = TRUE;
52 }
53
54 /**
55 * sets the title of the page
56 *
57 * @param string $title
58 * @param null $pageTitle
59 *
60 * @paqram string $pageTitle
61 *
62 * @return void
63 * @access public
64 */
65 function setTitle($title, $pageTitle = NULL) {
66 if (!$pageTitle) {
67 $pageTitle = $title;
68 }
69 if (civicrm_wp_in_civicrm()) {
70 global $civicrm_wp_title;
71 $civicrm_wp_title = $pageTitle;
72 $template = CRM_Core_Smarty::singleton();
73 $template->assign('pageTitle', $pageTitle);
74 }
75 }
76
77 /**
78 * Append an additional breadcrumb tag to the existing breadcrumb
79 *
80 * @param $breadCrumbs
81 *
82 * @internal param string $title
83 * @internal param string $url
84 *
85 * @return void
86 * @access public
87 * @static
88 */
89 function appendBreadCrumb($breadCrumbs) {
90 $breadCrumb = wp_get_breadcrumb();
91
92 if (is_array($breadCrumbs)) {
93 foreach ($breadCrumbs as $crumbs) {
94 if (stripos($crumbs['url'], 'id%%')) {
95 $args = array('cid', 'mid');
96 foreach ($args as $a) {
97 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
98 FALSE, NULL, $_GET
99 );
100 if ($val) {
101 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
102 }
103 }
104 }
105 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
106 }
107 }
108
109 $template = CRM_Core_Smarty::singleton();
110 $template->assign_by_ref('breadcrumb', $breadCrumb);
111 wp_set_breadcrumb($breadCrumb);
112 }
113
114 /**
115 * Reset an additional breadcrumb tag to the existing breadcrumb
116 *
117 * @return void
118 * @access public
119 * @static
120 */
121 function resetBreadCrumb() {
122 $bc = array();
123 wp_set_breadcrumb($bc);
124 }
125
126 /**
127 * Append a string to the head of the html file
128 *
129 * @param string $head the new string to be appended
130 *
131 * @return void
132 * @access public
133 * @static
134 */
135 function addHTMLHead($head) {
136 static $registered = FALSE;
137 if (!$registered) {
138 // front-end view
139 add_action('wp_head', array(__CLASS__, '_showHTMLHead'));
140 // back-end views
141 add_action('admin_head', array(__CLASS__, '_showHTMLHead'));
142 }
143 CRM_Core_Region::instance('wp_head')->add(array(
144 'markup' => $head,
145 ));
146 }
147
148 static function _showHTMLHead() {
149 $region = CRM_Core_Region::instance('wp_head', FALSE);
150 if ($region) {
151 echo $region->render('');
152 }
153 }
154
155 /**
156 * Add a script file
157 *
158 * @param $url: string, absolute path to file
159 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
160 *
161 * Note: This function is not to be called directly
162 * @see CRM_Core_Region::render()
163 *
164 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
165 * @access public
166 */
167 public function addScriptUrl($url, $region) {
168 return FALSE;
169 }
170
171 /**
172 * Add an inline script
173 *
174 * @param $code: string, javascript code
175 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
176 *
177 * Note: This function is not to be called directly
178 * @see CRM_Core_Region::render()
179 *
180 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
181 * @access public
182 */
183 public function addScript($code, $region) {
184 return FALSE;
185 }
186
187 /**
188 * Add a css file
189 *
190 * @param $url: string, absolute path to file
191 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
192 *
193 * Note: This function is not to be called directly
194 * @see CRM_Core_Region::render()
195 *
196 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
197 * @access public
198 */
199 public function addStyleUrl($url, $region) {
200 return FALSE;
201 }
202
203 /**
204 * Add an inline style
205 *
206 * @param $code: string, css code
207 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
208 *
209 * Note: This function is not to be called directly
210 * @see CRM_Core_Region::render()
211 *
212 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
213 * @access public
214 */
215 public function addStyle($code, $region) {
216 return FALSE;
217 }
218
219 /**
220 * rewrite various system urls to https
221 *
222 * @param null
223 *
224 * @return void
225 * @access public
226 * @static
227 */
228 function mapConfigToSSL() {
229 global $base_url;
230 $base_url = str_replace('http://', 'https://', $base_url);
231 }
232
233 /**
234 * figure out the post url for the form
235 *
236 * @param mix $action the default action if one is pre-specified
237 *
238 * @return string the url to post the form
239 * @access public
240 * @static
241 */
242 function postURL($action) {
243 if (!empty($action)) {
244 return $action;
245 }
246
247 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
248 }
249
250 /**
251 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
252 *
253 * @param $path string The path being linked to, such as "civicrm/add"
254 * @param $query string A query string to append to the link.
255 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
256 * Useful for links that will be displayed outside the site, such as in an
257 * RSS feed.
258 * @param $fragment string A fragment identifier (named anchor) to append to the link.
259 * @param $htmlize boolean whether to convert to html eqivalant
260 * @param $frontend boolean a gross joomla hack
261 *
262 * @param bool $forceBackend
263 *
264 * @return string an HTML string containing a link to the given path.
265 * @access public
266 */
267 function url(
268 $path = NULL,
269 $query = NULL,
270 $absolute = FALSE,
271 $fragment = NULL,
272 $htmlize = TRUE,
273 $frontend = FALSE,
274 $forceBackend = FALSE
275 ) {
276 $config = CRM_Core_Config::singleton();
277 $script = '';
278 $separator = $htmlize ? '&amp;' : '&';
279 $wpPageParam = '';
280 $fragment = isset($fragment) ? ('#' . $fragment) : '';
281
282 $path = CRM_Utils_String::stripPathChars($path);
283
284 //this means wp function we are trying to use is not available,
285 //so load bootStrap
286 if (!function_exists('get_option')) {
287 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
288 }
289 if ($config->userFrameworkFrontend) {
290 if (get_option('permalink_structure') != '') {
291 global $post;
292 $script = get_permalink($post->ID);
293 }
294
295 // when shortcode is included in page
296 // also make sure we have valid query object
297 global $wp_query;
298 if ( method_exists( $wp_query, 'get' ) ) {
299 if (get_query_var('page_id')) {
300 $wpPageParam = "page_id=" . get_query_var('page_id');
301 }
302 elseif (get_query_var('p')) {
303 // when shortcode is inserted in post
304 $wpPageParam = "p=" . get_query_var('p');
305 }
306 }
307 }
308
309 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
310
311 if (!isset($path) && !isset($query)) {
312 // FIXME: This short-circuited codepath is the same as the general one below, except
313 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
314 // why it's different (and I can only find two obvious use-cases for this codepath,
315 // of which at least one looks gratuitous). A more ambitious person would simply remove
316 // this code.
317 return $base . $fragment;
318 }
319
320 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam || $script != '')) {
321 $base = $script;
322 }
323
324 $queryParts = array();
325 if (isset($path)) {
326 $queryParts[] = 'page=CiviCRM';
327 $queryParts[] = "q={$path}";
328 }
329 if ($wpPageParam) {
330 $queryParts[] = $wpPageParam;
331 }
332 if (isset($query)) {
333 $queryParts[] = $query;
334 }
335
336 return $base . '?' . implode($separator, $queryParts) . $fragment;
337 }
338
339 /**
340 * @param $absolute
341 * @param $frontend
342 * @param $forceBackend
343 *
344 * @return mixed|null|string
345 */
346 private function getBaseUrl($absolute, $frontend, $forceBackend) {
347 $config = CRM_Core_Config::singleton();
348
349 if (!isset($config->useFrameworkRelativeBase)) {
350 $base = parse_url($config->userFrameworkBaseURL);
351 $config->useFrameworkRelativeBase = $base['path'];
352 }
353
354 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
355
356 if ((is_admin() && !$frontend) || $forceBackend) {
357 $base .= 'wp-admin/admin.php';
358 return $base;
359 }
360 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
361 $base .= CIVICRM_UF_WP_BASEPAGE;
362 return $base;
363 }
364 elseif (isset($config->wpBasePage)) {
365 $base .= $config->wpBasePage;
366 return $base;
367 }
368 return $base;
369 }
370
371 /**
372 * Authenticate the user against the wordpress db
373 *
374 * @param string $name the user name
375 * @param string $password the password for the above user name
376 *
377 * @param bool $loadCMSBootstrap
378 * @param null $realPath
379 *
380 * @return mixed false if no auth
381 * array(
382 * contactID, ufID, unique string ) if success
383 * @access public
384 * @static
385 */
386 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
387 $config = CRM_Core_Config::singleton();
388
389 if ($loadCMSBootstrap) {
390 $config->userSystem->loadBootStrap($name, $password);
391 }
392
393 $user = wp_authenticate($name, $password);
394 if (is_a($user, 'WP_Error')) {
395 return FALSE;
396 }
397
398 // need to change this to make sure we matched only one row
399
400 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
401 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
402 if (!$contactID) {
403 return FALSE;
404 }
405 return array($contactID, $user->data->ID, mt_rand());
406 }
407
408 /**
409 * Set a message in the UF to display to a user
410 *
411 * @param string $message the message to set
412 *
413 * @access public
414 * @static
415 */
416 function setMessage($message) {
417 }
418
419 /**
420 * @param $user
421 *
422 * @return bool
423 */
424 function loadUser( $user ) {
425 return true;
426 }
427
428 function permissionDenied() {
429 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
430 }
431
432 function logout() {
433 // destroy session
434 if (session_id()) {
435 session_destroy();
436 }
437 wp_logout();
438 wp_redirect(wp_login_url());
439 }
440
441 function updateCategories() {}
442
443 /**
444 * Get the locale set in the hosting CMS
445 *
446 * @return string with the locale or null for none
447 */
448 function getUFLocale() {
449 // WPML plugin
450 if (defined('ICL_LANGUAGE_CODE')) {
451 $language = ICL_LANGUAGE_CODE;
452 }
453
454 // TODO: set language variable for others WordPress plugin
455
456 if (isset($language)) {
457 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language, 0, 2));
458 } else {
459 return NULL;
460 }
461 }
462
463 /**
464 * load wordpress bootstrap
465 *
466 * @param $name string optional username for login
467 * @param $pass string optional password for login
468 *
469 * @return bool
470 */
471 function loadBootStrap($name = NULL, $pass = NULL) {
472 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
473
474 $cmsRootPath = $this->cmsRootPath();
475 if (!$cmsRootPath) {
476 CRM_Core_Error::fatal("Could not find the install directory for WordPress");
477 }
478
479 require_once ($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php');
480 $wpUserTimezone = get_option('timezone_string');
481 if ($wpUserTimezone) {
482 date_default_timezone_set($wpUserTimezone);
483 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
484 }
485 require_once ($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php');
486 $uid = CRM_Utils_Array::value('uid', $name);
487 if ($uid) {
488 $account = wp_set_current_user($uid);
489 if ($account && $account->data->ID) {
490 global $user;
491 $user = $account;
492 return TRUE;
493 }
494 }
495 return true;
496 }
497
498 /**
499 * @param $dir
500 *
501 * @return bool
502 */
503 function validInstallDir($dir) {
504 $includePath = "$dir/wp-includes";
505 if (
506 @opendir($includePath) &&
507 file_exists("$includePath/version.php")
508 ) {
509 return TRUE;
510 }
511 return FALSE;
512 }
513
514 /**
515 * Determine the location of the CMS root.
516 *
517 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
518 */
519 /**
520 * @return NULL|string
521 */
522 function cmsRootPath() {
523 $cmsRoot = $valid = NULL;
524 if (defined('CIVICRM_CMSDIR')) {
525 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
526 $cmsRoot = CIVICRM_CMSDIR;
527 $valid = TRUE;
528 }
529 }
530 else {
531 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
532
533 //might be windows installation.
534 $firstVar = array_shift($pathVars);
535 if ($firstVar) {
536 $cmsRoot = $firstVar;
537 }
538
539 //start w/ csm dir search.
540 foreach ($pathVars as $var) {
541 $cmsRoot .= "/$var";
542 if ($this->validInstallDir($cmsRoot)) {
543 //stop as we found bootstrap.
544 $valid = TRUE;
545 break;
546 }
547 }
548 }
549
550 return ($valid) ? $cmsRoot : NULL;
551 }
552
553 /**
554 * @param $params
555 * @param $mail
556 *
557 * @return mixed
558 */
559 function createUser(&$params, $mail) {
560 $user_data = array(
561 'ID' => '',
562 'user_pass' => $params['cms_pass'],
563 'user_login' => $params['cms_name'],
564 'user_email' => $params[$mail],
565 'nickname' => $params['cms_name'],
566 'role' => get_option('default_role'),
567 );
568 if (isset($params['contactID'])) {
569 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
570 if ($contactType == 'Individual') {
571 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
572 $params['contactID'], 'first_name'
573 );
574 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
575 $params['contactID'], 'last_name'
576 );
577 }
578 }
579
580 $uid = wp_insert_user($user_data);
581
582 $creds = array();
583 $creds['user_login'] = $params['cms_name'];
584 $creds['user_password'] = $params['cms_pass'];
585 $creds['remember'] = TRUE;
586 $user = wp_signon($creds, FALSE);
587
588 wp_new_user_notification($uid, $user_data['user_pass']);
589 return $uid;
590 }
591
592 /**
593 * Change user name in host CMS
594 *
595 * @param integer $ufID User ID in CMS
596 * @param string $ufName User name
597 */
598 function updateCMSName($ufID, $ufName) {
599 // CRM-10620
600 if (function_exists('wp_update_user')) {
601 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
602 $ufName = CRM_Utils_Type::escape($ufName, 'String');
603
604 $values = array ('ID' => $ufID, 'user_email' => $ufName);
605 if( $ufID ) {
606 wp_update_user( $values ) ;
607 }
608 }
609 }
610
611 /**
612 * @param $params
613 * @param $errors
614 * @param string $emailName
615 */
616 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
617 $config = CRM_Core_Config::singleton();
618
619 $dao = new CRM_Core_DAO();
620 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
621 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
622
623 if (!empty($params['name'])) {
624 if (!validate_username($params['name'])) {
625 $errors['cms_name'] = ts("Your username contains invalid characters");
626 }
627 elseif (username_exists(sanitize_user($params['name']))) {
628 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
629 }
630 }
631
632 if (!empty($params['mail'])) {
633 if (!is_email($params['mail'])) {
634 $errors[$emailName] = "Your email is invaid";
635 }
636 elseif (email_exists($params['mail'])) {
637 $resetUrl = $config->userFrameworkBaseURL . 'wp-login.php?action=lostpassword';
638 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
639 array(1 => $params['mail'], 2 => $resetUrl)
640 );
641 }
642 }
643 }
644
645 /**
646 * check is user logged in.
647 *
648 * @return boolean true/false.
649 */
650 public function isUserLoggedIn() {
651 $isloggedIn = FALSE;
652 if (function_exists('is_user_logged_in')) {
653 $isloggedIn = is_user_logged_in();
654 }
655
656 return $isloggedIn;
657 }
658
659 /**
660 * @return mixed
661 */
662 function getLoggedInUserObject() {
663 if (function_exists('is_user_logged_in') &&
664 is_user_logged_in()) {
665 global $current_user;
666 }
667 return $current_user;
668 }
669 /**
670 * Get currently logged in user uf id.
671 *
672 * @return int $userID logged in user uf id.
673 */
674 public function getLoggedInUfID() {
675 $ufID = NULL;
676 $current_user = $this->getLoggedInUserObject();
677 return isset($current_user->ID) ? $current_user->ID : NULL;
678 }
679
680 /**
681 * Get currently logged in user unique identifier - this tends to be the email address or user name.
682 *
683 * @return string $userID logged in user unique identifier
684 */
685 function getLoggedInUniqueIdentifier() {
686 $user = $this->getLoggedInUserObject();
687 return $this->getUniqueIdentifierFromUserObject($user);
688 }
689
690 /**
691 * Get User ID from UserFramework system (Joomla)
692 * @param object $user object as described by the CMS
693 * @return mixed <NULL, number>
694 */
695 function getUserIDFromUserObject($user) {
696 return !empty($user->ID) ? $user->ID : NULL;
697 }
698
699 /**
700 * Get Unique Identifier from UserFramework system (CMS)
701 * @param object $user object as described by the User Framework
702 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
703 *
704 */
705 function getUniqueIdentifierFromUserObject($user) {
706 return empty($user->user_email) ? NULL : $user->user_email;
707 }
708
709 /**
710 * Get user login URL for hosting CMS (method declared in each CMS system class)
711 *
712 * @param string $destination - if present, add destination to querystring (works for Drupal only)
713 *
714 * @return string - loginURL for the current CMS
715 *
716 */
717 public function getLoginURL($destination = '') {
718 $config = CRM_Core_Config::singleton();
719 $loginURL = $config->userFrameworkBaseURL;
720 $loginURL .= 'wp-login.php';
721 return $loginURL;
722 }
723
724 /**
725 * @param $form
726 */
727 public function getLoginDestination(&$form) {
728 return;
729 }
730
731 /**
732 * Return the current WordPress version if relevant function exists
733 *
734 * @return string - version number
735 *
736 */
737 function getVersion() {
738 if (function_exists('get_bloginfo')) {
739 return get_bloginfo('version', 'display');
740 }
741 else {
742 return 'Unknown';
743 }
744 }
745
746 /**
747 * get timezone as a string
748 * @return string Timezone e.g. 'America/Los_Angeles'
749 */
750 function getTimeZoneString() {
751 return get_option('timezone_string');
752 }
753
754 /**
755 * Get Url to view user record
756 * @param integer $contactID Contact ID
757 *
758 * @return string
759 */
760 function getUserRecordUrl($contactID) {
761 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
762 if (CRM_Core_Session::singleton()->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array('cms:administer users'))) {
763 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
764 }
765 }
766 }
767