Sort address tokens into an optgroup
[civicrm-core.git] / CRM / Utils / System / WordPress.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 */
43 function __construct() {
44 /**
45 * 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
46 * functions and leave the codebase oblivious to the type of CMS
47 * @deprecated
48 * @var bool
49 */
50 $this->is_drupal = FALSE;
51 }
52
53 /**
54 * sets the title of the page
55 *
56 * @param string $title
57 * @param null $pageTitle
58 *
59 * @paqram string $pageTitle
60 *
61 * @return void
62 * @access public
63 */
64 function setTitle($title, $pageTitle = NULL) {
65 if (!$pageTitle) {
66 $pageTitle = $title;
67 }
68 if (civicrm_wp_in_civicrm()) {
69 global $civicrm_wp_title;
70 $civicrm_wp_title = $pageTitle;
71 $template = CRM_Core_Smarty::singleton();
72 $template->assign('pageTitle', $pageTitle);
73 }
74 }
75
76 /**
77 * Append an additional breadcrumb tag to the existing breadcrumb
78 *
79 * @param $breadCrumbs
80 *
81 * @internal param string $title
82 * @internal param string $url
83 *
84 * @return void
85 * @access public
86 * @static
87 */
88 function appendBreadCrumb($breadCrumbs) {
89 $breadCrumb = wp_get_breadcrumb();
90
91 if (is_array($breadCrumbs)) {
92 foreach ($breadCrumbs as $crumbs) {
93 if (stripos($crumbs['url'], 'id%%')) {
94 $args = array('cid', 'mid');
95 foreach ($args as $a) {
96 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
97 FALSE, NULL, $_GET
98 );
99 if ($val) {
100 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
101 }
102 }
103 }
104 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
105 }
106 }
107
108 $template = CRM_Core_Smarty::singleton();
109 $template->assign_by_ref('breadcrumb', $breadCrumb);
110 wp_set_breadcrumb($breadCrumb);
111 }
112
113 /**
114 * Reset an additional breadcrumb tag to the existing breadcrumb
115 *
116 * @return void
117 * @access public
118 * @static
119 */
120 function resetBreadCrumb() {
121 $bc = array();
122 wp_set_breadcrumb($bc);
123 }
124
125 /**
126 * Append a string to the head of the html file
127 *
128 * @param string $head the new string to be appended
129 *
130 * @return void
131 * @access public
132 * @static
133 */
134 function addHTMLHead($head) {
135 static $registered = FALSE;
136 if (!$registered) {
137 // front-end view
138 add_action('wp_head', array(__CLASS__, '_showHTMLHead'));
139 // back-end views
140 add_action('admin_head', array(__CLASS__, '_showHTMLHead'));
141 }
142 CRM_Core_Region::instance('wp_head')->add(array(
143 'markup' => $head,
144 ));
145 }
146
147 static function _showHTMLHead() {
148 $region = CRM_Core_Region::instance('wp_head', FALSE);
149 if ($region) {
150 echo $region->render('');
151 }
152 }
153
154 /**
155 * Add a script file
156 *
157 * @param $url: string, absolute path to file
158 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
159 *
160 * Note: This function is not to be called directly
161 * @see CRM_Core_Region::render()
162 *
163 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
164 * @access public
165 */
166 public function addScriptUrl($url, $region) {
167 return FALSE;
168 }
169
170 /**
171 * Add an inline script
172 *
173 * @param $code: string, javascript code
174 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
175 *
176 * Note: This function is not to be called directly
177 * @see CRM_Core_Region::render()
178 *
179 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
180 * @access public
181 */
182 public function addScript($code, $region) {
183 return FALSE;
184 }
185
186 /**
187 * Add a css file
188 *
189 * @param $url: string, absolute path to file
190 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
191 *
192 * Note: This function is not to be called directly
193 * @see CRM_Core_Region::render()
194 *
195 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
196 * @access public
197 */
198 public function addStyleUrl($url, $region) {
199 return FALSE;
200 }
201
202 /**
203 * Add an inline style
204 *
205 * @param $code: string, css code
206 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
207 *
208 * Note: This function is not to be called directly
209 * @see CRM_Core_Region::render()
210 *
211 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
212 * @access public
213 */
214 public function addStyle($code, $region) {
215 return FALSE;
216 }
217
218 /**
219 * rewrite various system urls to https
220 *
221 * @param null
222 *
223 * @return void
224 * @access public
225 * @static
226 */
227 function mapConfigToSSL() {
228 global $base_url;
229 $base_url = str_replace('http://', 'https://', $base_url);
230 }
231
232 /**
233 * figure out the post url for the form
234 *
235 * @param mix $action the default action if one is pre-specified
236 *
237 * @return string the url to post the form
238 * @access public
239 * @static
240 */
241 function postURL($action) {
242 if (!empty($action)) {
243 return $action;
244 }
245
246 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
247 }
248
249 /**
250 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
251 *
252 * @param $path string The path being linked to, such as "civicrm/add"
253 * @param $query string A query string to append to the link.
254 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
255 * Useful for links that will be displayed outside the site, such as in an
256 * RSS feed.
257 * @param $fragment string A fragment identifier (named anchor) to append to the link.
258 * @param $htmlize boolean whether to convert to html eqivalant
259 * @param $frontend boolean a gross joomla hack
260 *
261 * @param bool $forceBackend
262 *
263 * @return string an HTML string containing a link to the given path.
264 * @access public
265 */
266 function url(
267 $path = NULL,
268 $query = NULL,
269 $absolute = FALSE,
270 $fragment = NULL,
271 $htmlize = TRUE,
272 $frontend = FALSE,
273 $forceBackend = FALSE
274 ) {
275 $config = CRM_Core_Config::singleton();
276 $script = '';
277 $separator = $htmlize ? '&amp;' : '&';
278 $wpPageParam = '';
279 $fragment = isset($fragment) ? ('#' . $fragment) : '';
280
281 $path = CRM_Utils_String::stripPathChars($path);
282
283 //this means wp function we are trying to use is not available,
284 //so load bootStrap
285 if (!function_exists('get_option')) {
286 $this->loadBootStrap(); // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
287 }
288 if ($config->userFrameworkFrontend) {
289 if (get_option('permalink_structure') != '') {
290 global $post;
291 $script = get_permalink($post->ID);
292 }
293
294 // when shortcode is included in page
295 // also make sure we have valid query object
296 global $wp_query;
297 if ( method_exists( $wp_query, 'get' ) ) {
298 if (get_query_var('page_id')) {
299 $wpPageParam = "page_id=" . get_query_var('page_id');
300 }
301 elseif (get_query_var('p')) {
302 // when shortcode is inserted in post
303 $wpPageParam = "p=" . get_query_var('p');
304 }
305 }
306 }
307
308 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
309
310 if (!isset($path) && !isset($query)) {
311 // FIXME: This short-circuited codepath is the same as the general one below, except
312 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
313 // why it's different (and I can only find two obvious use-cases for this codepath,
314 // of which at least one looks gratuitous). A more ambitious person would simply remove
315 // this code.
316 return $base . $fragment;
317 }
318
319 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam || $script != '')) {
320 $base = $script;
321 }
322
323 $queryParts = array();
324 if (isset($path)) {
325 $queryParts[] = 'page=CiviCRM';
326 $queryParts[] = "q={$path}";
327 }
328 if ($wpPageParam) {
329 $queryParts[] = $wpPageParam;
330 }
331 if (isset($query)) {
332 $queryParts[] = $query;
333 }
334
335 return $base . '?' . implode($separator, $queryParts) . $fragment;
336 }
337
338 /**
339 * @param $absolute
340 * @param $frontend
341 * @param $forceBackend
342 *
343 * @return mixed|null|string
344 */
345 private function getBaseUrl($absolute, $frontend, $forceBackend) {
346 $config = CRM_Core_Config::singleton();
347
348 if (!isset($config->useFrameworkRelativeBase)) {
349 $base = parse_url($config->userFrameworkBaseURL);
350 $config->useFrameworkRelativeBase = $base['path'];
351 }
352
353 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
354
355 if ((is_admin() && !$frontend) || $forceBackend) {
356 $base .= 'wp-admin/admin.php';
357 return $base;
358 }
359 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
360 $base .= CIVICRM_UF_WP_BASEPAGE;
361 return $base;
362 }
363 elseif (isset($config->wpBasePage)) {
364 $base .= $config->wpBasePage;
365 return $base;
366 }
367 return $base;
368 }
369
370 /**
371 * Authenticate the user against the wordpress db
372 *
373 * @param string $name the user name
374 * @param string $password the password for the above user name
375 *
376 * @param bool $loadCMSBootstrap
377 * @param null $realPath
378 *
379 * @return mixed false if no auth
380 * array(
381 * contactID, ufID, unique string ) if success
382 * @access public
383 * @static
384 */
385 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
386 $config = CRM_Core_Config::singleton();
387
388 if ($loadCMSBootstrap) {
389 $config->userSystem->loadBootStrap($name, $password);
390 }
391
392 $user = wp_authenticate($name, $password);
393 if (is_a($user, 'WP_Error')) {
394 return FALSE;
395 }
396
397 // need to change this to make sure we matched only one row
398
399 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
400 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
401 if (!$contactID) {
402 return FALSE;
403 }
404 return array($contactID, $user->data->ID, mt_rand());
405 }
406
407 /**
408 * Set a message in the UF to display to a user
409 *
410 * @param string $message the message to set
411 *
412 * @access public
413 * @static
414 */
415 function setMessage($message) {
416 }
417
418 /**
419 * @param $user
420 *
421 * @return bool
422 */
423 function loadUser( $user ) {
424 return true;
425 }
426
427 function permissionDenied() {
428 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
429 }
430
431 function logout() {
432 // destroy session
433 if (session_id()) {
434 session_destroy();
435 }
436 wp_logout();
437 wp_redirect(wp_login_url());
438 }
439
440 function updateCategories() {}
441
442 /**
443 * Get the locale set in the hosting CMS
444 *
445 * @return string with the locale or null for none
446 */
447 function getUFLocale() {
448 // WPML plugin
449 if (defined('ICL_LANGUAGE_CODE')) {
450 $language = ICL_LANGUAGE_CODE;
451 }
452
453 // TODO: set language variable for others WordPress plugin
454
455 if (isset($language)) {
456 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language, 0, 2));
457 } else {
458 return NULL;
459 }
460 }
461
462 /**
463 * load wordpress bootstrap
464 *
465 * @param $name string optional username for login
466 * @param $pass string optional password for login
467 *
468 * @return bool
469 */
470 function loadBootStrap($name = NULL, $pass = NULL) {
471 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
472
473 $cmsRootPath = $this->cmsRootPath();
474 if (!$cmsRootPath) {
475 CRM_Core_Error::fatal("Could not find the install directory for WordPress");
476 }
477
478 require_once ($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php');
479 $wpUserTimezone = get_option('timezone_string');
480 if ($wpUserTimezone) {
481 date_default_timezone_set($wpUserTimezone);
482 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
483 }
484 require_once ($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php');
485 $uid = CRM_Utils_Array::value('uid', $name);
486 if ($uid) {
487 $account = wp_set_current_user($uid);
488 if ($account && $account->data->ID) {
489 global $user;
490 $user = $account;
491 return TRUE;
492 }
493 }
494 return true;
495 }
496
497 /**
498 * @param $dir
499 *
500 * @return bool
501 */
502 function validInstallDir($dir) {
503 $includePath = "$dir/wp-includes";
504 if (
505 @opendir($includePath) &&
506 file_exists("$includePath/version.php")
507 ) {
508 return TRUE;
509 }
510 return FALSE;
511 }
512
513 /**
514 * Determine the location of the CMS root.
515 *
516 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
517 */
518 /**
519 * @return NULL|string
520 */
521 function cmsRootPath() {
522 $cmsRoot = $valid = NULL;
523 if (defined('CIVICRM_CMSDIR')) {
524 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
525 $cmsRoot = CIVICRM_CMSDIR;
526 $valid = TRUE;
527 }
528 }
529 else {
530 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
531
532 //might be windows installation.
533 $firstVar = array_shift($pathVars);
534 if ($firstVar) {
535 $cmsRoot = $firstVar;
536 }
537
538 //start w/ csm dir search.
539 foreach ($pathVars as $var) {
540 $cmsRoot .= "/$var";
541 if ($this->validInstallDir($cmsRoot)) {
542 //stop as we found bootstrap.
543 $valid = TRUE;
544 break;
545 }
546 }
547 }
548
549 return ($valid) ? $cmsRoot : NULL;
550 }
551
552 /**
553 * @param $params
554 * @param $mail
555 *
556 * @return mixed
557 */
558 function createUser(&$params, $mail) {
559 $user_data = array(
560 'ID' => '',
561 'user_pass' => $params['cms_pass'],
562 'user_login' => $params['cms_name'],
563 'user_email' => $params[$mail],
564 'nickname' => $params['cms_name'],
565 'role' => get_option('default_role'),
566 );
567 if (isset($params['contactID'])) {
568 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
569 if ($contactType == 'Individual') {
570 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
571 $params['contactID'], 'first_name'
572 );
573 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
574 $params['contactID'], 'last_name'
575 );
576 }
577 }
578
579 $uid = wp_insert_user($user_data);
580
581 $creds = array();
582 $creds['user_login'] = $params['cms_name'];
583 $creds['user_password'] = $params['cms_pass'];
584 $creds['remember'] = TRUE;
585 $user = wp_signon($creds, FALSE);
586
587 wp_new_user_notification($uid, $user_data['user_pass']);
588 return $uid;
589 }
590
591 /**
592 * Change user name in host CMS
593 *
594 * @param integer $ufID User ID in CMS
595 * @param string $ufName User name
596 */
597 function updateCMSName($ufID, $ufName) {
598 // CRM-10620
599 if (function_exists('wp_update_user')) {
600 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
601 $ufName = CRM_Utils_Type::escape($ufName, 'String');
602
603 $values = array ('ID' => $ufID, 'user_email' => $ufName);
604 if( $ufID ) {
605 wp_update_user( $values ) ;
606 }
607 }
608 }
609
610 /**
611 * @param $params
612 * @param $errors
613 * @param string $emailName
614 */
615 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
616 $config = CRM_Core_Config::singleton();
617
618 $dao = new CRM_Core_DAO();
619 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
620 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
621
622 if (!empty($params['name'])) {
623 if (!validate_username($params['name'])) {
624 $errors['cms_name'] = ts("Your username contains invalid characters");
625 }
626 elseif (username_exists(sanitize_user($params['name']))) {
627 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
628 }
629 }
630
631 if (!empty($params['mail'])) {
632 if (!is_email($params['mail'])) {
633 $errors[$emailName] = "Your email is invaid";
634 }
635 elseif (email_exists($params['mail'])) {
636 $resetUrl = $config->userFrameworkBaseURL . 'wp-login.php?action=lostpassword';
637 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
638 array(1 => $params['mail'], 2 => $resetUrl)
639 );
640 }
641 }
642 }
643
644 /**
645 * check is user logged in.
646 *
647 * @return boolean true/false.
648 */
649 public function isUserLoggedIn() {
650 $isloggedIn = FALSE;
651 if (function_exists('is_user_logged_in')) {
652 $isloggedIn = is_user_logged_in();
653 }
654
655 return $isloggedIn;
656 }
657
658 /**
659 * @return mixed
660 */
661 function getLoggedInUserObject() {
662 if (function_exists('is_user_logged_in') &&
663 is_user_logged_in()) {
664 global $current_user;
665 }
666 return $current_user;
667 }
668 /**
669 * Get currently logged in user uf id.
670 *
671 * @return int $userID logged in user uf id.
672 */
673 public function getLoggedInUfID() {
674 $ufID = NULL;
675 $current_user = $this->getLoggedInUserObject();
676 return isset($current_user->ID) ? $current_user->ID : NULL;
677 }
678
679 /**
680 * Get currently logged in user unique identifier - this tends to be the email address or user name.
681 *
682 * @return string $userID logged in user unique identifier
683 */
684 function getLoggedInUniqueIdentifier() {
685 $user = $this->getLoggedInUserObject();
686 return $this->getUniqueIdentifierFromUserObject($user);
687 }
688
689 /**
690 * Get User ID from UserFramework system (Joomla)
691 * @param object $user object as described by the CMS
692 * @return mixed <NULL, number>
693 */
694 function getUserIDFromUserObject($user) {
695 return !empty($user->ID) ? $user->ID : NULL;
696 }
697
698 /**
699 * Get Unique Identifier from UserFramework system (CMS)
700 * @param object $user object as described by the User Framework
701 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
702 *
703 */
704 function getUniqueIdentifierFromUserObject($user) {
705 return empty($user->user_email) ? NULL : $user->user_email;
706 }
707
708 /**
709 * Get user login URL for hosting CMS (method declared in each CMS system class)
710 *
711 * @param string $destination - if present, add destination to querystring (works for Drupal only)
712 *
713 * @return string - loginURL for the current CMS
714 *
715 */
716 public function getLoginURL($destination = '') {
717 $config = CRM_Core_Config::singleton();
718 $loginURL = $config->userFrameworkBaseURL;
719 $loginURL .= 'wp-login.php';
720 return $loginURL;
721 }
722
723 /**
724 * @param $form
725 */
726 public function getLoginDestination(&$form) {
727 return;
728 }
729
730 /**
731 * Return the current WordPress version if relevant function exists
732 *
733 * @return string - version number
734 *
735 */
736 function getVersion() {
737 if (function_exists('get_bloginfo')) {
738 return get_bloginfo('version', 'display');
739 }
740 else {
741 return 'Unknown';
742 }
743 }
744
745 /**
746 * get timezone as a string
747 * @return string Timezone e.g. 'America/Los_Angeles'
748 */
749 function getTimeZoneString() {
750 return get_option('timezone_string');
751 }
752
753 /**
754 * Get Url to view user record
755 * @param integer $contactID Contact ID
756 *
757 * @return string
758 */
759 function getUserRecordUrl($contactID) {
760 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
761 if (CRM_Core_Session::singleton()->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array('cms:administer users'))) {
762 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
763 }
764 }
765 }
766