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