Merge pull request #4971 from kurund/batch-16
[civicrm-core.git] / CRM / Utils / System / DrupalBase.php
... / ...
CommitLineData
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 * Drupal specific stuff goes here
38 */
39abstract 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 * @param string $dir base civicrm directory
63 * Return default Site Settings
64 * @return array
65 * array
66 * - $url, (Joomla - non admin url)
67 * - $siteName,
68 * - $siteRoot
69 */
70 public function getDefaultSiteSettings($dir) {
71 $config = CRM_Core_Config::singleton();
72 $siteName = $siteRoot = NULL;
73 $matches = array();
74 if (preg_match(
75 '|/sites/([\w\.\-\_]+)/|',
76 $config->templateCompileDir,
77 $matches
78 )) {
79 $siteName = $matches[1];
80 if ($siteName) {
81 $siteName = "/sites/$siteName/";
82 $siteNamePos = strpos($dir, $siteName);
83 if ($siteNamePos !== FALSE) {
84 $siteRoot = substr($dir, 0, $siteNamePos);
85 }
86 }
87 }
88 $url = $config->userFrameworkBaseURL;
89 return array($url, $siteName, $siteRoot);
90 }
91
92 /**
93 * Check if a resource url is within the drupal directory and format appropriately
94 *
95 * @param $url (reference)
96 *
97 * @return bool
98 * TRUE for internal paths, FALSE for external. The drupal_add_js fn is able to add js more
99 * efficiently if it is known to be in the drupal site
100 */
101 public function formatResourceUrl(&$url) {
102 $internal = FALSE;
103 $base = CRM_Core_Config::singleton()->resourceBase;
104 global $base_url;
105 // Handle absolute urls
106 // 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)
107 // to see if the url is within our drupal dir, if it is we are able to treated it as an internal url
108 if (strpos($url, $base_url) === 0) {
109 $internal = TRUE;
110 $url = trim(str_replace($base_url, '', $url), '/');
111 }
112 // Handle relative urls that are within the CiviCRM module directory
113 elseif (strpos($url, $base) === 0) {
114 $internal = TRUE;
115 $url = $this->appendCoreDirectoryToResourceBase(substr(drupal_get_path('module', 'civicrm'), 0, -6)) . trim(substr($url, strlen($base)), '/');
116 }
117 // Strip query string
118 $q = strpos($url, '?');
119 if ($q && $internal) {
120 $url = substr($url, 0, $q);
121 }
122 return $internal;
123 }
124
125 /**
126 * In instance where civicrm folder has a drupal folder & a civicrm core folder @ the same level append the
127 * civicrm folder name to the url
128 * See CRM-13737 for discussion of how this allows implementers to alter the folder structure
129 * @todo - this only provides a limited amount of flexiblity - it still expects a 'civicrm' folder with a 'drupal' folder
130 * and is only flexible as to the name of the civicrm folder.
131 *
132 * @param string $url
133 * Potential resource url based on standard folder assumptions.
134 * @return string
135 * with civicrm-core directory appended if not standard civi dir
136 */
137 public function appendCoreDirectoryToResourceBase($url) {
138 global $civicrm_root;
139 $lastDirectory = basename($civicrm_root);
140 if ($lastDirectory != 'civicrm') {
141 return $url .= $lastDirectory . '/';
142 }
143 return $url;
144 }
145
146 /**
147 * Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
148 *
149 * @param string $path
150 * The path being linked to, such as "civicrm/add".
151 * @param string $query
152 * A query string to append to the link.
153 * @param bool $absolute
154 * Whether to force the output to be an absolute link (beginning with http:).
155 * Useful for links that will be displayed outside the site, such as in an
156 * RSS feed.
157 * @param string $fragment
158 * A fragment identifier (named anchor) to append to the link.
159 * @param bool $htmlize
160 * whether to convert to html eqivalant.
161 * @param bool $frontend
162 * a gross joomla hack.
163 * @param bool $forceBackend
164 * a gross joomla hack.
165 *
166 * @return string
167 * an HTML string containing a link to the given path.
168 */
169 public function url(
170 $path = NULL, $query = NULL, $absolute = FALSE,
171 $fragment = NULL, $htmlize = TRUE,
172 $frontend = FALSE, $forceBackend = FALSE
173 ) {
174 $config = CRM_Core_Config::singleton();
175 $script = 'index.php';
176
177 $path = CRM_Utils_String::stripPathChars($path);
178
179 if (isset($fragment)) {
180 $fragment = '#' . $fragment;
181 }
182
183 if (!isset($config->useFrameworkRelativeBase)) {
184 $base = parse_url($config->userFrameworkBaseURL);
185 $config->useFrameworkRelativeBase = $base['path'];
186 }
187 $base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
188
189 $separator = $htmlize ? '&amp;' : '&';
190
191 if (!$config->cleanURL) {
192 if (isset($path)) {
193 if (isset($query)) {
194 return $base . $script . '?q=' . $path . $separator . $query . $fragment;
195 }
196 else {
197 return $base . $script . '?q=' . $path . $fragment;
198 }
199 }
200 else {
201 if (isset($query)) {
202 return $base . $script . '?' . $query . $fragment;
203 }
204 else {
205 return $base . $fragment;
206 }
207 }
208 }
209 else {
210 if (isset($path)) {
211 if (isset($query)) {
212 return $base . $path . '?' . $query . $fragment;
213 }
214 else {
215 return $base . $path . $fragment;
216 }
217 }
218 else {
219 if (isset($query)) {
220 return $base . $script . '?' . $query . $fragment;
221 }
222 else {
223 return $base . $fragment;
224 }
225 }
226 }
227 }
228
229 /**
230 * Get User ID from UserFramework system (Drupal)
231 * @param object $user
232 * Object as described by the CMS.
233 * @return mixed
234 * <NULL, number>
235 */
236 public function getUserIDFromUserObject($user) {
237 return !empty($user->uid) ? $user->uid : NULL;
238 }
239
240 /**
241 * Get Unique Identifier from UserFramework system (CMS)
242 * @param object $user
243 * Object as described by the User Framework.
244 * @return mixed
245 * $uniqueIdentifer Unique identifier from the user Framework system
246 */
247 public function getUniqueIdentifierFromUserObject($user) {
248 return empty($user->mail) ? NULL : $user->mail;
249 }
250
251 /**
252 * Get currently logged in user unique identifier - this tends to be the email address or user name.
253 *
254 * @return string
255 * logged in user unique identifier
256 */
257 public function getLoggedInUniqueIdentifier() {
258 global $user;
259 return $this->getUniqueIdentifierFromUserObject($user);
260 }
261
262 /**
263 * Action to take when access is not permitted
264 */
265 public function permissionDenied() {
266 drupal_access_denied();
267 }
268
269 /**
270 * Get Url to view user record
271 * @param int $contactID
272 * Contact ID.
273 *
274 * @return string
275 */
276 public function getUserRecordUrl($contactID) {
277 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
278 if (CRM_Core_Session::singleton()
279 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array(
280 'cms:administer users',
281 'cms:view user account',
282 ))
283 ) {
284 return CRM_Utils_System::url('user/' . $uid);
285 };
286 }
287
288 /**
289 * Is the current user permitted to add a user
290 * @return bool
291 */
292 public function checkPermissionAddUser() {
293 if (CRM_Core_Permission::check('administer users')) {
294 return TRUE;
295 }
296 }
297
298
299 /**
300 * Log error to CMS
301 */
302 public function logger($message) {
303 if (CRM_Core_Config::singleton()->userFrameworkLogging) {
304 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG);
305 }
306 }
307
308 /**
309 * Flush css/js caches
310 */
311 public function clearResourceCache() {
312 _drupal_flush_css_js();
313 }
314
315 /**
316 * Append to coreResourcesList
317 */
318 public function appendCoreResources(&$list) {
319 $list[] = 'js/crm.drupal.js';
320 }
321
322 /**
323 * Reset any system caches that may be required for proper CiviCRM
324 * integration.
325 */
326 public function flush() {
327 drupal_flush_all_caches();
328 }
329
330 /**
331 * Get a list of all installed modules, including enabled and disabled ones
332 *
333 * @return array
334 * CRM_Core_Module
335 */
336 public function getModules() {
337 $result = array();
338 $q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
339 foreach ($q as $row) {
340 $result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
341 }
342 return $result;
343 }
344
345 /**
346 * Find any users/roles/security-principals with the given permission
347 * and replace it with one or more permissions.
348 *
349 * @param string $oldPerm
350 * @param array $newPerms
351 * Array, strings.
352 *
353 * @return void
354 */
355 public function replacePermission($oldPerm, $newPerms) {
356 $roles = user_roles(FALSE, $oldPerm);
357 if (!empty($roles)) {
358 foreach (array_keys($roles) as $rid) {
359 user_role_revoke_permissions($rid, array($oldPerm));
360 user_role_grant_permissions($rid, $newPerms);
361 }
362 }
363 }
364
365 /**
366 * Format the url as per language Negotiation.
367 *
368 * @param string $url
369 *
370 * @return string
371 * , formatted url.
372 */
373 public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
374 if (empty($url)) {
375 return $url;
376 }
377
378 //CRM-7803 -from d7 onward.
379 $config = CRM_Core_Config::singleton();
380 if (function_exists('variable_get') &&
381 module_exists('locale') &&
382 function_exists('language_negotiation_get')
383 ) {
384 global $language;
385
386 //does user configuration allow language
387 //support from the URL (Path prefix or domain)
388 if (language_negotiation_get('language') == 'locale-url') {
389 $urlType = variable_get('locale_language_negotiation_url_part');
390
391 //url prefix
392 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
393 if (isset($language->prefix) && $language->prefix) {
394 if ($addLanguagePart) {
395 $url .= $language->prefix . '/';
396 }
397 if ($removeLanguagePart) {
398 $url = str_replace("/{$language->prefix}/", '/', $url);
399 }
400 }
401 }
402 //domain
403 if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
404 if (isset($language->domain) && $language->domain) {
405 if ($addLanguagePart) {
406 $url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $language->domain . base_path();
407 }
408 if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
409 $url = str_replace('\\', '/', $url);
410 $parseUrl = parse_url($url);
411
412 //kinda hackish but not sure how to do it right
413 //hope http_build_url() will help at some point.
414 if (is_array($parseUrl) && !empty($parseUrl)) {
415 $urlParts = explode('/', $url);
416 $hostKey = array_search($parseUrl['host'], $urlParts);
417 $ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
418 $urlParts[$hostKey] = $ufUrlParts['host'];
419 $url = implode('/', $urlParts);
420 }
421 }
422 }
423 }
424 }
425 }
426 return $url;
427 }
428
429 /**
430 * GET CMS Version
431 * @return string
432 */
433 public function getVersion() {
434 return defined('VERSION') ? VERSION : 'Unknown';
435 }
436
437 /**
438 */
439 public function updateCategories() {
440 // copied this from profile.module. Seems a bit inefficient, but i dont know a better way
441 // CRM-3600
442 cache_clear_all();
443 menu_rebuild();
444 }
445
446 /**
447 * Get the locale set in the hosting CMS
448 *
449 * @return string
450 * with the locale or null for none
451 */
452 public function getUFLocale() {
453 // return CiviCRM’s xx_YY locale that either matches Drupal’s Chinese locale
454 // (for CRM-6281), Drupal’s xx_YY or is retrieved based on Drupal’s xx
455 // sometimes for CLI based on order called, this might not be set and/or empty
456 global $language;
457
458 if (empty($language)) {
459 return NULL;
460 }
461
462 if ($language->language == 'zh-hans') {
463 return 'zh_CN';
464 }
465
466 if ($language->language == 'zh-hant') {
467 return 'zh_TW';
468 }
469
470 if (preg_match('/^.._..$/', $language->language)) {
471 return $language->language;
472 }
473
474 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
475 }
476
477 /**
478 * Perform any post login activities required by the UF -
479 * e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
480 * calls hook_user op 'login' and generates a new session.
481 *
482 * @param array $params
483 *
484 * FIXME: Document values accepted/required by $params
485 */
486 public function userLoginFinalize($params = array()) {
487 user_login_finalize($params);
488 }
489
490 /**
491 * Figure out the post url for the form
492 *
493 * @param mix $action
494 * The default action if one is pre-specified.
495 *
496 * @return string
497 * the url to post the form
498 */
499 public function postURL($action) {
500 if (!empty($action)) {
501 return $action;
502 }
503 return $this->url($_GET['q']);
504 }
505}