Merge pull request #5513 from mallezie/contact-select-file-16178
[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
346 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
347 $wpUserTimezone = get_option('timezone_string');
348 if ($wpUserTimezone) {
349 date_default_timezone_set($wpUserTimezone);
350 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
351 }
352 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
353 $uid = CRM_Utils_Array::value('uid', $name);
354 if (!$uid) {
355 $name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST));
356 $pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST));
357 if ($name) {
358 $uid = wp_authenticate($name, $pass);
359 if (!$uid) {
360 if ($throwError) {
361 echo '<br />Sorry, unrecognized username or password.';
362 exit();
363 }
364 return FALSE;
365 }
366 }
367 }
368 if ($uid) {
369 $account = wp_set_current_user($uid);
370 if ($account && $account->data->ID) {
371 global $user;
372 $user = $account;
373 return TRUE;
374 }
375 }
376 return TRUE;
377 }
378
379 /**
380 * @param $dir
381 *
382 * @return bool
383 */
384 public function validInstallDir($dir) {
385 $includePath = "$dir/wp-includes";
386 if (file_exists("$includePath/version.php")) {
387 return TRUE;
388 }
389 return FALSE;
390 }
391
392 /**
393 * Determine the location of the CMS root.
394 *
395 * @return string|NULL
396 * local file system path to CMS root, or NULL if it cannot be determined
397 */
398 public function cmsRootPath() {
399 $cmsRoot = $valid = NULL;
400 if (defined('CIVICRM_CMSDIR')) {
401 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
402 $cmsRoot = CIVICRM_CMSDIR;
403 $valid = TRUE;
404 }
405 }
406 else {
407 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
408
409 //might be windows installation.
410 $firstVar = array_shift($pathVars);
411 if ($firstVar) {
412 $cmsRoot = $firstVar;
413 }
414
415 //start w/ csm dir search.
416 foreach ($pathVars as $var) {
417 $cmsRoot .= "/$var";
418 if ($this->validInstallDir($cmsRoot)) {
419 //stop as we found bootstrap.
420 $valid = TRUE;
421 break;
422 }
423 }
424 }
425
426 return ($valid) ? $cmsRoot : NULL;
427 }
428
429 /**
430 * @inheritDoc
431 */
432 public function createUser(&$params, $mail) {
433 $user_data = array(
434 'ID' => '',
435 'user_pass' => $params['cms_pass'],
436 'user_login' => $params['cms_name'],
437 'user_email' => $params[$mail],
438 'nickname' => $params['cms_name'],
439 'role' => get_option('default_role'),
440 );
441 if (isset($params['contactID'])) {
442 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
443 if ($contactType == 'Individual') {
444 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
445 $params['contactID'], 'first_name'
446 );
447 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
448 $params['contactID'], 'last_name'
449 );
450 }
451 }
452
453 $uid = wp_insert_user($user_data);
454
455 $creds = array();
456 $creds['user_login'] = $params['cms_name'];
457 $creds['user_password'] = $params['cms_pass'];
458 $creds['remember'] = TRUE;
459 $user = wp_signon($creds, FALSE);
460
461 wp_new_user_notification($uid, $user_data['user_pass']);
462 return $uid;
463 }
464
465 /**
466 * @inheritDoc
467 */
468 public function updateCMSName($ufID, $ufName) {
469 // CRM-10620
470 if (function_exists('wp_update_user')) {
471 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
472 $ufName = CRM_Utils_Type::escape($ufName, 'String');
473
474 $values = array('ID' => $ufID, 'user_email' => $ufName);
475 if ($ufID) {
476 wp_update_user($values);
477 }
478 }
479 }
480
481 /**
482 * @param array $params
483 * @param $errors
484 * @param string $emailName
485 */
486 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
487 $config = CRM_Core_Config::singleton();
488
489 $dao = new CRM_Core_DAO();
490 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
491 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
492
493 if (!empty($params['name'])) {
494 if (!validate_username($params['name'])) {
495 $errors['cms_name'] = ts("Your username contains invalid characters");
496 }
497 elseif (username_exists(sanitize_user($params['name']))) {
498 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
499 }
500 }
501
502 if (!empty($params['mail'])) {
503 if (!is_email($params['mail'])) {
504 $errors[$emailName] = "Your email is invaid";
505 }
506 elseif (email_exists($params['mail'])) {
507 $resetUrl = $config->userFrameworkBaseURL . 'wp-login.php?action=lostpassword';
508 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
509 array(1 => $params['mail'], 2 => $resetUrl)
510 );
511 }
512 }
513 }
514
515 /**
516 * @inheritDoc
517 */
518 public function isUserLoggedIn() {
519 $isloggedIn = FALSE;
520 if (function_exists('is_user_logged_in')) {
521 $isloggedIn = is_user_logged_in();
522 }
523
524 return $isloggedIn;
525 }
526
527 /**
528 * @return mixed
529 */
530 public function getLoggedInUserObject() {
531 if (function_exists('is_user_logged_in') &&
532 is_user_logged_in()
533 ) {
534 global $current_user;
535 }
536 return $current_user;
537 }
538
539 /**
540 * @inheritDoc
541 */
542 public function getLoggedInUfID() {
543 $ufID = NULL;
544 $current_user = $this->getLoggedInUserObject();
545 return isset($current_user->ID) ? $current_user->ID : NULL;
546 }
547
548 /**
549 * @inheritDoc
550 */
551 public function getLoggedInUniqueIdentifier() {
552 $user = $this->getLoggedInUserObject();
553 return $this->getUniqueIdentifierFromUserObject($user);
554 }
555
556 /**
557 * Get User ID from UserFramework system (Joomla)
558 * @param object $user
559 * Object as described by the CMS.
560 *
561 * @return int|null
562 */
563 public function getUserIDFromUserObject($user) {
564 return !empty($user->ID) ? $user->ID : NULL;
565 }
566
567 /**
568 * @inheritDoc
569 */
570 public function getUniqueIdentifierFromUserObject($user) {
571 return empty($user->user_email) ? NULL : $user->user_email;
572 }
573
574 /**
575 * @inheritDoc
576 */
577 public function getLoginURL($destination = '') {
578 $config = CRM_Core_Config::singleton();
579 $loginURL = $config->userFrameworkBaseURL;
580 $loginURL .= 'wp-login.php';
581 return $loginURL;
582 }
583
584 /**
585 * FIXME: Do something
586 */
587 public function getLoginDestination(&$form) {
588 return NULL;
589 }
590
591 /**
592 * @inheritDoc
593 */
594 public function getVersion() {
595 if (function_exists('get_bloginfo')) {
596 return get_bloginfo('version', 'display');
597 }
598 else {
599 return 'Unknown';
600 }
601 }
602
603 /**
604 * @inheritDoc
605 */
606 public function getTimeZoneString() {
607 return get_option('timezone_string');
608 }
609
610 /**
611 * @inheritDoc
612 */
613 public function getUserRecordUrl($contactID) {
614 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
615 if (CRM_Core_Session::singleton()
616 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array('cms:administer users'))
617 ) {
618 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
619 }
620 }
621
622 }