b3a4bd7a87bd9431e12d75c81f2d924b5e582f40
[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, $current_site, $current_blog, $current_user;
379
380 if (!defined('WP_USE_THEMES')) {
381 define('WP_USE_THEMES', FALSE);
382 }
383
384 $cmsRootPath = $this->cmsRootPath();
385 if (!$cmsRootPath) {
386 CRM_Core_Error::fatal("Could not find the install directory for WordPress");
387 }
388 $path = Civi::settings()->get('wpLoadPhp');
389 if (!empty($path)) {
390 require_once $path;
391 }
392 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) {
393 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
394 }
395 else {
396 CRM_Core_Error::fatal("Could not find the bootstrap file for WordPress");
397 }
398 $wpUserTimezone = get_option('timezone_string');
399 if ($wpUserTimezone) {
400 date_default_timezone_set($wpUserTimezone);
401 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
402 }
403 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
404 $uid = CRM_Utils_Array::value('uid', $name);
405 if (!$uid) {
406 $name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST));
407 $pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST));
408 if ($name) {
409 $uid = wp_authenticate($name, $pass); // this returns a WP_User object if successful
410 if (!$uid) {
411 if ($throwError) {
412 echo '<br />Sorry, unrecognized username or password.';
413 exit();
414 }
415 return FALSE;
416 }
417 }
418 }
419 if ($uid) {
420 if ($uid instanceof WP_User) {
421 $account = wp_set_current_user($uid->ID);
422 }
423 else {
424 $account = wp_set_current_user($uid);
425 }
426 if ($account && $account->data->ID) {
427 global $user;
428 $user = $account;
429 return TRUE;
430 }
431 }
432 return TRUE;
433 }
434
435 /**
436 * @param $dir
437 *
438 * @return bool
439 */
440 public function validInstallDir($dir) {
441 $includePath = "$dir/wp-includes";
442 if (file_exists("$includePath/version.php")) {
443 return TRUE;
444 }
445 return FALSE;
446 }
447
448 /**
449 * Determine the location of the CMS root.
450 *
451 * @return string|NULL
452 * local file system path to CMS root, or NULL if it cannot be determined
453 */
454 public function cmsRootPath() {
455 $cmsRoot = $valid = NULL;
456 if (defined('CIVICRM_CMSDIR')) {
457 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
458 $cmsRoot = CIVICRM_CMSDIR;
459 $valid = TRUE;
460 }
461 }
462 else {
463 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
464
465 //might be windows installation.
466 $firstVar = array_shift($pathVars);
467 if ($firstVar) {
468 $cmsRoot = $firstVar;
469 }
470
471 //start w/ csm dir search.
472 foreach ($pathVars as $var) {
473 $cmsRoot .= "/$var";
474 if ($this->validInstallDir($cmsRoot)) {
475 //stop as we found bootstrap.
476 $valid = TRUE;
477 break;
478 }
479 }
480 }
481
482 return ($valid) ? $cmsRoot : NULL;
483 }
484
485 /**
486 * @inheritDoc
487 */
488 public function createUser(&$params, $mail) {
489 $user_data = array(
490 'ID' => '',
491 'user_pass' => $params['cms_pass'],
492 'user_login' => $params['cms_name'],
493 'user_email' => $params[$mail],
494 'nickname' => $params['cms_name'],
495 'role' => get_option('default_role'),
496 );
497 if (isset($params['contactID'])) {
498 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
499 if ($contactType == 'Individual') {
500 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
501 $params['contactID'], 'first_name'
502 );
503 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
504 $params['contactID'], 'last_name'
505 );
506 }
507 }
508
509 $uid = wp_insert_user($user_data);
510
511 $creds = array();
512 $creds['user_login'] = $params['cms_name'];
513 $creds['user_password'] = $params['cms_pass'];
514 $creds['remember'] = TRUE;
515 $user = wp_signon($creds, FALSE);
516
517 wp_new_user_notification($uid, $user_data['user_pass']);
518 return $uid;
519 }
520
521 /**
522 * @inheritDoc
523 */
524 public function updateCMSName($ufID, $ufName) {
525 // CRM-10620
526 if (function_exists('wp_update_user')) {
527 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
528 $ufName = CRM_Utils_Type::escape($ufName, 'String');
529
530 $values = array('ID' => $ufID, 'user_email' => $ufName);
531 if ($ufID) {
532 wp_update_user($values);
533 }
534 }
535 }
536
537 /**
538 * @param array $params
539 * @param $errors
540 * @param string $emailName
541 */
542 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
543 $config = CRM_Core_Config::singleton();
544
545 $dao = new CRM_Core_DAO();
546 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
547 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
548
549 if (!empty($params['name'])) {
550 if (!validate_username($params['name'])) {
551 $errors['cms_name'] = ts("Your username contains invalid characters");
552 }
553 elseif (username_exists(sanitize_user($params['name']))) {
554 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
555 }
556 }
557
558 if (!empty($params['mail'])) {
559 if (!is_email($params['mail'])) {
560 $errors[$emailName] = "Your email is invaid";
561 }
562 elseif (email_exists($params['mail'])) {
563 $resetUrl = $config->userFrameworkBaseURL . 'wp-login.php?action=lostpassword';
564 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
565 array(1 => $params['mail'], 2 => $resetUrl)
566 );
567 }
568 }
569 }
570
571 /**
572 * @inheritDoc
573 */
574 public function isUserLoggedIn() {
575 $isloggedIn = FALSE;
576 if (function_exists('is_user_logged_in')) {
577 $isloggedIn = is_user_logged_in();
578 }
579
580 return $isloggedIn;
581 }
582
583 /**
584 * @return mixed
585 */
586 public function getLoggedInUserObject() {
587 if (function_exists('is_user_logged_in') &&
588 is_user_logged_in()
589 ) {
590 global $current_user;
591 }
592 return $current_user;
593 }
594
595 /**
596 * @inheritDoc
597 */
598 public function getLoggedInUfID() {
599 $ufID = NULL;
600 $current_user = $this->getLoggedInUserObject();
601 return isset($current_user->ID) ? $current_user->ID : NULL;
602 }
603
604 /**
605 * @inheritDoc
606 */
607 public function getLoggedInUniqueIdentifier() {
608 $user = $this->getLoggedInUserObject();
609 return $this->getUniqueIdentifierFromUserObject($user);
610 }
611
612 /**
613 * Get User ID from UserFramework system (Joomla)
614 * @param object $user
615 * Object as described by the CMS.
616 *
617 * @return int|null
618 */
619 public function getUserIDFromUserObject($user) {
620 return !empty($user->ID) ? $user->ID : NULL;
621 }
622
623 /**
624 * @inheritDoc
625 */
626 public function getUniqueIdentifierFromUserObject($user) {
627 return empty($user->user_email) ? NULL : $user->user_email;
628 }
629
630 /**
631 * @inheritDoc
632 */
633 public function getLoginURL($destination = '') {
634 $config = CRM_Core_Config::singleton();
635 $loginURL = $config->userFrameworkBaseURL;
636 $loginURL .= 'wp-login.php';
637 return $loginURL;
638 }
639
640 /**
641 * FIXME: Do something.
642 *
643 * @param \CRM_Core_Form $form
644 *
645 * @return NULL|string
646 */
647 public function getLoginDestination(&$form) {
648 return NULL;
649 }
650
651 /**
652 * @inheritDoc
653 */
654 public function getVersion() {
655 if (function_exists('get_bloginfo')) {
656 return get_bloginfo('version', 'display');
657 }
658 else {
659 return 'Unknown';
660 }
661 }
662
663 /**
664 * @inheritDoc
665 */
666 public function getTimeZoneString() {
667 return get_option('timezone_string');
668 }
669
670 /**
671 * @inheritDoc
672 */
673 public function getUserRecordUrl($contactID) {
674 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
675 if (CRM_Core_Session::singleton()
676 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array('cms:administer users'))
677 ) {
678 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
679 }
680 }
681
682 /**
683 * Append WP js to coreResourcesList.
684 *
685 * @param array $list
686 */
687 public function appendCoreResources(&$list) {
688 $list[] = 'js/crm.wordpress.js';
689 }
690
691 /**
692 * @inheritDoc
693 */
694 public function synchronizeUsers() {
695 $config = CRM_Core_Config::singleton();
696 if (PHP_SAPI != 'cli') {
697 set_time_limit(300);
698 }
699 $id = 'ID';
700 $mail = 'user_email';
701
702 $uf = $config->userFramework;
703 $contactCount = 0;
704 $contactCreated = 0;
705 $contactMatching = 0;
706
707 global $wpdb;
708 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
709
710 foreach ($wpUserIds as $wpUserId) {
711 $wpUserData = get_userdata($wpUserId);
712 $contactCount++;
713 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData,
714 $wpUserData->$id,
715 $wpUserData->$mail,
716 $uf,
717 1,
718 'Individual',
719 TRUE
720 )
721 ) {
722 $contactCreated++;
723 }
724 else {
725 $contactMatching++;
726 }
727 if (is_object($match)) {
728 $match->free();
729 }
730 }
731
732 return array(
733 'contactCount' => $contactCount,
734 'contactMatching' => $contactMatching,
735 'contactCreated' => $contactCreated,
736 );
737 }
738
739 }