Merge pull request #4866 from totten/master-phpcs
[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 */
43 public 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 $this->is_wordpress = TRUE;
52 }
53
54 /**
55 * Sets the title of the page
56 *
57 * @param string $title
58 * @param null $pageTitle
59 *
60 * @return void
61 */
62 public function setTitle($title, $pageTitle = NULL) {
63 if (!$pageTitle) {
64 $pageTitle = $title;
65 }
66
67 // get civi-wordpress instance
68 $civi = civi_wp();
69
70 // do we have functionality provided by plugin version 4.6+ present?
71 if (method_exists($civi, 'civicrm_context_get')) {
72
73 global $civicrm_wp_title;
74 $civicrm_wp_title = $pageTitle;
75
76 // yes, set page title, depending on context
77 $context = civi_wp()->civicrm_context_get();
78 switch ($context) {
79 case 'admin':
80 case 'shortcode':
81 $template = CRM_Core_Smarty::singleton();
82 $template->assign('pageTitle', $pageTitle);
83 }
84
85 }
86 elseif (civicrm_wp_in_civicrm()) {
87
88 // legacy pre-4.6 behaviour
89 global $civicrm_wp_title;
90 $civicrm_wp_title = $pageTitle;
91 $template = CRM_Core_Smarty::singleton();
92 $template->assign('pageTitle', $pageTitle);
93
94 }
95 }
96
97 /**
98 * Append an additional breadcrumb tag to the existing breadcrumb
99 *
100 * @param $breadCrumbs
101 *
102 * @internal param string $title
103 * @internal param string $url
104 *
105 * @return void
106 * @static
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 * Reset an additional breadcrumb tag to the existing breadcrumb
135 *
136 * @return void
137 * @static
138 */
139 public function resetBreadCrumb() {
140 $bc = array();
141 wp_set_breadcrumb($bc);
142 }
143
144 /**
145 * Append a string to the head of the html file
146 *
147 * @param string $head
148 * The new string to be appended.
149 *
150 * @return void
151 * @static
152 */
153 public function addHTMLHead($head) {
154 static $registered = FALSE;
155 if (!$registered) {
156 // front-end view
157 add_action('wp_head', array(__CLASS__, '_showHTMLHead'));
158 // back-end views
159 add_action('admin_head', array(__CLASS__, '_showHTMLHead'));
160 }
161 CRM_Core_Region::instance('wp_head')->add(array(
162 'markup' => $head,
163 ));
164 }
165
166 public static function _showHTMLHead() {
167 $region = CRM_Core_Region::instance('wp_head', FALSE);
168 if ($region) {
169 echo $region->render('');
170 }
171 }
172
173 /**
174 * Add a script file
175 *
176 * @param $url: string, absolute path to file
177 * @param $region
178 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
179 *
180 * Note: This function is not to be called directly
181 * @see CRM_Core_Region::render()
182 *
183 * @return bool 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 $region
194 * String, 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 TRUE if we support this operation in this CMS, FALSE otherwise
200 */
201 public function addScript($code, $region) {
202 return FALSE;
203 }
204
205 /**
206 * Add a css file
207 *
208 * @param $url: string, absolute path to file
209 * @param $region
210 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
211 *
212 * Note: This function is not to be called directly
213 * @see CRM_Core_Region::render()
214 *
215 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
216 */
217 public function addStyleUrl($url, $region) {
218 return FALSE;
219 }
220
221 /**
222 * Add an inline style
223 *
224 * @param $code: string, css code
225 * @param $region
226 * String, location within the document: 'html-header', 'page-header', 'page-footer'.
227 *
228 * Note: This function is not to be called directly
229 * @see CRM_Core_Region::render()
230 *
231 * @return bool 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 * @static
244 */
245 public function mapConfigToSSL() {
246 global $base_url;
247 $base_url = str_replace('http://', 'https://', $base_url);
248 }
249
250 /**
251 * Figure out the post url for the form
252 *
253 * @param mix $action
254 * The default action if one is pre-specified.
255 *
256 * @return string the url to post the form
257 * @static
258 */
259 public function postURL($action) {
260 if (!empty($action)) {
261 return $action;
262 }
263
264 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
265 }
266
267 /**
268 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
269 *
270 * @param $path
271 * String The path being linked to, such as "civicrm/add".
272 * @param $query
273 * String A query string to append to the link.
274 * @param $absolute
275 * Boolean Whether to force the output to be an absolute link (beginning with http:).
276 * Useful for links that will be displayed outside the site, such as in an
277 * RSS feed.
278 * @param $fragment
279 * String A fragment identifier (named anchor) to append to the link.
280 * @param $htmlize
281 * Boolean whether to convert to html eqivalant.
282 * @param $frontend
283 * Boolean a gross joomla hack.
284 *
285 * @param bool $forceBackend
286 *
287 * @return string 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 mixed false if no auth
405 * array(
406 * contactID, ufID, unique string ) if success
407 * @static
408 */
409 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
410 $config = CRM_Core_Config::singleton();
411
412 if ($loadCMSBootstrap) {
413 $config->userSystem->loadBootStrap($name, $password);
414 }
415
416 $user = wp_authenticate($name, $password);
417 if (is_a($user, 'WP_Error')) {
418 return FALSE;
419 }
420
421 // need to change this to make sure we matched only one row
422
423 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
424 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
425 if (!$contactID) {
426 return FALSE;
427 }
428 return array($contactID, $user->data->ID, mt_rand());
429 }
430
431 /**
432 * Set a message in the UF to display to a user
433 *
434 * @param string $message
435 * The message to set.
436 *
437 * @static
438 */
439 public function setMessage($message) {
440 }
441
442 /**
443 * @param $user
444 *
445 * @return bool
446 */
447 public function loadUser($user) {
448 return TRUE;
449 }
450
451 public function permissionDenied() {
452 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
453 }
454
455 public function logout() {
456 // destroy session
457 if (session_id()) {
458 session_destroy();
459 }
460 wp_logout();
461 wp_redirect(wp_login_url());
462 }
463
464 public function updateCategories() {
465 }
466
467 /**
468 * Get the locale set in the hosting CMS
469 *
470 * @return string with the locale or null for none
471 */
472 public function getUFLocale() {
473 // WPML plugin
474 if (defined('ICL_LANGUAGE_CODE')) {
475 $language = ICL_LANGUAGE_CODE;
476 }
477
478 // TODO: set language variable for others WordPress plugin
479
480 if (isset($language)) {
481 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language, 0, 2));
482 }
483 else {
484 return NULL;
485 }
486 }
487
488 /**
489 * Load wordpress bootstrap
490 *
491 * @param $name
492 * String optional username for login.
493 * @param $pass
494 * String optional password for login.
495 *
496 * @return bool
497 */
498 public function loadBootStrap($name = NULL, $pass = NULL) {
499 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
500
501 $cmsRootPath = $this->cmsRootPath();
502 if (!$cmsRootPath) {
503 CRM_Core_Error::fatal("Could not find the install directory for WordPress");
504 }
505
506 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
507 $wpUserTimezone = get_option('timezone_string');
508 if ($wpUserTimezone) {
509 date_default_timezone_set($wpUserTimezone);
510 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
511 }
512 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
513 $uid = CRM_Utils_Array::value('uid', $name);
514 if ($uid) {
515 $account = wp_set_current_user($uid);
516 if ($account && $account->data->ID) {
517 global $user;
518 $user = $account;
519 return TRUE;
520 }
521 }
522 return TRUE;
523 }
524
525 /**
526 * @param $dir
527 *
528 * @return bool
529 */
530 public function validInstallDir($dir) {
531 $includePath = "$dir/wp-includes";
532 if (file_exists("$includePath/version.php")) {
533 return TRUE;
534 }
535 return FALSE;
536 }
537
538 /**
539 * Determine the location of the CMS root.
540 *
541 * @return string|NULL local file system path to CMS root, or NULL if it cannot be determined
542 */
543 /**
544 * @return NULL|string
545 */
546 public function cmsRootPath() {
547 $cmsRoot = $valid = NULL;
548 if (defined('CIVICRM_CMSDIR')) {
549 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
550 $cmsRoot = CIVICRM_CMSDIR;
551 $valid = TRUE;
552 }
553 }
554 else {
555 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
556
557 //might be windows installation.
558 $firstVar = array_shift($pathVars);
559 if ($firstVar) {
560 $cmsRoot = $firstVar;
561 }
562
563 //start w/ csm dir search.
564 foreach ($pathVars as $var) {
565 $cmsRoot .= "/$var";
566 if ($this->validInstallDir($cmsRoot)) {
567 //stop as we found bootstrap.
568 $valid = TRUE;
569 break;
570 }
571 }
572 }
573
574 return ($valid) ? $cmsRoot : NULL;
575 }
576
577 /**
578 * @param array $params
579 * @param $mail
580 *
581 * @return mixed
582 */
583 public function createUser(&$params, $mail) {
584 $user_data = array(
585 'ID' => '',
586 'user_pass' => $params['cms_pass'],
587 'user_login' => $params['cms_name'],
588 'user_email' => $params[$mail],
589 'nickname' => $params['cms_name'],
590 'role' => get_option('default_role'),
591 );
592 if (isset($params['contactID'])) {
593 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
594 if ($contactType == 'Individual') {
595 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
596 $params['contactID'], 'first_name'
597 );
598 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
599 $params['contactID'], 'last_name'
600 );
601 }
602 }
603
604 $uid = wp_insert_user($user_data);
605
606 $creds = array();
607 $creds['user_login'] = $params['cms_name'];
608 $creds['user_password'] = $params['cms_pass'];
609 $creds['remember'] = TRUE;
610 $user = wp_signon($creds, FALSE);
611
612 wp_new_user_notification($uid, $user_data['user_pass']);
613 return $uid;
614 }
615
616 /**
617 * Change user name in host CMS
618 *
619 * @param int $ufID
620 * User ID in CMS.
621 * @param string $ufName
622 * User name.
623 */
624 public function updateCMSName($ufID, $ufName) {
625 // CRM-10620
626 if (function_exists('wp_update_user')) {
627 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
628 $ufName = CRM_Utils_Type::escape($ufName, 'String');
629
630 $values = array('ID' => $ufID, 'user_email' => $ufName);
631 if ($ufID) {
632 wp_update_user($values);
633 }
634 }
635 }
636
637 /**
638 * @param array $params
639 * @param $errors
640 * @param string $emailName
641 */
642 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
643 $config = CRM_Core_Config::singleton();
644
645 $dao = new CRM_Core_DAO();
646 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
647 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
648
649 if (!empty($params['name'])) {
650 if (!validate_username($params['name'])) {
651 $errors['cms_name'] = ts("Your username contains invalid characters");
652 }
653 elseif (username_exists(sanitize_user($params['name']))) {
654 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
655 }
656 }
657
658 if (!empty($params['mail'])) {
659 if (!is_email($params['mail'])) {
660 $errors[$emailName] = "Your email is invaid";
661 }
662 elseif (email_exists($params['mail'])) {
663 $resetUrl = $config->userFrameworkBaseURL . 'wp-login.php?action=lostpassword';
664 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
665 array(1 => $params['mail'], 2 => $resetUrl)
666 );
667 }
668 }
669 }
670
671 /**
672 * Check is user logged in.
673 *
674 * @return boolean true/false.
675 */
676 public function isUserLoggedIn() {
677 $isloggedIn = FALSE;
678 if (function_exists('is_user_logged_in')) {
679 $isloggedIn = is_user_logged_in();
680 }
681
682 return $isloggedIn;
683 }
684
685 /**
686 * @return mixed
687 */
688 public function getLoggedInUserObject() {
689 if (function_exists('is_user_logged_in') &&
690 is_user_logged_in()) {
691 global $current_user;
692 }
693 return $current_user;
694 }
695 /**
696 * Get currently logged in user uf id.
697 *
698 * @return int $userID logged in user uf id.
699 */
700 public function getLoggedInUfID() {
701 $ufID = NULL;
702 $current_user = $this->getLoggedInUserObject();
703 return isset($current_user->ID) ? $current_user->ID : NULL;
704 }
705
706 /**
707 * Get currently logged in user unique identifier - this tends to be the email address or user name.
708 *
709 * @return string $userID 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 * @return mixed <NULL, number>
721 */
722 public function getUserIDFromUserObject($user) {
723 return !empty($user->ID) ? $user->ID : NULL;
724 }
725
726 /**
727 * Get Unique Identifier from UserFramework system (CMS)
728 * @param object $user
729 * Object as described by the User Framework.
730 * @return mixed $uniqueIdentifer Unique identifier from the user Framework system
731 *
732 */
733 public function getUniqueIdentifierFromUserObject($user) {
734 return empty($user->user_email) ? NULL : $user->user_email;
735 }
736
737 /**
738 * Get user login URL for hosting CMS (method declared in each CMS system class)
739 *
740 * @param string $destination
741 * If present, add destination to querystring (works for Drupal only).
742 *
743 * @return string - loginURL for the current CMS
744 *
745 */
746 public function getLoginURL($destination = '') {
747 $config = CRM_Core_Config::singleton();
748 $loginURL = $config->userFrameworkBaseURL;
749 $loginURL .= 'wp-login.php';
750 return $loginURL;
751 }
752
753 /**
754 * @param CRM_Core_Form $form
755 */
756 public function getLoginDestination(&$form) {
757 return;
758 }
759
760 /**
761 * Return the current WordPress version if relevant function exists
762 *
763 * @return string - version number
764 *
765 */
766 public function getVersion() {
767 if (function_exists('get_bloginfo')) {
768 return get_bloginfo('version', 'display');
769 }
770 else {
771 return 'Unknown';
772 }
773 }
774
775 /**
776 * Get timezone as a string
777 * @return string Timezone e.g. 'America/Los_Angeles'
778 */
779 public function getTimeZoneString() {
780 return get_option('timezone_string');
781 }
782
783 /**
784 * Get Url to view user record
785 * @param int $contactID
786 * Contact ID.
787 *
788 * @return string
789 */
790 public function getUserRecordUrl($contactID) {
791 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
792 if (CRM_Core_Session::singleton()->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array('cms:administer users'))) {
793 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
794 }
795 }
796 }