Merge pull request #369 from deepak-srivastava/ninja
[civicrm-core.git] / CRM / Utils / System / WordPress.php
CommitLineData
6a488035
TO
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 */
39class 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 inlcuded 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 cmsRootPath() {
437 $cmsRoot = $valid = NULL;
438 $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
439
440 //might be windows installation.
441 $firstVar = array_shift($pathVars);
442 if ($firstVar) {
443 $cmsRoot = $firstVar;
444 }
445
446 //start w/ csm dir search.
447 foreach ($pathVars as $var) {
448 $cmsRoot .= "/$var";
449 $cmsIncludePath = "$cmsRoot/wp-includes";
450 //stop as we found bootstrap.
451 if (@opendir($cmsIncludePath) &&
452 file_exists("$cmsIncludePath/version.php")
453 ) {
454 $valid = TRUE;
455 break;
456 }
457 }
458
459 return ($valid) ? $cmsRoot : NULL;
460 }
461
462 function createUser(&$params, $mail) {
463 $user_data = array(
464 'ID' => '',
465 'user_pass' => $params['cms_pass'],
466 'user_login' => $params['cms_name'],
467 'user_email' => $params[$mail],
468 'nickname' => $params['cms_name'],
469 'role' => get_option('default_role'),
470 );
471 if (isset($params['contactID'])) {
472 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
473 if ($contactType == 'Individual') {
474 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
475 $params['contactID'], 'first_name'
476 );
477 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
478 $params['contactID'], 'last_name'
479 );
480 }
481 }
482
483 $uid = wp_insert_user($user_data);
484
485 $creds = array();
486 $creds['user_login'] = $params['cms_name'];
487 $creds['user_password'] = $params['cms_pass'];
488 $creds['remember'] = TRUE;
489 $user = wp_signon($creds, FALSE);
490
491 wp_new_user_notification($uid, $user_data['user_pass']);
492 return $uid;
493 }
494
495 /*
496 * Change user name in host CMS
497 *
498 * @param integer $ufID User ID in CMS
499 * @param string $ufName User name
500 */
501 function updateCMSName($ufID, $ufName) {
502 // CRM-10620
503 if (function_exists('wp_update_user')) {
504 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
505 $ufName = CRM_Utils_Type::escape($ufName, 'String');
506
507 $values = array ('ID' => $ufID, 'user_email' => $ufName);
508 if( $ufID ) {
509 wp_update_user( $values ) ;
510 }
511 }
512 }
513
514 function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
515 $config = CRM_Core_Config::singleton();
516
517 $dao = new CRM_Core_DAO();
518 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
519 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
520
521 if (CRM_Utils_Array::value('name', $params)) {
522 if (!validate_username($params['name'])) {
523 $errors['cms_name'] = ts("Your username contains invalid characters");
524 }
525 elseif (username_exists(sanitize_user($params['name']))) {
526 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
527 }
528 }
529
530 if (CRM_Utils_Array::value('mail', $params)) {
531 if (!is_email($params['mail'])) {
532 $errors[$emailName] = "Your email is invaid";
533 }
534 elseif (email_exists($params['mail'])) {
535 $resetUrl = $config->userFrameworkBaseURL . 'wp-login.php?action=lostpassword';
536 $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>',
537 array(1 => $params['mail'], 2 => $resetUrl)
538 );
539 }
540 }
541 }
542
543 /**
544 * check is user logged in.
545 *
546 * @return boolean true/false.
547 */
548 public function isUserLoggedIn() {
549 $isloggedIn = FALSE;
550 if (function_exists('is_user_logged_in')) {
551 $isloggedIn = is_user_logged_in();
552 }
553
554 return $isloggedIn;
555 }
556
557 /**
558 * Get currently logged in user uf id.
559 *
560 * @return int $userID logged in user uf id.
561 */
562 public function getLoggedInUfID() {
563 $ufID = NULL;
564 if (function_exists('is_user_logged_in') &&
565 is_user_logged_in()
566 ) {
567 global $current_user;
568 $ufID = $current_user->ID;
569 }
570 return $ufID;
571 }
572
573 /**
574 * Get user login URL for hosting CMS (method declared in each CMS system class)
575 *
576 * @param string $destination - if present, add destination to querystring (works for Drupal only)
577 *
578 * @return string - loginURL for the current CMS
579 *
580 */
581 public function getLoginURL($destination = '') {
582 $config = CRM_Core_Config::singleton();
583 $loginURL = $config->userFrameworkBaseURL;
584 $loginURL .= 'wp-login.php';
585 return $loginURL;
586 }
587
588 public function getLoginDestination(&$form) {
589 return;
590 }
591
592 /**
593 * Return the current WordPress version if relevant function exists
594 *
595 * @return string - version number
596 *
597 */
598 function getVersion() {
599 if (function_exists('get_bloginfo')) {
600 return get_bloginfo('version', 'display');
601 }
602 else {
603 return 'Unknown';
604 }
605 }
606}
607