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