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