Merge pull request #417 from colemanw/CRM-12339
[civicrm-core.git] / CRM / Utils / System / WordPress.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 function __construct() {
41 $this->is_drupal = FALSE;
42 }
43
44 /**
45 * sets the title of the page
46 *
47 * @param string $title
48 * @paqram string $pageTitle
49 *
50 * @return void
51 * @access public
52 */
53 function setTitle($title, $pageTitle = NULL) {
54 if (!$pageTitle) {
55 $pageTitle = $title;
56 }
57 if (civicrm_wp_in_civicrm()) {
58 global $civicrm_wp_title;
59 $civicrm_wp_title = $pageTitle;
60 $template = CRM_Core_Smarty::singleton();
61 $template->assign('pageTitle', $pageTitle);
62 }
63 }
64
65 /**
66 * Append an additional breadcrumb tag to the existing breadcrumb
67 *
68 * @param string $title
69 * @param string $url
70 *
71 * @return void
72 * @access public
73 * @static
74 */
75 function appendBreadCrumb($breadCrumbs) {
76 $breadCrumb = wp_get_breadcrumb();
77
78 if (is_array($breadCrumbs)) {
79 foreach ($breadCrumbs as $crumbs) {
80 if (stripos($crumbs['url'], 'id%%')) {
81 $args = array('cid', 'mid');
82 foreach ($args as $a) {
83 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
84 FALSE, NULL, $_GET
85 );
86 if ($val) {
87 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
88 }
89 }
90 }
91 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
92 }
93 }
94
95 $template = CRM_Core_Smarty::singleton();
96 $template->assign_by_ref('breadcrumb', $breadCrumb);
97 wp_set_breadcrumb($breadCrumb);
98 }
99
100 /**
101 * Reset an additional breadcrumb tag to the existing breadcrumb
102 *
103 * @return void
104 * @access public
105 * @static
106 */
107 function resetBreadCrumb() {
108 $bc = array();
109 wp_set_breadcrumb($bc);
110 }
111
112 /**
113 * Append a string to the head of the html file
114 *
115 * @param string $head the new string to be appended
116 *
117 * @return void
118 * @access public
119 * @static
120 */
121 function addHTMLHead($head) {
122 static $registered = FALSE;
123 if (!$registered) {
124 // front-end view
125 add_action('wp_head', array(__CLASS__, '_showHTMLHead'));
126 // back-end views
127 add_action('admin_head', array(__CLASS__, '_showHTMLHead'));
128 }
129 CRM_Core_Region::instance('wp_head')->add(array(
130 'markup' => $head,
131 ));
132 }
133
134 static function _showHTMLHead() {
135 $region = CRM_Core_Region::instance('wp_head', FALSE);
136 if ($region) {
137 echo $region->render('');
138 }
139 }
140
141 /**
142 * Add a script file
143 *
144 * @param $url: string, absolute path to file
145 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
146 *
147 * Note: This function is not to be called directly
148 * @see CRM_Core_Region::render()
149 *
150 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
151 * @access public
152 */
153 public function addScriptUrl($url, $region) {
154 return FALSE;
155 }
156
157 /**
158 * Add an inline script
159 *
160 * @param $code: string, javascript code
161 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
162 *
163 * Note: This function is not to be called directly
164 * @see CRM_Core_Region::render()
165 *
166 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
167 * @access public
168 */
169 public function addScript($code, $region) {
170 return FALSE;
171 }
172
173 /**
174 * Add a css file
175 *
176 * @param $url: string, absolute path to file
177 * @param $region string, 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 TRUE if we support this operation in this CMS, FALSE otherwise
183 * @access public
184 */
185 public function addStyleUrl($url, $region) {
186 return FALSE;
187 }
188
189 /**
190 * Add an inline style
191 *
192 * @param $code: string, css code
193 * @param $region string, location within the document: 'html-header', 'page-header', 'page-footer'
194 *
195 * Note: This function is not to be called directly
196 * @see CRM_Core_Region::render()
197 *
198 * @return bool TRUE if we support this operation in this CMS, FALSE otherwise
199 * @access public
200 */
201 public function addStyle($code, $region) {
202 return FALSE;
203 }
204
205 /**
206 * rewrite various system urls to https
207 *
208 * @param null
209 *
210 * @return void
211 * @access public
212 * @static
213 */
214 function mapConfigToSSL() {
215 global $base_url;
216 $base_url = str_replace('http://', 'https://', $base_url);
217 }
218
219 /**
220 * figure out the post url for the form
221 *
222 * @param mix $action the default action if one is pre-specified
223 *
224 * @return string the url to post the form
225 * @access public
226 * @static
227 */
228 function postURL($action) {
229 if (!empty($action)) {
230 return $action;
231 }
232
233 return $this->url($_GET['q'], NULL, TRUE, NULL, FALSE);
234 }
235
236 /**
237 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
238 *
239 * @param $path string The path being linked to, such as "civicrm/add"
240 * @param $query string A query string to append to the link.
241 * @param $absolute boolean Whether to force the output to be an absolute link (beginning with http:).
242 * Useful for links that will be displayed outside the site, such as in an
243 * RSS feed.
244 * @param $fragment string A fragment identifier (named anchor) to append to the link.
245 * @param $htmlize boolean whether to convert to html eqivalant
246 * @param $frontend boolean a gross joomla hack
247 *
248 * @return string an HTML string containing a link to the given path.
249 * @access public
250 *
251 */
252 function url(
253 $path = NULL,
254 $query = NULL,
255 $absolute = FALSE,
256 $fragment = NULL,
257 $htmlize = TRUE,
258 $frontend = FALSE,
259 $forceBackend = FALSE
260 ) {
261 $config = CRM_Core_Config::singleton();
262 $script = '';
263 $separator = $htmlize ? '&amp;' : '&';
264 $pageID = '';
265
266 $path = CRM_Utils_String::stripPathChars($path);
267
268 //this means wp function we are trying to use is not available,
269 //so load bootStrap
270 if (!function_exists('get_option')) {
271 $this->loadBootStrap();
272 }
273 $permlinkStructure = get_option('permalink_structure');
274 if ($config->userFrameworkFrontend) {
275 if ($permlinkStructure != '') {
276 global $post;
277 $script = get_permalink($post->ID);
278 }
279
280 // when shortcode is included in page
281 // also make sure we have valid query object
282 global $wp_query;
283 if ( method_exists( $wp_query, 'get' ) ) {
284 if (get_query_var('page_id')) {
285 $pageID = "{$separator}page_id=" . get_query_var('page_id');
286 }
287 elseif (get_query_var('p')) {
288 // when shortcode is inserted in post
289 $pageID = "{$separator}p=" . get_query_var('p');
290 }
291 }
292 }
293
294 if (isset($fragment)) {
295 $fragment = '#' . $fragment;
296 }
297
298 if (!isset($config->useFrameworkRelativeBase)) {
299 $base = parse_url($config->userFrameworkBaseURL);
300 $config->useFrameworkRelativeBase = $base['path'];
301 }
302
303 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
304
305 if ((is_admin() && !$frontend) || $forceBackend) {
306 $base .= 'wp-admin/admin.php';
307 }
308 elseif (defined('CIVICRM_UF_WP_BASEPAGE')) {
309 $base .= CIVICRM_UF_WP_BASEPAGE;
310 }
311
312 if (isset($path)) {
313 if (isset($query)) {
314 if ($permlinkStructure != '' && ($pageID || $script != '')) {
315 return $script . '?page=CiviCRM&q=' . $path . $pageID . $separator . $query . $fragment;
316 }
317 else {
318 return $base . '?page=CiviCRM&q=' . $path . $pageID . $separator . $query . $fragment;
319 }
320 }
321 else {
322 if ($permlinkStructure != '' && ($pageID || $script != '')) {
323 return $script . '?page=CiviCRM&q=' . $path . $pageID . $fragment;
324 }
325 else {
326 return $base .'?page=CiviCRM&q=' . $path . $pageID . $fragment;
327 }
328 }
329 }
330 else {
331 if (isset($query)) {
332 if ($permlinkStructure != '' && ($pageID || $script != '')) {
333 return $script . '?' . $query . $pageID . $fragment;
334 }
335 else {
336 return $base . $script . '?' . $query . $pageID . $fragment;
337 }
338 }
339 else {
340 return $base . $fragment;
341 }
342 }
343 }
344
345 /**
346 * Authenticate the user against the wordpress db
347 *
348 * @param string $name the user name
349 * @param string $password the password for the above user name
350 *
351 * @return mixed false if no auth
352 * array(
353 contactID, ufID, unique string ) if success
354 * @access public
355 * @static
356 */
357 function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
358 $config = CRM_Core_Config::singleton();
359
360 if ($loadCMSBootstrap) {
361 self::loadBootstrap($name, $password);
362 }
363
364 $user = wp_authenticate($name, $password);
365 if (is_a($user, 'WP_Error')) {
366 return FALSE;
367 }
368
369 // need to change this to make sure we matched only one row
370
371 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
372 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
373 if (!$contactID) {
374 return FALSE;
375 }
376 return array($contactID, $user->data->ID, mt_rand());
377 }
378
379 /**
380 * Set a message in the UF to display to a user
381 *
382 * @param string $message the message to set
383 *
384 * @access public
385 * @static
386 */
387 function setMessage($message) {
388 }
389
390 function loadUser( $user ) {
391 return true;
392 }
393
394 function permissionDenied() {
395 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
396 }
397
398 function logout() {
399 // destroy session
400 if (session_id()) {
401 session_destroy();
402 }
403 wp_logout();
404 wp_redirect(wp_login_url());
405 }
406
407 function updateCategories() {}
408
409 /**
410 * Get the locale set in the hosting CMS
411 *
412 * @return string with the locale or null for none
413 */
414 function getUFLocale() {
415 return NULL;
416 }
417
418 /**
419 * load wordpress bootstrap
420 *
421 * @param $name string optional username for login
422 * @param $pass string optional password for login
423 */
424 function loadBootStrap($name = NULL, $pass = NULL) {
425 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb;
426
427 $cmsRootPath = $this->cmsRootPath();
428 if (!$cmsRootPath) {
429 CRM_Core_Error::fatal("Could not find the install directory for WordPress");
430 }
431
432 require_once ($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php');
433 return true;
434 }
435
436 function validInstallDir($dir) {
437 $includePath = "$dir/wp-includes";
438 if (
439 @opendir($includePath) &&
440 file_exists("$includePath/version.php")
441 ) {
442 return TRUE;
443 }
444 return FALSE;
445 }
446
447 function cmsRootPath() {
448 $cmsRoot = $valid = NULL;
449 if (defined('CIVICRM_CMSDIR')) {
450 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
451 $cmsRoot = CIVICRM_CMSDIR;
452 $valid = TRUE;
453 }
454 }
455 else {
456 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
457
458 //might be windows installation.
459 $firstVar = array_shift($pathVars);
460 if ($firstVar) {
461 $cmsRoot = $firstVar;
462 }
463
464 //start w/ csm dir search.
465 foreach ($pathVars as $var) {
466 $cmsRoot .= "/$var";
467 if ($this->validInstallDir($cmsRoot)) {
468 //stop as we found bootstrap.
469 $valid = TRUE;
470 break;
471 }
472 }
473 }
474
475 return ($valid) ? $cmsRoot : NULL;
476 }
477
478 function createUser(&$params, $mail) {
479 $user_data = array(
480 'ID' => '',
481 'user_pass' => $params['cms_pass'],
482 'user_login' => $params['cms_name'],
483 'user_email' => $params[$mail],
484 'nickname' => $params['cms_name'],
485 'role' => get_option('default_role'),
486 );
487 if (isset($params['contactID'])) {
488 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
489 if ($contactType == 'Individual') {
490 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
491 $params['contactID'], 'first_name'
492 );
493 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
494 $params['contactID'], 'last_name'
495 );
496 }
497 }
498
499 $uid = wp_insert_user($user_data);
500
501 $creds = array();
502 $creds['user_login'] = $params['cms_name'];
503 $creds['user_password'] = $params['cms_pass'];
504 $creds['remember'] = TRUE;
505 $user = wp_signon($creds, FALSE);
506
507 wp_new_user_notification($uid, $user_data['user_pass']);
508 return $uid;
509 }
510
511 /*
512 * Change user name in host CMS
513 *
514 * @param integer $ufID User ID in CMS
515 * @param string $ufName User name
516 */
517 function updateCMSName($ufID, $ufName) {
518 // CRM-10620
519 if (function_exists('wp_update_user')) {
520 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
521 $ufName = CRM_Utils_Type::escape($ufName, 'String');
522
523 $values = array ('ID' => $ufID, 'user_email' => $ufName);
524 if( $ufID ) {
525 wp_update_user( $values ) ;
526 }
527 }
528 }
529
530 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
531 $config = CRM_Core_Config::singleton();
532
533 $dao = new CRM_Core_DAO();
534 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
535 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
536
537 if (CRM_Utils_Array::value('name', $params)) {
538 if (!validate_username($params['name'])) {
539 $errors['cms_name'] = ts("Your username contains invalid characters");
540 }
541 elseif (username_exists(sanitize_user($params['name']))) {
542 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
543 }
544 }
545
546 if (CRM_Utils_Array::value('mail', $params)) {
547 if (!is_email($params['mail'])) {
548 $errors[$emailName] = "Your email is invaid";
549 }
550 elseif (email_exists($params['mail'])) {
551 $resetUrl = $config->userFrameworkBaseURL . 'wp-login.php?action=lostpassword';
552 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
553 array(1 => $params['mail'], 2 => $resetUrl)
554 );
555 }
556 }
557 }
558
559 /**
560 * check is user logged in.
561 *
562 * @return boolean true/false.
563 */
564 public function isUserLoggedIn() {
565 $isloggedIn = FALSE;
566 if (function_exists('is_user_logged_in')) {
567 $isloggedIn = is_user_logged_in();
568 }
569
570 return $isloggedIn;
571 }
572
573 /**
574 * Get currently logged in user uf id.
575 *
576 * @return int $userID logged in user uf id.
577 */
578 public function getLoggedInUfID() {
579 $ufID = NULL;
580 if (function_exists('is_user_logged_in') &&
581 is_user_logged_in()
582 ) {
583 global $current_user;
584 $ufID = $current_user->ID;
585 }
586 return $ufID;
587 }
588
589 /**
590 * Get user login URL for hosting CMS (method declared in each CMS system class)
591 *
592 * @param string $destination - if present, add destination to querystring (works for Drupal only)
593 *
594 * @return string - loginURL for the current CMS
595 *
596 */
597 public function getLoginURL($destination = '') {
598 $config = CRM_Core_Config::singleton();
599 $loginURL = $config->userFrameworkBaseURL;
600 $loginURL .= 'wp-login.php';
601 return $loginURL;
602 }
603
604 public function getLoginDestination(&$form) {
605 return;
606 }
607
608 /**
609 * Return the current WordPress version if relevant function exists
610 *
611 * @return string - version number
612 *
613 */
614 function getVersion() {
615 if (function_exists('get_bloginfo')) {
616 return get_bloginfo('version', 'display');
617 }
618 else {
619 return 'Unknown';
620 }
621 }
622 }
623