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