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