Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-11-02-19-51-55
[civicrm-core.git] / CRM / Utils / System / DrupalBase.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35
36 /**
37 * Drupal specific stuff goes here
38 */
39 abstract class CRM_Utils_System_DrupalBase extends CRM_Utils_System_Base {
40
41 /**
42 * Does this CMS / UF support a CMS specific logging mechanism?
43 * @todo - we should think about offering up logging mechanisms in a way that is also extensible by extensions
44 * @var bool
45 */
46 var $supports_UF_Logging = TRUE;
47
48 /**
49 */
50 public function __construct() {
51 /**
52 * 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
53 * functions and leave the codebase oblivious to the type of CMS
54 * @deprecated
55 * @var bool
56 */
57 $this->is_drupal = TRUE;
58 $this->supports_form_extensions = TRUE;
59 }
60
61 /**
62 * @inheritDoc
63 */
64 public function getDefaultSiteSettings($dir) {
65 $config = CRM_Core_Config::singleton();
66 $siteName = $siteRoot = NULL;
67 $matches = array();
68 if (preg_match(
69 '|/sites/([\w\.\-\_]+)/|',
70 $config->templateCompileDir,
71 $matches
72 )) {
73 $siteName = $matches[1];
74 if ($siteName) {
75 $siteName = "/sites/$siteName/";
76 $siteNamePos = strpos($dir, $siteName);
77 if ($siteNamePos !== FALSE) {
78 $siteRoot = substr($dir, 0, $siteNamePos);
79 }
80 }
81 }
82 $url = $config->userFrameworkBaseURL;
83 return array($url, $siteName, $siteRoot);
84 }
85
86 /**
87 * Check if a resource url is within the drupal directory and format appropriately.
88 *
89 * @param $url (reference)
90 *
91 * @return bool
92 * TRUE for internal paths, FALSE for external. The drupal_add_js fn is able to add js more
93 * efficiently if it is known to be in the drupal site
94 */
95 public function formatResourceUrl(&$url) {
96 $internal = FALSE;
97 $base = CRM_Core_Config::singleton()->resourceBase;
98 global $base_url;
99 // Handle absolute urls
100 // compares $url (which is some unknown/untrusted value from a third-party dev) to the CMS's base url (which is independent of civi's url)
101 // to see if the url is within our drupal dir, if it is we are able to treated it as an internal url
102 if (strpos($url, $base_url) === 0) {
103 $internal = TRUE;
104 $url = trim(str_replace($base_url, '', $url), '/');
105 }
106 // Handle relative urls that are within the CiviCRM module directory
107 elseif (strpos($url, $base) === 0) {
108 $internal = TRUE;
109 $url = $this->appendCoreDirectoryToResourceBase(substr(drupal_get_path('module', 'civicrm'), 0, -6)) . trim(substr($url, strlen($base)), '/');
110 }
111 // Strip query string
112 $q = strpos($url, '?');
113 if ($q && $internal) {
114 $url = substr($url, 0, $q);
115 }
116 return $internal;
117 }
118
119 /**
120 * In instance where civicrm folder has a drupal folder & a civicrm core folder @ the same level append the
121 * civicrm folder name to the url
122 * See CRM-13737 for discussion of how this allows implementers to alter the folder structure
123 * @todo - this only provides a limited amount of flexiblity - it still expects a 'civicrm' folder with a 'drupal' folder
124 * and is only flexible as to the name of the civicrm folder.
125 *
126 * @param string $url
127 * Potential resource url based on standard folder assumptions.
128 * @return string
129 * with civicrm-core directory appended if not standard civi dir
130 */
131 public function appendCoreDirectoryToResourceBase($url) {
132 global $civicrm_root;
133 $lastDirectory = basename($civicrm_root);
134 if ($lastDirectory != 'civicrm') {
135 return $url .= $lastDirectory . '/';
136 }
137 return $url;
138 }
139
140 /**
141 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
142 *
143 * @inheritDoc
144 */
145 public function url(
146 $path = NULL,
147 $query = NULL,
148 $absolute = FALSE,
149 $fragment = NULL,
150 $htmlize = TRUE,
151 $frontend = FALSE,
152 $forceBackend = FALSE
153 ) {
154 $config = CRM_Core_Config::singleton();
155 $script = 'index.php';
156
157 $path = CRM_Utils_String::stripPathChars($path);
158
159 if (isset($fragment)) {
160 $fragment = '#' . $fragment;
161 }
162
163 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
164
165 $separator = $htmlize ? '&amp;' : '&';
166
167 if (!$config->cleanURL) {
168 if (isset($path)) {
169 if (isset($query)) {
170 return $base . $script . '?q=' . $path . $separator . $query . $fragment;
171 }
172 else {
173 return $base . $script . '?q=' . $path . $fragment;
174 }
175 }
176 else {
177 if (isset($query)) {
178 return $base . $script . '?' . $query . $fragment;
179 }
180 else {
181 return $base . $fragment;
182 }
183 }
184 }
185 else {
186 if (isset($path)) {
187 if (isset($query)) {
188 return $base . $path . '?' . $query . $fragment;
189 }
190 else {
191 return $base . $path . $fragment;
192 }
193 }
194 else {
195 if (isset($query)) {
196 return $base . $script . '?' . $query . $fragment;
197 }
198 else {
199 return $base . $fragment;
200 }
201 }
202 }
203 }
204
205 /**
206 * @inheritDoc
207 */
208 public function getUserIDFromUserObject($user) {
209 return !empty($user->uid) ? $user->uid : NULL;
210 }
211
212 /**
213 * @inheritDoc
214 */
215 public function setMessage($message) {
216 drupal_set_message($message);
217 }
218
219 /**
220 * @inheritDoc
221 */
222 public function getUniqueIdentifierFromUserObject($user) {
223 return empty($user->mail) ? NULL : $user->mail;
224 }
225
226 /**
227 * @inheritDoc
228 */
229 public function getLoggedInUniqueIdentifier() {
230 global $user;
231 return $this->getUniqueIdentifierFromUserObject($user);
232 }
233
234 /**
235 * @inheritDoc
236 */
237 public function permissionDenied() {
238 drupal_access_denied();
239 }
240
241 /**
242 * @inheritDoc
243 */
244 public function getUserRecordUrl($contactID) {
245 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
246 if (CRM_Core_Session::singleton()
247 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array(
248 'cms:administer users',
249 'cms:view user account',
250 ))
251 ) {
252 return CRM_Utils_System::url('user/' . $uid);
253 };
254 }
255
256 /**
257 * @inheritDoc
258 */
259 public function checkPermissionAddUser() {
260 return CRM_Core_Permission::check('administer users');
261 }
262
263 /**
264 * @inheritDoc
265 */
266 public function logger($message) {
267 if (CRM_Core_Config::singleton()->userFrameworkLogging && function_exists('watchdog')) {
268 watchdog('civicrm', '%message', array('%message' => $message), NULL, WATCHDOG_DEBUG);
269 }
270 }
271
272 /**
273 * @inheritDoc
274 */
275 public function clearResourceCache() {
276 _drupal_flush_css_js();
277 }
278
279 /**
280 * Append Drupal js to coreResourcesList.
281 *
282 * @param array $list
283 */
284 public function appendCoreResources(&$list) {
285 $list[] = 'js/crm.drupal.js';
286 }
287
288 /**
289 * @inheritDoc
290 */
291 public function flush() {
292 drupal_flush_all_caches();
293 }
294
295 /**
296 * @inheritDoc
297 */
298 public function getModules() {
299 $result = array();
300 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
301 foreach ($q as $row) {
302 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
303 }
304 return $result;
305 }
306
307 /**
308 * Find any users/roles/security-principals with the given permission
309 * and replace it with one or more permissions.
310 *
311 * @param string $oldPerm
312 * @param array $newPerms
313 * Array, strings.
314 *
315 * @return void
316 */
317 public function replacePermission($oldPerm, $newPerms) {
318 $roles = user_roles(FALSE, $oldPerm);
319 if (!empty($roles)) {
320 foreach (array_keys($roles) as $rid) {
321 user_role_revoke_permissions($rid, array($oldPerm));
322 user_role_grant_permissions($rid, $newPerms);
323 }
324 }
325 }
326
327 /**
328 * @inheritDoc
329 */
330 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
331 if (empty($url)) {
332 return $url;
333 }
334
335 //CRM-7803 -from d7 onward.
336 $config = CRM_Core_Config::singleton();
337 if (function_exists('variable_get') &&
338 module_exists('locale') &&
339 function_exists('language_negotiation_get')
340 ) {
341 global $language;
342
343 //does user configuration allow language
344 //support from the URL (Path prefix or domain)
345 if (language_negotiation_get('language') == 'locale-url') {
346 $urlType = variable_get('locale_language_negotiation_url_part');
347
348 //url prefix
349 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
350 if (isset($language->prefix) && $language->prefix) {
351 if ($addLanguagePart) {
352 $url .= $language->prefix . '/';
353 }
354 if ($removeLanguagePart) {
355 $url = str_replace("/{$language->prefix}/", '/', $url);
356 }
357 }
358 }
359 //domain
360 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
361 if (isset($language->domain) && $language->domain) {
362 if ($addLanguagePart) {
363 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $language->domain . base_path();
364 }
365 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
366 $url = str_replace('\\', '/', $url);
367 $parseUrl = parse_url($url);
368
369 //kinda hackish but not sure how to do it right
370 //hope http_build_url() will help at some point.
371 if (is_array($parseUrl) && !empty($parseUrl)) {
372 $urlParts = explode('/', $url);
373 $hostKey = array_search($parseUrl['host'], $urlParts);
374 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
375 $urlParts[$hostKey] = $ufUrlParts['host'];
376 $url = implode('/', $urlParts);
377 }
378 }
379 }
380 }
381 }
382 }
383 return $url;
384 }
385
386 /**
387 * @inheritDoc
388 */
389 public function getVersion() {
390 return defined('VERSION') ? VERSION : 'Unknown';
391 }
392
393 /**
394 * @inheritDoc
395 */
396 public function updateCategories() {
397 // copied this from profile.module. Seems a bit inefficient, but i don't know a better way
398 cache_clear_all();
399 menu_rebuild();
400 }
401
402 /**
403 * @inheritDoc
404 */
405 public function getUFLocale() {
406 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
407 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
408 // sometimes for CLI based on order called, this might not be set and/or empty
409 global $language;
410
411 if (empty($language)) {
412 return NULL;
413 }
414
415 if ($language->language == 'zh-hans') {
416 return 'zh_CN';
417 }
418
419 if ($language->language == 'zh-hant') {
420 return 'zh_TW';
421 }
422
423 if (preg_match('/^.._..$/', $language->language)) {
424 return $language->language;
425 }
426
427 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
428 }
429
430 /**
431 * @inheritDoc
432 */
433 public function setUFLocale($civicrm_language) {
434 global $language;
435
436 $langcode = substr($civicrm_language, 0, 2);
437 $languages = language_list();
438
439 if (isset($languages[$langcode])) {
440 $language = $languages[$langcode];
441
442 // Config must be re-initialized to reset the base URL
443 // otherwise links will have the wrong language prefix/domain.
444 $config = CRM_Core_Config::singleton();
445 $config->free();
446
447 return TRUE;
448 }
449
450 return FALSE;
451 }
452
453 /**
454 * Perform any post login activities required by the UF -
455 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
456 * calls hook_user op 'login' and generates a new session.
457 *
458 * @param array $params
459 *
460 * FIXME: Document values accepted/required by $params
461 */
462 public function userLoginFinalize($params = array()) {
463 user_login_finalize($params);
464 }
465
466 /**
467 * @inheritDoc
468 */
469 public function getLoginDestination(&$form) {
470 $args = NULL;
471
472 $id = $form->get('id');
473 if ($id) {
474 $args .= "&id=$id";
475 }
476 else {
477 $gid = $form->get('gid');
478 if ($gid) {
479 $args .= "&gid=$gid";
480 }
481 else {
482 // Setup Personal Campaign Page link uses pageId
483 $pageId = $form->get('pageId');
484 if ($pageId) {
485 $component = $form->get('component');
486 $args .= "&pageId=$pageId&component=$component&action=add";
487 }
488 }
489 }
490
491 $destination = NULL;
492 if ($args) {
493 // append destination so user is returned to form they came from after login
494 $destination = CRM_Utils_System::currentPath() . '?reset=1' . $args;
495 }
496 return $destination;
497 }
498
499 /**
500 * Fixme: Why are we overriding the parent function? Seems inconsistent.
501 * This version supplies slightly different params to $this->url (not absolute and html encoded) but why?
502 *
503 * @param string $action
504 *
505 * @return string
506 */
507 public function postURL($action) {
508 if (!empty($action)) {
509 return $action;
510 }
511 return $this->url($_GET['q']);
512 }
513
514 /**
515 * Get an array of user details for a contact, containing at minimum the user ID & name.
516 *
517 * @param int $contactID
518 *
519 * @return array
520 * CMS user details including
521 * - id
522 * - name (ie the system user name.
523 */
524 public function getUser($contactID) {
525 $userDetails = parent::getUser($contactID);
526 $user = $this->getUserObject($userDetails['id']);
527 $userDetails['name'] = $user->name;
528 $userDetails['email'] = $user->mail;
529 return $userDetails;
530 }
531
532 /**
533 * Load the user object.
534 *
535 * Note this function still works in drupal 6, 7 & 8 but is deprecated in Drupal 8.
536 *
537 * @param $userID
538 *
539 * @return object
540 */
541 public function getUserObject($userID) {
542 return user_load($userID);
543 }
544
545 public function parseDrupalSiteName($civicrm_root) {
546 $siteName = NULL;
547 if (strpos($civicrm_root,
548 DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . 'all' . DIRECTORY_SEPARATOR . 'modules'
549 ) === FALSE
550 ) {
551 $startPos = strpos($civicrm_root,
552 DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR
553 );
554 $endPos = strpos($civicrm_root,
555 DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR
556 );
557 if ($startPos && $endPos) {
558 // if component is in sites/SITENAME/modules
559 $siteName = substr($civicrm_root,
560 $startPos + 7,
561 $endPos - $startPos - 7
562 );
563 }
564 }
565 return $siteName;
566 }
567
568 }