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