Merge pull request #7151 from colemanw/CRM-17323
[civicrm-core.git] / CRM / Utils / System / WordPress.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
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 40 /**
bb3a214a 41 */
00be9182 42 public function __construct() {
4caaa696
EM
43 /**
44 * 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
45 * functions and leave the codebase oblivious to the type of CMS
46 * @deprecated
47 * @var bool
48 */
6a488035 49 $this->is_drupal = FALSE;
fe17e8d1 50 $this->is_wordpress = TRUE;
6a488035
TO
51 }
52
53 /**
17f443df 54 * @inheritDoc
6a488035 55 */
00be9182 56 public function setTitle($title, $pageTitle = NULL) {
6a488035
TO
57 if (!$pageTitle) {
58 $pageTitle = $title;
59 }
1beae3b1 60
17f443df
CW
61 // FIXME: Why is this global?
62 global $civicrm_wp_title;
63 $civicrm_wp_title = $title;
1beae3b1 64
17f443df
CW
65 // yes, set page title, depending on context
66 $context = civi_wp()->civicrm_context_get();
67 switch ($context) {
68 case 'admin':
69 case 'shortcode':
70 $template = CRM_Core_Smarty::singleton();
71 $template->assign('pageTitle', $pageTitle);
6a488035
TO
72 }
73 }
74
75 /**
17f443df 76 * @inheritDoc
6a488035 77 */
00be9182 78 public function appendBreadCrumb($breadCrumbs) {
6a488035
TO
79 $breadCrumb = wp_get_breadcrumb();
80
81 if (is_array($breadCrumbs)) {
82 foreach ($breadCrumbs as $crumbs) {
83 if (stripos($crumbs['url'], 'id%%')) {
84 $args = array('cid', 'mid');
85 foreach ($args as $a) {
86 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
87 FALSE, NULL, $_GET
88 );
89 if ($val) {
90 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
91 }
92 }
93 }
94 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
95 }
96 }
97
98 $template = CRM_Core_Smarty::singleton();
99 $template->assign_by_ref('breadcrumb', $breadCrumb);
100 wp_set_breadcrumb($breadCrumb);
101 }
102
103 /**
17f443df 104 * @inheritDoc
6a488035 105 */
00be9182 106 public function resetBreadCrumb() {
6a488035
TO
107 $bc = array();
108 wp_set_breadcrumb($bc);
109 }
110
111 /**
17f443df 112 * @inheritDoc
6a488035 113 */
00be9182 114 public function addHTMLHead($head) {
6a488035
TO
115 static $registered = FALSE;
116 if (!$registered) {
117 // front-end view
118 add_action('wp_head', array(__CLASS__, '_showHTMLHead'));
119 // back-end views
120 add_action('admin_head', array(__CLASS__, '_showHTMLHead'));
121 }
122 CRM_Core_Region::instance('wp_head')->add(array(
123 'markup' => $head,
124 ));
125 }
126
17f443df 127 /**
fe482240 128 * WP action callback.
17f443df 129 */
00be9182 130 public static function _showHTMLHead() {
6a488035
TO
131 $region = CRM_Core_Region::instance('wp_head', FALSE);
132 if ($region) {
133 echo $region->render('');
134 }
135 }
136
137 /**
17f443df 138 * @inheritDoc
6a488035 139 */
00be9182 140 public function mapConfigToSSL() {
6a488035
TO
141 global $base_url;
142 $base_url = str_replace('http://', 'https://', $base_url);
143 }
144
145 /**
17f443df 146 * @inheritDoc
6a488035 147 */
408b79bf 148 public function url(
6a488035
TO
149 $path = NULL,
150 $query = NULL,
151 $absolute = FALSE,
152 $fragment = NULL,
153 $htmlize = TRUE,
154 $frontend = FALSE,
155 $forceBackend = FALSE
156 ) {
353ffa53
TO
157 $config = CRM_Core_Config::singleton();
158 $script = '';
6a488035 159 $separator = $htmlize ? '&amp;' : '&';
353ffa53 160 $wpPageParam = '';
887f5d81 161 $fragment = isset($fragment) ? ('#' . $fragment) : '';
6a488035
TO
162
163 $path = CRM_Utils_String::stripPathChars($path);
164
165 //this means wp function we are trying to use is not available,
166 //so load bootStrap
167 if (!function_exists('get_option')) {
887f5d81 168 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
6a488035 169 }
6a488035 170 if ($config->userFrameworkFrontend) {
887f5d81 171 if (get_option('permalink_structure') != '') {
6a488035
TO
172 global $post;
173 $script = get_permalink($post->ID);
174 }
175
01aca362 176 // when shortcode is included in page
6a488035
TO
177 // also make sure we have valid query object
178 global $wp_query;
481a74f4 179 if (method_exists($wp_query, 'get')) {
6a488035 180 if (get_query_var('page_id')) {
887f5d81 181 $wpPageParam = "page_id=" . get_query_var('page_id');
6a488035
TO
182 }
183 elseif (get_query_var('p')) {
184 // when shortcode is inserted in post
887f5d81 185 $wpPageParam = "p=" . get_query_var('p');
6a488035
TO
186 }
187 }
188 }
189
887f5d81
TO
190 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
191
192 if (!isset($path) && !isset($query)) {
193 // FIXME: This short-circuited codepath is the same as the general one below, except
194 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
195 // why it's different (and I can only find two obvious use-cases for this codepath,
196 // of which at least one looks gratuitous). A more ambitious person would simply remove
197 // this code.
198 return $base . $fragment;
199 }
200
201 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam || $script != '')) {
202 $base = $script;
6a488035
TO
203 }
204
887f5d81
TO
205 $queryParts = array();
206 if (isset($path)) {
207 $queryParts[] = 'page=CiviCRM';
208 $queryParts[] = "q={$path}";
6a488035 209 }
887f5d81
TO
210 if ($wpPageParam) {
211 $queryParts[] = $wpPageParam;
212 }
213 if (isset($query)) {
214 $queryParts[] = $query;
6a488035
TO
215 }
216
887f5d81
TO
217 return $base . '?' . implode($separator, $queryParts) . $fragment;
218 }
219
bb3a214a
EM
220 /**
221 * @param $absolute
222 * @param $frontend
223 * @param $forceBackend
224 *
225 * @return mixed|null|string
226 */
887f5d81 227 private function getBaseUrl($absolute, $frontend, $forceBackend) {
353ffa53 228 $config = CRM_Core_Config::singleton();
6a488035
TO
229
230 if (!isset($config->useFrameworkRelativeBase)) {
231 $base = parse_url($config->userFrameworkBaseURL);
232 $config->useFrameworkRelativeBase = $base['path'];
233 }
234
235 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
236
237 if ((is_admin() && !$frontend) || $forceBackend) {
238 $base .= 'wp-admin/admin.php';
887f5d81 239 return $base;
6a488035
TO
240 }
241 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
242 $base .= CIVICRM_UF_WP_BASEPAGE;
887f5d81 243 return $base;
6a488035 244 }
36b820ae
DL
245 elseif (isset($config->wpBasePage)) {
246 $base .= $config->wpBasePage;
887f5d81 247 return $base;
36b820ae 248 }
887f5d81 249 return $base;
01aca362 250 }
6a488035
TO
251
252 /**
17f443df 253 * @inheritDoc
6a488035 254 */
00be9182 255 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
6a488035
TO
256 $config = CRM_Core_Config::singleton();
257
258 if ($loadCMSBootstrap) {
b6c54d16 259 $config->userSystem->loadBootStrap($name, $password);
6a488035
TO
260 }
261
262 $user = wp_authenticate($name, $password);
263 if (is_a($user, 'WP_Error')) {
264 return FALSE;
265 }
266
17f443df 267 // TODO: need to change this to make sure we matched only one row
6a488035
TO
268
269 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
270 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
271 if (!$contactID) {
272 return FALSE;
273 }
274 return array($contactID, $user->data->ID, mt_rand());
275 }
276
277 /**
17f443df 278 * FIXME: Do something
6a488035 279 */
00be9182 280 public function setMessage($message) {
6a488035
TO
281 }
282
bb3a214a 283 /**
17f443df 284 * FIXME: Do something
bb3a214a 285 */
e7292422
TO
286 public function loadUser($user) {
287 return TRUE;
6a488035
TO
288 }
289
17f443df
CW
290 /**
291 * FIXME: Use CMS-native approach
292 */
00be9182 293 public function permissionDenied() {
0499b0ad 294 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
6a488035
TO
295 }
296
17f443df
CW
297 /**
298 * @inheritDoc
299 */
00be9182 300 public function logout() {
6a488035
TO
301 // destroy session
302 if (session_id()) {
303 session_destroy();
304 }
305 wp_logout();
306 wp_redirect(wp_login_url());
307 }
308
6a488035 309 /**
17f443df 310 * @inheritDoc
6a488035 311 */
00be9182 312 public function getUFLocale() {
19780d2b
DL
313 // WPML plugin
314 if (defined('ICL_LANGUAGE_CODE')) {
315 $language = ICL_LANGUAGE_CODE;
316 }
317
318 // TODO: set language variable for others WordPress plugin
319
320 if (isset($language)) {
321 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language, 0, 2));
0db6c3e1
TO
322 }
323 else {
19780d2b
DL
324 return NULL;
325 }
6a488035
TO
326 }
327
328 /**
fe482240 329 * Load wordpress bootstrap.
6a488035 330 *
5a4f6742
CW
331 * @param string $name
332 * optional username for login.
333 * @param string $pass
334 * optional password for login.
f4aaa82a
EM
335 *
336 * @return bool
6a488035 337 */
00be9182 338 public function loadBootStrap($name = NULL, $pass = NULL) {
6a488035
TO
339 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
340
341 $cmsRootPath = $this->cmsRootPath();
342 if (!$cmsRootPath) {
343 CRM_Core_Error::fatal("Could not find the install directory for WordPress");
344 }
b299b1cc
KC
345 $path = CRM_Core_BAO_Setting::getItem('CiviCRM Preferences', 'wpLoadPhp');
346 if (!empty($path)) {
35da5d8d 347 require_once $path;
b299b1cc
KC
348 }
349 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) {
35da5d8d 350 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
b299b1cc
KC
351 }
352 else {
353 CRM_Core_Error::fatal("Could not find the bootstrap file for WordPress");
35da5d8d 354 }
6491539b
DL
355 $wpUserTimezone = get_option('timezone_string');
356 if ($wpUserTimezone) {
357 date_default_timezone_set($wpUserTimezone);
358 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
359 }
e7292422 360 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
fe1e7958 361 $uid = CRM_Utils_Array::value('uid', $name);
17763922
WA
362 if (!$uid) {
363 $name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST));
364 $pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST));
365 if ($name) {
366 $uid = wp_authenticate($name, $pass);
367 if (!$uid) {
368 if ($throwError) {
369 echo '<br />Sorry, unrecognized username or password.';
370 exit();
371 }
372 return FALSE;
373 }
374 }
375 }
fe1e7958 376 if ($uid) {
377 $account = wp_set_current_user($uid);
378 if ($account && $account->data->ID) {
379 global $user;
380 $user = $account;
381 return TRUE;
382 }
383 }
e7292422 384 return TRUE;
6a488035
TO
385 }
386
bb3a214a
EM
387 /**
388 * @param $dir
389 *
390 * @return bool
391 */
00be9182 392 public function validInstallDir($dir) {
dfbcf0b7 393 $includePath = "$dir/wp-includes";
f81c7606 394 if (file_exists("$includePath/version.php")) {
dfbcf0b7
DL
395 return TRUE;
396 }
397 return FALSE;
398 }
399
bb3a214a
EM
400 /**
401 * Determine the location of the CMS root.
402 *
72b3a70c
CW
403 * @return string|NULL
404 * local file system path to CMS root, or NULL if it cannot be determined
bb3a214a 405 */
00be9182 406 public function cmsRootPath() {
6a488035 407 $cmsRoot = $valid = NULL;
dfbcf0b7
DL
408 if (defined('CIVICRM_CMSDIR')) {
409 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
410 $cmsRoot = CIVICRM_CMSDIR;
411 $valid = TRUE;
412 }
6a488035 413 }
dfbcf0b7
DL
414 else {
415 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
6a488035 416
dfbcf0b7
DL
417 //might be windows installation.
418 $firstVar = array_shift($pathVars);
419 if ($firstVar) {
420 $cmsRoot = $firstVar;
421 }
422
423 //start w/ csm dir search.
424 foreach ($pathVars as $var) {
425 $cmsRoot .= "/$var";
426 if ($this->validInstallDir($cmsRoot)) {
427 //stop as we found bootstrap.
428 $valid = TRUE;
429 break;
430 }
6a488035
TO
431 }
432 }
433
434 return ($valid) ? $cmsRoot : NULL;
435 }
436
bb3a214a 437 /**
17f443df 438 * @inheritDoc
bb3a214a 439 */
00be9182 440 public function createUser(&$params, $mail) {
6a488035
TO
441 $user_data = array(
442 'ID' => '',
443 'user_pass' => $params['cms_pass'],
444 'user_login' => $params['cms_name'],
445 'user_email' => $params[$mail],
446 'nickname' => $params['cms_name'],
447 'role' => get_option('default_role'),
448 );
449 if (isset($params['contactID'])) {
450 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
451 if ($contactType == 'Individual') {
452 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
453 $params['contactID'], 'first_name'
454 );
455 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
456 $params['contactID'], 'last_name'
457 );
458 }
459 }
460
461 $uid = wp_insert_user($user_data);
462
463 $creds = array();
464 $creds['user_login'] = $params['cms_name'];
465 $creds['user_password'] = $params['cms_pass'];
466 $creds['remember'] = TRUE;
467 $user = wp_signon($creds, FALSE);
468
469 wp_new_user_notification($uid, $user_data['user_pass']);
470 return $uid;
471 }
472
f4aaa82a 473 /**
17f443df 474 * @inheritDoc
6a488035 475 */
00be9182 476 public function updateCMSName($ufID, $ufName) {
6a488035
TO
477 // CRM-10620
478 if (function_exists('wp_update_user')) {
353ffa53 479 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
6a488035
TO
480 $ufName = CRM_Utils_Type::escape($ufName, 'String');
481
e7292422 482 $values = array('ID' => $ufID, 'user_email' => $ufName);
481a74f4
TO
483 if ($ufID) {
484 wp_update_user($values);
6a488035
TO
485 }
486 }
487 }
488
bb3a214a 489 /**
c490a46a 490 * @param array $params
bb3a214a
EM
491 * @param $errors
492 * @param string $emailName
493 */
00be9182 494 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
6a488035
TO
495 $config = CRM_Core_Config::singleton();
496
353ffa53
TO
497 $dao = new CRM_Core_DAO();
498 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
6a488035
TO
499 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
500
a7488080 501 if (!empty($params['name'])) {
6a488035
TO
502 if (!validate_username($params['name'])) {
503 $errors['cms_name'] = ts("Your username contains invalid characters");
504 }
505 elseif (username_exists(sanitize_user($params['name']))) {
506 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
507 }
508 }
509
a7488080 510 if (!empty($params['mail'])) {
6a488035
TO
511 if (!is_email($params['mail'])) {
512 $errors[$emailName] = "Your email is invaid";
513 }
514 elseif (email_exists($params['mail'])) {
515 $resetUrl = $config->userFrameworkBaseURL . 'wp-login.php?action=lostpassword';
516 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
517 array(1 => $params['mail'], 2 => $resetUrl)
518 );
519 }
520 }
521 }
522
523 /**
17f443df 524 * @inheritDoc
6a488035
TO
525 */
526 public function isUserLoggedIn() {
527 $isloggedIn = FALSE;
528 if (function_exists('is_user_logged_in')) {
529 $isloggedIn = is_user_logged_in();
530 }
531
532 return $isloggedIn;
533 }
534
bb3a214a
EM
535 /**
536 * @return mixed
537 */
00be9182 538 public function getLoggedInUserObject() {
2b617cb0 539 if (function_exists('is_user_logged_in') &&
353ffa53
TO
540 is_user_logged_in()
541 ) {
2b617cb0
EM
542 global $current_user;
543 }
544 return $current_user;
545 }
353ffa53 546
6a488035 547 /**
17f443df 548 * @inheritDoc
6a488035
TO
549 */
550 public function getLoggedInUfID() {
551 $ufID = NULL;
2b617cb0
EM
552 $current_user = $this->getLoggedInUserObject();
553 return isset($current_user->ID) ? $current_user->ID : NULL;
554 }
555
556 /**
17f443df 557 * @inheritDoc
2b617cb0 558 */
00be9182 559 public function getLoggedInUniqueIdentifier() {
2b617cb0
EM
560 $user = $this->getLoggedInUserObject();
561 return $this->getUniqueIdentifierFromUserObject($user);
6a488035
TO
562 }
563
32998c82
EM
564 /**
565 * Get User ID from UserFramework system (Joomla)
77855840
TO
566 * @param object $user
567 * Object as described by the CMS.
72b3a70c
CW
568 *
569 * @return int|null
32998c82 570 */
00be9182 571 public function getUserIDFromUserObject($user) {
32998c82
EM
572 return !empty($user->ID) ? $user->ID : NULL;
573 }
574
2b617cb0 575 /**
17f443df 576 * @inheritDoc
2b617cb0 577 */
00be9182 578 public function getUniqueIdentifierFromUserObject($user) {
2b617cb0
EM
579 return empty($user->user_email) ? NULL : $user->user_email;
580 }
581
6a488035 582 /**
17f443df 583 * @inheritDoc
6a488035
TO
584 */
585 public function getLoginURL($destination = '') {
586 $config = CRM_Core_Config::singleton();
587 $loginURL = $config->userFrameworkBaseURL;
588 $loginURL .= 'wp-login.php';
589 return $loginURL;
590 }
591
bb3a214a 592 /**
17f443df 593 * FIXME: Do something
bb3a214a 594 */
6a488035 595 public function getLoginDestination(&$form) {
408b79bf 596 return NULL;
6a488035
TO
597 }
598
599 /**
17f443df 600 * @inheritDoc
6a488035 601 */
00be9182 602 public function getVersion() {
6a488035
TO
603 if (function_exists('get_bloginfo')) {
604 return get_bloginfo('version', 'display');
605 }
606 else {
607 return 'Unknown';
608 }
609 }
6491539b
DL
610
611 /**
17f443df 612 * @inheritDoc
6491539b 613 */
00be9182 614 public function getTimeZoneString() {
6491539b
DL
615 return get_option('timezone_string');
616 }
59f97da6
EM
617
618 /**
17f443df 619 * @inheritDoc
59f97da6 620 */
00be9182 621 public function getUserRecordUrl($contactID) {
59f97da6 622 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
353ffa53
TO
623 if (CRM_Core_Session::singleton()
624 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array('cms:administer users'))
625 ) {
59f97da6
EM
626 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
627 }
628 }
96025800 629
469d8dab
CW
630 /**
631 * Append WP js to coreResourcesList.
632 */
633 public function appendCoreResources(&$list) {
634 $list[] = 'js/crm.wordpress.js';
635 }
636
6a488035 637}