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