Merge pull request #6050 from eileenmcnaughton/CRM-16717
[civicrm-core.git] / CRM / Utils / System / WordPress.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 public function __construct() {
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 */
49 $this->is_drupal = FALSE;
50 $this->is_wordpress = TRUE;
51 }
52
53 /**
54 * @inheritDoc
55 */
56 public function setTitle($title, $pageTitle = NULL) {
57 if (!$pageTitle) {
58 $pageTitle = $title;
59 }
60
61 // FIXME: Why is this global?
62 global $civicrm_wp_title;
63 $civicrm_wp_title = $title;
64
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);
72 }
73 }
74
75 /**
76 * @inheritDoc
77 */
78 public function appendBreadCrumb($breadCrumbs) {
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 /**
104 * @inheritDoc
105 */
106 public function resetBreadCrumb() {
107 $bc = array();
108 wp_set_breadcrumb($bc);
109 }
110
111 /**
112 * @inheritDoc
113 */
114 public function addHTMLHead($head) {
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
127 /**
128 * WP action callback.
129 */
130 public static function _showHTMLHead() {
131 $region = CRM_Core_Region::instance('wp_head', FALSE);
132 if ($region) {
133 echo $region->render('');
134 }
135 }
136
137 /**
138 * @inheritDoc
139 */
140 public function mapConfigToSSL() {
141 global $base_url;
142 $base_url = str_replace('http://', 'https://', $base_url);
143 }
144
145 /**
146 * @inheritDoc
147 */
148 public function url(
149 $path = NULL,
150 $query = NULL,
151 $absolute = FALSE,
152 $fragment = NULL,
153 $htmlize = TRUE,
154 $frontend = FALSE,
155 $forceBackend = FALSE
156 ) {
157 $config = CRM_Core_Config::singleton();
158 $script = '';
159 $separator = $htmlize ? '&amp;' : '&';
160 $wpPageParam = '';
161 $fragment = isset($fragment) ? ('#' . $fragment) : '';
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')) {
168 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
169 }
170 if ($config->userFrameworkFrontend) {
171 if (get_option('permalink_structure') != '') {
172 global $post;
173 $script = get_permalink($post->ID);
174 }
175
176 // when shortcode is included in page
177 // also make sure we have valid query object
178 global $wp_query;
179 if (method_exists($wp_query, 'get')) {
180 if (get_query_var('page_id')) {
181 $wpPageParam = "page_id=" . get_query_var('page_id');
182 }
183 elseif (get_query_var('p')) {
184 // when shortcode is inserted in post
185 $wpPageParam = "p=" . get_query_var('p');
186 }
187 }
188 }
189
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;
203 }
204
205 $queryParts = array();
206 if (isset($path)) {
207 $queryParts[] = 'page=CiviCRM';
208 $queryParts[] = "q={$path}";
209 }
210 if ($wpPageParam) {
211 $queryParts[] = $wpPageParam;
212 }
213 if (isset($query)) {
214 $queryParts[] = $query;
215 }
216
217 return $base . '?' . implode($separator, $queryParts) . $fragment;
218 }
219
220 /**
221 * @param $absolute
222 * @param $frontend
223 * @param $forceBackend
224 *
225 * @return mixed|null|string
226 */
227 private function getBaseUrl($absolute, $frontend, $forceBackend) {
228 $config = CRM_Core_Config::singleton();
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';
239 return $base;
240 }
241 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
242 $base .= CIVICRM_UF_WP_BASEPAGE;
243 return $base;
244 }
245 elseif (isset($config->wpBasePage)) {
246 $base .= $config->wpBasePage;
247 return $base;
248 }
249 return $base;
250 }
251
252 /**
253 * @inheritDoc
254 */
255 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
256 $config = CRM_Core_Config::singleton();
257
258 if ($loadCMSBootstrap) {
259 $config->userSystem->loadBootStrap($name, $password);
260 }
261
262 $user = wp_authenticate($name, $password);
263 if (is_a($user, 'WP_Error')) {
264 return FALSE;
265 }
266
267 // TODO: need to change this to make sure we matched only one row
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 /**
278 * FIXME: Do something
279 */
280 public function setMessage($message) {
281 }
282
283 /**
284 * FIXME: Do something
285 */
286 public function loadUser($user) {
287 return TRUE;
288 }
289
290 /**
291 * FIXME: Use CMS-native approach
292 */
293 public function permissionDenied() {
294 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
295 }
296
297 /**
298 * @inheritDoc
299 */
300 public function logout() {
301 // destroy session
302 if (session_id()) {
303 session_destroy();
304 }
305 wp_logout();
306 wp_redirect(wp_login_url());
307 }
308
309 /**
310 * @inheritDoc
311 */
312 public function getUFLocale() {
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));
322 }
323 else {
324 return NULL;
325 }
326 }
327
328 /**
329 * Load wordpress bootstrap.
330 *
331 * @param string $name
332 * optional username for login.
333 * @param string $pass
334 * optional password for login.
335 *
336 * @return bool
337 */
338 public function loadBootStrap($name = NULL, $pass = NULL) {
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 }
345 $path = CRM_Core_BAO_Setting::getItem('CiviCRM Preferences', 'wpLoadPhp');
346 if (!empty($path)) {
347 require_once $path;
348 }
349 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) {
350 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
351 }
352 else {
353 CRM_Core_Error::fatal("Could not find the bootstrap file for WordPress");
354 }
355 $wpUserTimezone = get_option('timezone_string');
356 if ($wpUserTimezone) {
357 date_default_timezone_set($wpUserTimezone);
358 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
359 }
360 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
361 $uid = CRM_Utils_Array::value('uid', $name);
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 }
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 }
384 return TRUE;
385 }
386
387 /**
388 * @param $dir
389 *
390 * @return bool
391 */
392 public function validInstallDir($dir) {
393 $includePath = "$dir/wp-includes";
394 if (file_exists("$includePath/version.php")) {
395 return TRUE;
396 }
397 return FALSE;
398 }
399
400 /**
401 * Determine the location of the CMS root.
402 *
403 * @return string|NULL
404 * local file system path to CMS root, or NULL if it cannot be determined
405 */
406 public function cmsRootPath() {
407 $cmsRoot = $valid = NULL;
408 if (defined('CIVICRM_CMSDIR')) {
409 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
410 $cmsRoot = CIVICRM_CMSDIR;
411 $valid = TRUE;
412 }
413 }
414 else {
415 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
416
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 }
431 }
432 }
433
434 return ($valid) ? $cmsRoot : NULL;
435 }
436
437 /**
438 * @inheritDoc
439 */
440 public function createUser(&$params, $mail) {
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
473 /**
474 * @inheritDoc
475 */
476 public function updateCMSName($ufID, $ufName) {
477 // CRM-10620
478 if (function_exists('wp_update_user')) {
479 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
480 $ufName = CRM_Utils_Type::escape($ufName, 'String');
481
482 $values = array('ID' => $ufID, 'user_email' => $ufName);
483 if ($ufID) {
484 wp_update_user($values);
485 }
486 }
487 }
488
489 /**
490 * @param array $params
491 * @param $errors
492 * @param string $emailName
493 */
494 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
495 $config = CRM_Core_Config::singleton();
496
497 $dao = new CRM_Core_DAO();
498 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
499 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
500
501 if (!empty($params['name'])) {
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
510 if (!empty($params['mail'])) {
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 /**
524 * @inheritDoc
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
535 /**
536 * @return mixed
537 */
538 public function getLoggedInUserObject() {
539 if (function_exists('is_user_logged_in') &&
540 is_user_logged_in()
541 ) {
542 global $current_user;
543 }
544 return $current_user;
545 }
546
547 /**
548 * @inheritDoc
549 */
550 public function getLoggedInUfID() {
551 $ufID = NULL;
552 $current_user = $this->getLoggedInUserObject();
553 return isset($current_user->ID) ? $current_user->ID : NULL;
554 }
555
556 /**
557 * @inheritDoc
558 */
559 public function getLoggedInUniqueIdentifier() {
560 $user = $this->getLoggedInUserObject();
561 return $this->getUniqueIdentifierFromUserObject($user);
562 }
563
564 /**
565 * Get User ID from UserFramework system (Joomla)
566 * @param object $user
567 * Object as described by the CMS.
568 *
569 * @return int|null
570 */
571 public function getUserIDFromUserObject($user) {
572 return !empty($user->ID) ? $user->ID : NULL;
573 }
574
575 /**
576 * @inheritDoc
577 */
578 public function getUniqueIdentifierFromUserObject($user) {
579 return empty($user->user_email) ? NULL : $user->user_email;
580 }
581
582 /**
583 * @inheritDoc
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
592 /**
593 * FIXME: Do something
594 */
595 public function getLoginDestination(&$form) {
596 return NULL;
597 }
598
599 /**
600 * @inheritDoc
601 */
602 public function getVersion() {
603 if (function_exists('get_bloginfo')) {
604 return get_bloginfo('version', 'display');
605 }
606 else {
607 return 'Unknown';
608 }
609 }
610
611 /**
612 * @inheritDoc
613 */
614 public function getTimeZoneString() {
615 return get_option('timezone_string');
616 }
617
618 /**
619 * @inheritDoc
620 */
621 public function getUserRecordUrl($contactID) {
622 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
623 if (CRM_Core_Session::singleton()
624 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array('cms:administer users'))
625 ) {
626 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
627 }
628 }
629
630 /**
631 * Append WP js to coreResourcesList.
632 */
633 public function appendCoreResources(&$list) {
634 $list[] = 'js/crm.wordpress.js';
635 }
636
637 }