bootstrap.inc

  1. 7.x drupal/includes/bootstrap.inc
  2. 5.x drupal/includes/bootstrap.inc
  3. 6.x drupal/includes/bootstrap.inc
  4. 8.x drupal/core/includes/bootstrap.inc

Functions that need to be loaded on every Drupal request.

Functions

Namesort descending Description
config_get_config_directory Returns the path of a configuration directory.
conf_path Deprecated Returns the appropriate configuration directory.
drupal_add_http_header Deprecated Sets an HTTP response header for the current page.
drupal_bootstrap Deprecated Ensures Drupal is bootstrapped to the specified phase.
drupal_classloader Initializes and returns the class loader.
drupal_classloader_register Registers an additional namespace.
drupal_generate_test_ua Generates a user agent string with a HMAC and timestamp for simpletest.
drupal_get_bootstrap_phase Deprecated Returns the current bootstrap phase for this Drupal process.
drupal_get_filename Returns and optionally sets the filename for a system resource.
drupal_get_http_header Deprecated Gets the HTTP response headers for the current page.
drupal_get_messages Returns all messages that have been set with drupal_set_message().
drupal_get_user_timezone Returns the time zone of the current user.
drupal_installation_attempted Returns TRUE if a Drupal installation is currently being attempted.
drupal_maintenance_theme Enables use of the theme system without requiring database access.
drupal_page_cache_get_cid Gets the page cache cid for this request.
drupal_page_get_cache Retrieves the current page from the cache.
drupal_page_header Deprecated Sets HTTP headers in preparation for a page response.
drupal_page_is_cacheable Determines the cacheability of the current page.
drupal_placeholder Formats text for emphasized display in a placeholder inside a sentence.
drupal_register_shutdown_function Registers a function for execution on shutdown.
drupal_send_headers Deprecated Sends the HTTP response headers that were previously set, adding defaults.
drupal_serve_page_from_cache Sets HTTP headers in preparation for a cached page response.
drupal_set_message Sets a message to display to the user.
drupal_static Provides central static variable storage.
drupal_static_reset Resets one or all centrally stored static variable(s).
drupal_validate_utf8 Checks whether a string is valid UTF-8.
drupal_valid_test_ua Returns the test prefix if this is an internal request from SimpleTest.
format_string Formats a string for HTML display by replacing variable placeholders.
language_default Deprecated Returns the default language used on the site.
language_list Deprecated Returns a list of languages set up on the site.
language_load Deprecated Loads a language object from the database.
module_implements Deprecated Determines which modules are implementing a hook.
module_invoke Deprecated Invokes a hook in a particular module.
module_list Deprecated Returns the list of enabled modules.
request_path Returns the requested URL path of the page being viewed.
request_uri Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
t Translates a string to the current language or to a given language.
watchdog Deprecated Logs a system message.
watchdog_exception Logs an exception.
_current_path @todo This is a temporary function pending refactoring Drupal to use Symfony's Request object exclusively.
_drupal_error_handler Provides custom PHP error handling.
_drupal_exception_handler Provides custom PHP exception handling.
_drupal_set_preferred_header_name Deprecated Sets the preferred name for the HTTP header.
_drupal_shutdown_function Executes registered shutdown functions.

Constants

Namesort descending Description
CONFIG_ACTIVE_DIRECTORY $config_directories key for active directory.
CONFIG_STAGING_DIRECTORY $config_directories key for staging directory.
DRUPAL_ANONYMOUS_RID Role ID for anonymous users; should match what's in the "role" table.
DRUPAL_AUTHENTICATED_RID Role ID for authenticated users; should match what's in the "role" table.
DRUPAL_BOOTSTRAP_CODE Deprecated Fourth bootstrap phase: load code for subsystems and modules.
DRUPAL_BOOTSTRAP_CONFIGURATION Deprecated First bootstrap phase: initialize configuration.
DRUPAL_BOOTSTRAP_FULL Deprecated Final bootstrap phase: initialize language, path, theme, and modules.
DRUPAL_BOOTSTRAP_KERNEL Deprecated Second bootstrap phase, initialize a kernel.
DRUPAL_BOOTSTRAP_PAGE_CACHE Deprecated Third bootstrap phase: try to serve a cached page.
DRUPAL_EXTENSION_NAME_MAX_LENGTH The maximum number of characters in a module or theme name.
DRUPAL_MINIMUM_PHP Minimum supported version of PHP.
DRUPAL_MINIMUM_PHP_MEMORY_LIMIT Minimum recommended value of PHP memory_limit.
DRUPAL_PHP_FUNCTION_PATTERN Regular expression to match PHP function names.
DRUPAL_ROOT Defines the root directory of the Drupal installation.
ERROR_REPORTING_DISPLAY_ALL Error reporting level: display all messages.
ERROR_REPORTING_DISPLAY_SOME Error reporting level: display errors and warnings.
ERROR_REPORTING_DISPLAY_VERBOSE Error reporting level: display all messages, plus backtrace information.
ERROR_REPORTING_HIDE Error reporting level: display no errors.
REQUEST_TIME Time of the current request in seconds elapsed since the Unix Epoch.
WATCHDOG_ALERT Log message severity -- Alert: action must be taken immediately.
WATCHDOG_CRITICAL Log message severity -- Critical conditions.
WATCHDOG_DEBUG Log message severity -- Debug-level messages.
WATCHDOG_EMERGENCY Log message severity -- Emergency: system is unusable.
WATCHDOG_ERROR Log message severity -- Error conditions.
WATCHDOG_INFO Log message severity -- Informational messages.
WATCHDOG_NOTICE Log message severity -- Normal but significant conditions.
WATCHDOG_WARNING Log message severity -- Warning conditions.

File

drupal/core/includes/bootstrap.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions that need to be loaded on every Drupal request.
  5. */
  6. use Drupal\Component\Datetime\DateTimePlus;
  7. use Drupal\Component\Utility\Crypt;
  8. use Drupal\Component\Utility\Environment;
  9. use Drupal\Component\Utility\SafeMarkup;
  10. use Drupal\Component\Utility\String;
  11. use Drupal\Component\Utility\Unicode;
  12. use Drupal\Core\DrupalKernel;
  13. use Drupal\Core\Extension\ExtensionDiscovery;
  14. use Drupal\Core\Site\Settings;
  15. use Drupal\Core\Utility\Error;
  16. use Symfony\Component\ClassLoader\ApcClassLoader;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Drupal\Core\Language\LanguageInterface;
  20. /**
  21. * Minimum supported version of PHP.
  22. */
  23. const DRUPAL_MINIMUM_PHP = '5.4.2';
  24. /**
  25. * Minimum recommended value of PHP memory_limit.
  26. *
  27. * @todo Reduce the memory required to install on some environments in
  28. * https://www.drupal.org/node/2289201 and then decrease this limit.
  29. */
  30. const DRUPAL_MINIMUM_PHP_MEMORY_LIMIT = '64M';
  31. /**
  32. * Error reporting level: display no errors.
  33. */
  34. const ERROR_REPORTING_HIDE = 'hide';
  35. /**
  36. * Error reporting level: display errors and warnings.
  37. */
  38. const ERROR_REPORTING_DISPLAY_SOME = 'some';
  39. /**
  40. * Error reporting level: display all messages.
  41. */
  42. const ERROR_REPORTING_DISPLAY_ALL = 'all';
  43. /**
  44. * Error reporting level: display all messages, plus backtrace information.
  45. */
  46. const ERROR_REPORTING_DISPLAY_VERBOSE = 'verbose';
  47. /**
  48. * @defgroup logging_severity_levels Logging severity levels
  49. * @{
  50. * Logging severity levels as defined in RFC 3164.
  51. *
  52. * The WATCHDOG_* constant definitions correspond to the logging severity levels
  53. * defined in RFC 3164, section 4.1.1. PHP supplies predefined LOG_* constants
  54. * for use in the syslog() function, but their values on Windows builds do not
  55. * correspond to RFC 3164. The associated PHP bug report was closed with the
  56. * comment, "And it's also not a bug, as Windows just have less log levels,"
  57. * and "So the behavior you're seeing is perfectly normal."
  58. *
  59. * @see http://www.faqs.org/rfcs/rfc3164.html
  60. * @see http://bugs.php.net/bug.php?id=18090
  61. * @see http://php.net/manual/function.syslog.php
  62. * @see http://php.net/manual/network.constants.php
  63. * @see watchdog()
  64. * @see watchdog_severity_levels()
  65. */
  66. /**
  67. * Log message severity -- Emergency: system is unusable.
  68. */
  69. const WATCHDOG_EMERGENCY = 0;
  70. /**
  71. * Log message severity -- Alert: action must be taken immediately.
  72. */
  73. const WATCHDOG_ALERT = 1;
  74. /**
  75. * Log message severity -- Critical conditions.
  76. */
  77. const WATCHDOG_CRITICAL = 2;
  78. /**
  79. * Log message severity -- Error conditions.
  80. */
  81. const WATCHDOG_ERROR = 3;
  82. /**
  83. * Log message severity -- Warning conditions.
  84. */
  85. const WATCHDOG_WARNING = 4;
  86. /**
  87. * Log message severity -- Normal but significant conditions.
  88. */
  89. const WATCHDOG_NOTICE = 5;
  90. /**
  91. * Log message severity -- Informational messages.
  92. */
  93. const WATCHDOG_INFO = 6;
  94. /**
  95. * Log message severity -- Debug-level messages.
  96. */
  97. const WATCHDOG_DEBUG = 7;
  98. /**
  99. * @} End of "defgroup logging_severity_levels".
  100. */
  101. /**
  102. * First bootstrap phase: initialize configuration.
  103. *
  104. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  105. */
  106. const DRUPAL_BOOTSTRAP_CONFIGURATION = 0;
  107. /**
  108. * Second bootstrap phase, initialize a kernel.
  109. *
  110. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  111. */
  112. const DRUPAL_BOOTSTRAP_KERNEL = 1;
  113. /**
  114. * Third bootstrap phase: try to serve a cached page.
  115. *
  116. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  117. */
  118. const DRUPAL_BOOTSTRAP_PAGE_CACHE = 2;
  119. /**
  120. * Fourth bootstrap phase: load code for subsystems and modules.
  121. *
  122. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  123. */
  124. const DRUPAL_BOOTSTRAP_CODE = 3;
  125. /**
  126. * Final bootstrap phase: initialize language, path, theme, and modules.
  127. *
  128. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  129. */
  130. const DRUPAL_BOOTSTRAP_FULL = 4;
  131. /**
  132. * Role ID for anonymous users; should match what's in the "role" table.
  133. */
  134. const DRUPAL_ANONYMOUS_RID = 'anonymous';
  135. /**
  136. * Role ID for authenticated users; should match what's in the "role" table.
  137. */
  138. const DRUPAL_AUTHENTICATED_RID = 'authenticated';
  139. /**
  140. * The maximum number of characters in a module or theme name.
  141. */
  142. const DRUPAL_EXTENSION_NAME_MAX_LENGTH = 50;
  143. /**
  144. * Time of the current request in seconds elapsed since the Unix Epoch.
  145. *
  146. * This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
  147. * since PHP 5.4.0. Float timestamps confuse most PHP functions
  148. * (including date_create()).
  149. *
  150. * @see http://php.net/manual/reserved.variables.server.php
  151. * @see http://php.net/manual/function.time.php
  152. */
  153. define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);
  154. /**
  155. * Regular expression to match PHP function names.
  156. *
  157. * @see http://php.net/manual/language.functions.php
  158. */
  159. const DRUPAL_PHP_FUNCTION_PATTERN = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
  160. /**
  161. * $config_directories key for active directory.
  162. *
  163. * @see config_get_config_directory()
  164. */
  165. const CONFIG_ACTIVE_DIRECTORY = 'active';
  166. /**
  167. * $config_directories key for staging directory.
  168. *
  169. * @see config_get_config_directory()
  170. */
  171. const CONFIG_STAGING_DIRECTORY = 'staging';
  172. /**
  173. * Defines the root directory of the Drupal installation.
  174. *
  175. * This strips two levels of directories off the current directory.
  176. */
  177. define('DRUPAL_ROOT', dirname(dirname(__DIR__)));
  178. /**
  179. * Returns the appropriate configuration directory.
  180. *
  181. * @param bool $require_settings
  182. * Only configuration directories with an existing settings.php file
  183. * will be recognized. Defaults to TRUE. During initial installation,
  184. * this is set to FALSE so that Drupal can detect a matching directory,
  185. * then create a new settings.php file in it.
  186. * @param bool $reset
  187. * Force a full search for matching directories even if one had been
  188. * found previously. Defaults to FALSE.
  189. * @param \Symfony\Component\HttpFoundation\Request $request
  190. * (optional) The current request. Defaults to \Drupal::request() or a new
  191. * request created from globals.
  192. *
  193. * @return string
  194. * The path of the matching directory.@see default.settings.php
  195. *
  196. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  197. * Use \Drupal\Core\DrupalKernel::getSitePath() instead. If the kernel is
  198. * unavailable or the site path needs to be recalculated then
  199. * Drupal\Core\DrupalKernel::findSitePath() can be used.
  200. */
  201. function conf_path($require_settings = TRUE, $reset = FALSE, Request $request = NULL) {
  202. if (!isset($request)) {
  203. if (\Drupal::hasRequest()) {
  204. $request = \Drupal::request();
  205. }
  206. // @todo Remove once external CLI scripts (Drush) are updated.
  207. else {
  208. $request = Request::createFromGlobals();
  209. }
  210. }
  211. if (\Drupal::hasService('kernel')) {
  212. $site_path = \Drupal::service('kernel')->getSitePath();
  213. }
  214. if (!isset($site_path) || empty($site_path)) {
  215. $site_path = DrupalKernel::findSitePath($request, $require_settings);
  216. }
  217. return $site_path;
  218. }
  219. /**
  220. * Returns the path of a configuration directory.
  221. *
  222. * @param string $type
  223. * (optional) The type of config directory to return. Drupal core provides
  224. * 'active' and 'staging'. Defaults to CONFIG_ACTIVE_DIRECTORY.
  225. *
  226. * @return string
  227. * The configuration directory path.
  228. */
  229. function config_get_config_directory($type = CONFIG_ACTIVE_DIRECTORY) {
  230. global $config_directories;
  231. if (!empty($config_directories[$type])) {
  232. return $config_directories[$type];
  233. }
  234. throw new \Exception(format_string('The configuration directory type %type does not exist.', array('%type' => $type)));
  235. }
  236. /**
  237. * Returns and optionally sets the filename for a system resource.
  238. *
  239. * The filename, whether provided, cached, or retrieved from the database, is
  240. * only returned if the file exists.
  241. *
  242. * This function plays a key role in allowing Drupal's resources (modules
  243. * and themes) to be located in different places depending on a site's
  244. * configuration. For example, a module 'foo' may legally be located
  245. * in any of these three places:
  246. *
  247. * core/modules/foo/foo.info.yml
  248. * modules/foo/foo.info.yml
  249. * sites/example.com/modules/foo/foo.info.yml
  250. *
  251. * Calling drupal_get_filename('module', 'foo') will give you one of
  252. * the above, depending on where the module is located.
  253. *
  254. * @param $type
  255. * The type of the item; one of 'core', 'profile', 'module', 'theme', or
  256. * 'theme_engine'.
  257. * @param $name
  258. * The name of the item for which the filename is requested. Ignored for
  259. * $type 'core'.
  260. * @param $filename
  261. * The filename of the item if it is to be set explicitly rather
  262. * than by consulting the database.
  263. *
  264. * @return
  265. * The filename of the requested item or NULL if the item is not found.
  266. */
  267. function drupal_get_filename($type, $name, $filename = NULL) {
  268. // The location of files will not change during the request, so do not use
  269. // drupal_static().
  270. static $files = array();
  271. // Type 'core' only exists to simplify application-level logic; it always maps
  272. // to the /core directory, whereas $name is ignored. It is only requested via
  273. // drupal_get_path(). /core/core.info.yml does not exist, but is required
  274. // since drupal_get_path() returns the dirname() of the returned pathname.
  275. if ($type === 'core') {
  276. return 'core/core.info.yml';
  277. }
  278. // Profiles are converted into modules in system_rebuild_module_data().
  279. // @todo Remove false-exposure of profiles as modules.
  280. $original_type = $type;
  281. if ($type == 'profile') {
  282. $type = 'module';
  283. }
  284. if (!isset($files[$type])) {
  285. $files[$type] = array();
  286. }
  287. if (isset($filename)) {
  288. $files[$type][$name] = $filename;
  289. }
  290. elseif (!isset($files[$type][$name])) {
  291. // If the pathname of the requested extension is not known, try to retrieve
  292. // the list of extension pathnames from various providers, checking faster
  293. // providers first.
  294. // Retrieve the current module list (derived from the service container).
  295. if ($type == 'module' && \Drupal::hasService('module_handler')) {
  296. foreach (\Drupal::moduleHandler()->getModuleList() as $module_name => $module) {
  297. $files[$type][$module_name] = $module->getPathname();
  298. }
  299. }
  300. // If still unknown, retrieve the file list prepared in state by
  301. // system_rebuild_module_data() and system_rebuild_theme_data().
  302. if (!isset($files[$type][$name]) && \Drupal::hasService('state')) {
  303. $files[$type] += \Drupal::state()->get('system.' . $type . '.files', array());
  304. }
  305. // If still unknown, perform a filesystem scan.
  306. if (!isset($files[$type][$name])) {
  307. $listing = new ExtensionDiscovery();
  308. // Prevent an infinite recursion by this legacy function.
  309. if ($original_type == 'profile') {
  310. $listing->setProfileDirectories(array());
  311. }
  312. foreach ($listing->scan($original_type) as $extension_name => $file) {
  313. $files[$type][$extension_name] = $file->getPathname();
  314. }
  315. }
  316. }
  317. if (isset($files[$type][$name])) {
  318. return $files[$type][$name];
  319. }
  320. }
  321. /**
  322. * Gets the page cache cid for this request.
  323. *
  324. * @param \Symfony\Component\HttpFoundation\Request $request
  325. * The request for this page.
  326. *
  327. * @return string
  328. * The cid for this request.
  329. */
  330. function drupal_page_cache_get_cid(Request $request) {
  331. $cid_parts = array(
  332. $request->getUri(),
  333. \Drupal::service('content_negotiation')->getContentType($request),
  334. );
  335. return sha1(implode(':', $cid_parts));
  336. }
  337. /**
  338. * Retrieves the current page from the cache.
  339. *
  340. * @param \Symfony\Component\HttpFoundation\Request $request
  341. * The request for this page.
  342. *
  343. * @return \Symfony\Component\HttpFoundation\Response
  344. * The response, if the page was found in the cache, NULL otherwise.
  345. */
  346. function drupal_page_get_cache(Request $request) {
  347. $cache = \Drupal::cache('render')->get(drupal_page_cache_get_cid($request));
  348. if ($cache) {
  349. return $cache->data;
  350. }
  351. }
  352. /**
  353. * Determines the cacheability of the current page.
  354. *
  355. * Note: we do not serve cached pages to authenticated users, or to anonymous
  356. * users when $_SESSION is non-empty. $_SESSION may contain status messages
  357. * from a form submission, the contents of a shopping cart, or other user-
  358. * specific content that should not be cached and displayed to other users.
  359. *
  360. * @param $allow_caching
  361. * Set to FALSE if you want to prevent this page to get cached.
  362. *
  363. * @return
  364. * TRUE if the current page can be cached, FALSE otherwise.
  365. */
  366. function drupal_page_is_cacheable($allow_caching = NULL) {
  367. $allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
  368. if (isset($allow_caching)) {
  369. $allow_caching_static = $allow_caching;
  370. }
  371. return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
  372. && PHP_SAPI !== 'cli';
  373. }
  374. /**
  375. * Sets an HTTP response header for the current page.
  376. *
  377. * Note: When sending a Content-Type header, always include a 'charset' type,
  378. * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
  379. *
  380. * @param $name
  381. * The HTTP header name, or the special 'Status' header name.
  382. * @param $value
  383. * The HTTP header value; if equal to FALSE, the specified header is unset.
  384. * If $name is 'Status', this is expected to be a status code followed by a
  385. * reason phrase, e.g. "404 Not Found".
  386. * @param $append
  387. * Whether to append the value to an existing header or to replace it.
  388. *
  389. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  390. * Use \Symfony\Component\HttpFoundation\Response->headers->set().
  391. * See https://drupal.org/node/2181523.
  392. */
  393. function drupal_add_http_header($name, $value, $append = FALSE) {
  394. // The headers as name/value pairs.
  395. $headers = &drupal_static('drupal_http_headers', array());
  396. $name_lower = strtolower($name);
  397. _drupal_set_preferred_header_name($name);
  398. if ($value === FALSE) {
  399. $headers[$name_lower] = FALSE;
  400. }
  401. elseif (isset($headers[$name_lower]) && $append) {
  402. // Multiple headers with identical names may be combined using comma (RFC
  403. // 2616, section 4.2).
  404. $headers[$name_lower] .= ',' . $value;
  405. }
  406. else {
  407. $headers[$name_lower] = $value;
  408. }
  409. }
  410. /**
  411. * Gets the HTTP response headers for the current page.
  412. *
  413. * @param $name
  414. * An HTTP header name. If omitted, all headers are returned as name/value
  415. * pairs. If an array value is FALSE, the header has been unset.
  416. *
  417. * @return
  418. * A string containing the header value, or FALSE if the header has been set,
  419. * or NULL if the header has not been set.
  420. *
  421. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  422. * Use \Symfony\Component\HttpFoundation\Response->headers->get().
  423. * See https://drupal.org/node/2181523.
  424. */
  425. function drupal_get_http_header($name = NULL) {
  426. $headers = &drupal_static('drupal_http_headers', array());
  427. if (isset($name)) {
  428. $name = strtolower($name);
  429. return isset($headers[$name]) ? $headers[$name] : NULL;
  430. }
  431. else {
  432. return $headers;
  433. }
  434. }
  435. /**
  436. * Sets the preferred name for the HTTP header.
  437. *
  438. * Header names are case-insensitive, but for maximum compatibility they should
  439. * follow "common form" (see RFC 2616, section 4.2).
  440. *
  441. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  442. * See https://drupal.org/node/2181523.
  443. */
  444. function _drupal_set_preferred_header_name($name = NULL) {
  445. static $header_names = array();
  446. if (!isset($name)) {
  447. return $header_names;
  448. }
  449. $header_names[strtolower($name)] = $name;
  450. }
  451. /**
  452. * Sends the HTTP response headers that were previously set, adding defaults.
  453. *
  454. * Headers are set in drupal_add_http_header(). Default headers are not set
  455. * if they have been replaced or unset using drupal_add_http_header().
  456. *
  457. * @param array $default_headers
  458. * (optional) An array of headers as name/value pairs.
  459. * @param bool $only_default
  460. * (optional) If TRUE and headers have already been sent, send only the
  461. * specified headers.
  462. *
  463. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  464. * See https://drupal.org/node/2181523.
  465. */
  466. function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
  467. $headers_sent = &drupal_static(__FUNCTION__, FALSE);
  468. $headers = drupal_get_http_header();
  469. if ($only_default && $headers_sent) {
  470. $headers = array();
  471. }
  472. $headers_sent = TRUE;
  473. $header_names = _drupal_set_preferred_header_name();
  474. foreach ($default_headers as $name => $value) {
  475. $name_lower = strtolower($name);
  476. if (!isset($headers[$name_lower])) {
  477. $headers[$name_lower] = $value;
  478. $header_names[$name_lower] = $name;
  479. }
  480. }
  481. foreach ($headers as $name_lower => $value) {
  482. if ($name_lower == 'status') {
  483. header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
  484. }
  485. // Skip headers that have been unset.
  486. elseif ($value !== FALSE) {
  487. header($header_names[$name_lower] . ': ' . $value);
  488. }
  489. }
  490. }
  491. /**
  492. * Sets HTTP headers in preparation for a page response.
  493. *
  494. * Authenticated users are always given a 'no-cache' header, and will fetch a
  495. * fresh page on every request. This prevents authenticated users from seeing
  496. * locally cached pages.
  497. *
  498. * Also give each page a unique ETag. This should force clients to include both
  499. * an If-Modified-Since header and an If-None-Match header when doing
  500. * conditional requests for the page (required by RFC 2616, section 13.3.4),
  501. * making the validation more robust. This is a workaround for a bug in Mozilla
  502. * Firefox that is triggered when Drupal's caching is enabled and the user
  503. * accesses Drupal via an HTTP proxy (see
  504. * https://bugzilla.mozilla.org/show_bug.cgi?id=269303): When an authenticated
  505. * user requests a page, and then logs out and requests the same page again,
  506. * Firefox may send a conditional request based on the page that was cached
  507. * locally when the user was logged in. If this page did not have an ETag
  508. * header, the request only contains an If-Modified-Since header. The date will
  509. * be recent, because with authenticated users the Last-Modified header always
  510. * refers to the time of the request. If the user accesses Drupal via a proxy
  511. * server, and the proxy already has a cached copy of the anonymous page with an
  512. * older Last-Modified date, the proxy may respond with 304 Not Modified, making
  513. * the client think that the anonymous and authenticated pageviews are
  514. * identical.
  515. *
  516. * @see drupal_page_set_cache()
  517. *
  518. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  519. * See https://drupal.org/node/2181523.
  520. */
  521. function drupal_page_header() {
  522. $headers_sent = &drupal_static(__FUNCTION__, FALSE);
  523. if ($headers_sent) {
  524. return TRUE;
  525. }
  526. $headers_sent = TRUE;
  527. $default_headers = array(
  528. 'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
  529. 'Last-Modified' => gmdate(DateTimePlus::RFC7231, REQUEST_TIME),
  530. 'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0',
  531. 'ETag' => '"' . REQUEST_TIME . '"',
  532. );
  533. drupal_send_headers($default_headers);
  534. }
  535. /**
  536. * Sets HTTP headers in preparation for a cached page response.
  537. *
  538. * The headers allow as much as possible in proxies and browsers without any
  539. * particular knowledge about the pages. Modules can override these headers
  540. * using drupal_add_http_header().
  541. *
  542. * If the request is conditional (using If-Modified-Since and If-None-Match),
  543. * and the conditions match those currently in the cache, a 304 Not Modified
  544. * response is sent.
  545. */
  546. function drupal_serve_page_from_cache(Response $response, Request $request) {
  547. // Only allow caching in the browser and prevent that the response is stored
  548. // by an external proxy server when the following conditions apply:
  549. // 1. There is a session cookie on the request.
  550. // 2. The Vary: Cookie header is on the response.
  551. // 3. The Cache-Control header does not contain the no-cache directive.
  552. if ($request->cookies->has(session_name()) &&
  553. in_array('Cookie', $response->getVary()) &&
  554. !$response->headers->hasCacheControlDirective('no-cache')) {
  555. $response->setPrivate();
  556. }
  557. // Negotiate whether to use compression.
  558. if ($response->headers->get('Content-Encoding') == 'gzip' && extension_loaded('zlib')) {
  559. if (strpos($request->headers->get('Accept-Encoding'), 'gzip') !== FALSE) {
  560. // The response content is already gzip'ed, so make sure
  561. // zlib.output_compression does not compress it once more.
  562. ini_set('zlib.output_compression', '0');
  563. }
  564. else {
  565. // The client does not support compression. Decompress the content and
  566. // remove the Content-Encoding header.
  567. $content = $response->getContent();
  568. $content = gzinflate(substr(substr($content, 10), 0, -8));
  569. $response->setContent($content);
  570. $response->headers->remove('Content-Encoding');
  571. }
  572. }
  573. // Perform HTTP revalidation.
  574. // @todo Use Response::isNotModified() as per https://drupal.org/node/2259489
  575. $last_modified = $response->getLastModified();
  576. if ($last_modified) {
  577. // See if the client has provided the required HTTP headers.
  578. $if_modified_since = $request->server->has('HTTP_IF_MODIFIED_SINCE') ? strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE')) : FALSE;
  579. $if_none_match = $request->server->has('HTTP_IF_NONE_MATCH') ? stripslashes($request->server->get('HTTP_IF_NONE_MATCH')) : FALSE;
  580. if ($if_modified_since && $if_none_match
  581. && $if_none_match == $response->getEtag() // etag must match
  582. && $if_modified_since == $last_modified->getTimestamp()) { // if-modified-since must match
  583. $response->setStatusCode(304);
  584. $response->setContent(NULL);
  585. // In the case of a 304 response, certain headers must be sent, and the
  586. // remaining may not (see RFC 2616, section 10.3.5).
  587. foreach (array_keys($response->headers->all()) as $name) {
  588. if (!in_array($name, array('content-location', 'expires', 'cache-control', 'vary'))) {
  589. $response->headers->remove($name);
  590. }
  591. }
  592. }
  593. }
  594. }
  595. /**
  596. * Translates a string to the current language or to a given language.
  597. *
  598. * The t() function serves two purposes. First, at run-time it translates
  599. * user-visible text into the appropriate language. Second, various mechanisms
  600. * that figure out what text needs to be translated work off t() -- the text
  601. * inside t() calls is added to the database of strings to be translated.
  602. * These strings are expected to be in English, so the first argument should
  603. * always be in English. To enable a fully-translatable site, it is important
  604. * that all human-readable text that will be displayed on the site or sent to
  605. * a user is passed through the t() function, or a related function. See the
  606. * @link http://drupal.org/node/322729 Localization API @endlink pages for
  607. * more information, including recommendations on how to break up or not
  608. * break up strings for translation.
  609. *
  610. * @section sec_translating_vars Translating Variables
  611. * You should never use t() to translate variables, such as calling
  612. * @code t($text); @endcode, unless the text that the variable holds has been
  613. * passed through t() elsewhere (e.g., $text is one of several translated
  614. * literal strings in an array). It is especially important never to call
  615. * @code t($user_text); @endcode, where $user_text is some text that a user
  616. * entered - doing that can lead to cross-site scripting and other security
  617. * problems. However, you can use variable substitution in your string, to put
  618. * variable text such as user names or link URLs into translated text. Variable
  619. * substitution looks like this:
  620. * @code
  621. * $text = t("@name's blog", array('@name' => user_format_name($account)));
  622. * @endcode
  623. * Basically, you can put variables like @name into your string, and t() will
  624. * substitute their sanitized values at translation time. (See the
  625. * Localization API pages referenced above and the documentation of
  626. * format_string() for details about how to define variables in your string.)
  627. * Translators can then rearrange the string as necessary for the language
  628. * (e.g., in Spanish, it might be "blog de @name").
  629. *
  630. * @param $string
  631. * A string containing the English string to translate.
  632. * @param $args
  633. * An associative array of replacements to make after translation. Based
  634. * on the first character of the key, the value is escaped and/or themed.
  635. * See format_string() for details.
  636. * @param $options
  637. * An associative array of additional options, with the following elements:
  638. * - 'langcode' (defaults to the current language): The language code to
  639. * translate to a language other than what is used to display the page.
  640. * - 'context' (defaults to the empty context): The context the source string
  641. * belongs to.
  642. *
  643. * @return
  644. * The translated string.
  645. *
  646. * @see format_string()
  647. * @ingroup sanitization
  648. */
  649. function t($string, array $args = array(), array $options = array()) {
  650. return \Drupal::translation()->translate($string, $args, $options);
  651. }
  652. /**
  653. * Formats a string for HTML display by replacing variable placeholders.
  654. *
  655. * @see \Drupal\Component\Utility\String::format()
  656. * @see t()
  657. * @ingroup sanitization
  658. */
  659. function format_string($string, array $args = array()) {
  660. return String::format($string, $args);
  661. }
  662. /**
  663. * Checks whether a string is valid UTF-8.
  664. *
  665. * All functions designed to filter input should use drupal_validate_utf8
  666. * to ensure they operate on valid UTF-8 strings to prevent bypass of the
  667. * filter.
  668. *
  669. * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
  670. * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
  671. * bytes. When these subsequent bytes are HTML control characters such as
  672. * quotes or angle brackets, parts of the text that were deemed safe by filters
  673. * end up in locations that are potentially unsafe; An onerror attribute that
  674. * is outside of a tag, and thus deemed safe by a filter, can be interpreted
  675. * by the browser as if it were inside the tag.
  676. *
  677. * The function does not return FALSE for strings containing character codes
  678. * above U+10FFFF, even though these are prohibited by RFC 3629.
  679. *
  680. * @param $text
  681. * The text to check.
  682. *
  683. * @return
  684. * TRUE if the text is valid UTF-8, FALSE if not.
  685. *
  686. * @see \Drupal\Component\Utility\Unicode::validateUtf8()
  687. */
  688. function drupal_validate_utf8($text) {
  689. return Unicode::validateUtf8($text);
  690. }
  691. /**
  692. * Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
  693. *
  694. * Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
  695. * equivalent using other environment variables.
  696. *
  697. * @todo The above comment is incorrect: http://drupal.org/node/1547294.
  698. */
  699. function request_uri($omit_query_string = FALSE) {
  700. if (isset($_SERVER['REQUEST_URI'])) {
  701. $uri = $_SERVER['REQUEST_URI'];
  702. }
  703. else {
  704. if (isset($_SERVER['argv'][0])) {
  705. $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
  706. }
  707. elseif (isset($_SERVER['QUERY_STRING'])) {
  708. $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
  709. }
  710. else {
  711. $uri = $_SERVER['SCRIPT_NAME'];
  712. }
  713. }
  714. // Prevent multiple slashes to avoid cross site requests via the Form API.
  715. $uri = '/' . ltrim($uri, '/');
  716. return $omit_query_string ? strtok($uri, '?') : $uri;
  717. }
  718. /**
  719. * Logs an exception.
  720. *
  721. * This is a wrapper function for watchdog() which automatically decodes an
  722. * exception.
  723. *
  724. * @param $type
  725. * The category to which this message belongs.
  726. * @param $exception
  727. * The exception that is going to be logged.
  728. * @param $message
  729. * The message to store in the log. If empty, a text that contains all useful
  730. * information about the passed-in exception is used.
  731. * @param $variables
  732. * Array of variables to replace in the message on display or
  733. * NULL if message is already translated or not possible to
  734. * translate.
  735. * @param $severity
  736. * The severity of the message, as per RFC 3164.
  737. * @param $link
  738. * A link to associate with the message.
  739. *
  740. * @see watchdog()
  741. * @see \Drupal\Core\Utility\Error::decodeException()
  742. */
  743. function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {
  744. // Use a default value if $message is not set.
  745. if (empty($message)) {
  746. // The exception message is run through
  747. // \Drupal\Component\Utility\String::checkPlain() by
  748. // \Drupal\Core\Utility\Error:decodeException().
  749. $message = '%type: !message in %function (line %line of %file).';
  750. }
  751. if ($link) {
  752. $variables['link'] = $link;
  753. }
  754. $variables += Error::decodeException($exception);
  755. \Drupal::logger($type)->log($severity, $message, $variables);
  756. }
  757. /**
  758. * Logs a system message.
  759. *
  760. * @param $type
  761. * The category to which this message belongs. Can be any string, but the
  762. * general practice is to use the name of the module calling watchdog().
  763. * @param $message
  764. * The message to store in the log. Keep $message translatable
  765. * by not concatenating dynamic values into it! Variables in the
  766. * message should be added by using placeholder strings alongside
  767. * the variables argument to declare the value of the placeholders.
  768. * See t() for documentation on how $message and $variables interact.
  769. * @param $variables
  770. * Array of variables to replace in the message on display or array() if
  771. * message is already translated or not possible to translate.
  772. * @param $severity
  773. * The severity of the message; one of the following values as defined in
  774. * @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
  775. * - WATCHDOG_EMERGENCY: Emergency, system is unusable.
  776. * - WATCHDOG_ALERT: Alert, action must be taken immediately.
  777. * - WATCHDOG_CRITICAL: Critical conditions.
  778. * - WATCHDOG_ERROR: Error conditions.
  779. * - WATCHDOG_WARNING: Warning conditions.
  780. * - WATCHDOG_NOTICE: (default) Normal but significant conditions.
  781. * - WATCHDOG_INFO: Informational messages.
  782. * - WATCHDOG_DEBUG: Debug-level messages.
  783. * @param $link
  784. * A link to associate with the message.
  785. *
  786. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  787. * Use \Drupal::logger($channel)->log($severity, $message, $context), or any
  788. * of the shortcut methods of \Psr\Log\LoggerTrait.
  789. *
  790. * @see watchdog_severity_levels()
  791. * @see hook_watchdog()
  792. */
  793. function watchdog($type, $message, array $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
  794. if ($link) {
  795. $variables['link'] = $link;
  796. }
  797. \Drupal::service('logger.factory')->get($type)->log($severity, $message, $variables);
  798. }
  799. /**
  800. * Sets a message to display to the user.
  801. *
  802. * Messages are stored in a session variable and displayed in the page template
  803. * via the $messages theme variable.
  804. *
  805. * Example usage:
  806. * @code
  807. * drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
  808. * @endcode
  809. *
  810. * @param string $message
  811. * (optional) The translated message to be displayed to the user. For
  812. * consistency with other messages, it should begin with a capital letter and
  813. * end with a period.
  814. * @param string $type
  815. * (optional) The message's type. Defaults to 'status'. These values are
  816. * supported:
  817. * - 'status'
  818. * - 'warning'
  819. * - 'error'
  820. * @param bool $repeat
  821. * (optional) If this is FALSE and the message is already set, then the
  822. * message won't be repeated. Defaults to FALSE.
  823. *
  824. * @return array|null
  825. * A multidimensional array with keys corresponding to the set message types.
  826. * The indexed array values of each contain the set messages for that type,
  827. * and each message is an associative array with the following format:
  828. * - safe: Boolean indicating whether the message string has been marked as
  829. * safe. Non-safe strings will be escaped automatically.
  830. * - message: The message string.
  831. * So, the following is an example of the full return array structure:
  832. * @code
  833. * array(
  834. * 'status' => array(
  835. * array(
  836. * 'safe' => TRUE,
  837. * 'message' => 'A <em>safe</em> markup string.',
  838. * ),
  839. * array(
  840. * 'safe' => FALSE,
  841. * 'message' => "$arbitrary_user_input to escape.",
  842. * ),
  843. * ),
  844. * );
  845. * @endcode
  846. * If there are no messages set, the function returns NULL.
  847. *
  848. * @see drupal_get_messages()
  849. * @see theme_status_messages()
  850. */
  851. function drupal_set_message($message = NULL, $type = 'status', $repeat = FALSE) {
  852. if ($message) {
  853. if (!isset($_SESSION['messages'][$type])) {
  854. $_SESSION['messages'][$type] = array();
  855. }
  856. if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
  857. $_SESSION['messages'][$type][] = array(
  858. 'safe' => SafeMarkup::isSafe($message),
  859. 'message' => $message,
  860. );
  861. }
  862. // Mark this page as being uncacheable.
  863. drupal_page_is_cacheable(FALSE);
  864. }
  865. // Messages not set when DB connection fails.
  866. return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
  867. }
  868. /**
  869. * Returns all messages that have been set with drupal_set_message().
  870. *
  871. * @param string $type
  872. * (optional) Limit the messages returned by type. Defaults to NULL, meaning
  873. * all types. These values are supported:
  874. * - NULL
  875. * - 'status'
  876. * - 'warning'
  877. * - 'error'
  878. * @param bool $clear_queue
  879. * (optional) If this is TRUE, the queue will be cleared of messages of the
  880. * type specified in the $type parameter. Otherwise the queue will be left
  881. * intact. Defaults to TRUE.
  882. *
  883. * @return array
  884. * An associative, nested array of messages grouped by message type, with
  885. * the top-level keys as the message type. The messages returned are
  886. * limited to the type specified in the $type parameter, if any. If there
  887. * are no messages of the specified type, an empty array is returned. See
  888. * drupal_set_message() for the array structure of indivdual messages.
  889. *
  890. * @see drupal_set_message()
  891. * @see theme_status_messages()
  892. */
  893. function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
  894. if ($messages = drupal_set_message()) {
  895. foreach ($messages as $message_type => $message_typed_messages) {
  896. foreach ($message_typed_messages as $key => $message) {
  897. if ($message['safe']) {
  898. $message['message'] = SafeMarkup::set($message['message']);
  899. }
  900. $messages[$message_type][$key] = $message['message'];
  901. }
  902. }
  903. if ($type) {
  904. if ($clear_queue) {
  905. unset($_SESSION['messages'][$type]);
  906. }
  907. if (isset($messages[$type])) {
  908. return array($type => $messages[$type]);
  909. }
  910. }
  911. else {
  912. if ($clear_queue) {
  913. unset($_SESSION['messages']);
  914. }
  915. return $messages;
  916. }
  917. }
  918. return array();
  919. }
  920. /**
  921. * Ensures Drupal is bootstrapped to the specified phase.
  922. *
  923. * In order to bootstrap Drupal from another PHP script, you can use this code:
  924. * @code
  925. * require_once '/path/to/drupal/core/vendor/autoload.php';
  926. * require_once '/path/to/drupal/core/includes/bootstrap.inc';
  927. * drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  928. * @endcode
  929. *
  930. * @param $phase
  931. * A constant telling which phase to bootstrap to. Possible values:
  932. * - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
  933. * - DRUPAL_BOOTSTRAP_KERNEL: Initalizes a kernel.
  934. *
  935. * @return int
  936. * The most recently completed phase.
  937. *
  938. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  939. * Interact directly with the kernel.
  940. */
  941. function drupal_bootstrap($phase = NULL) {
  942. // Temporary variables used for booting later legacy phases.
  943. /** @var \Drupal\Core\DrupalKernel $kernel */
  944. static $kernel;
  945. static $boot_level = 0;
  946. if (isset($phase)) {
  947. $request = Request::createFromGlobals();
  948. for ($current_phase = $boot_level; $current_phase <= $phase; $current_phase++) {
  949. switch ($current_phase) {
  950. case DRUPAL_BOOTSTRAP_CONFIGURATION:
  951. $kernel = DrupalKernel::createFromRequest($request, drupal_classloader(), 'prod');
  952. break;
  953. case DRUPAL_BOOTSTRAP_KERNEL:
  954. $kernel->boot();
  955. break;
  956. case DRUPAL_BOOTSTRAP_PAGE_CACHE:
  957. $kernel->handlePageCache($request);
  958. break;
  959. case DRUPAL_BOOTSTRAP_CODE:
  960. case DRUPAL_BOOTSTRAP_FULL:
  961. $kernel->prepareLegacyRequest($request);
  962. break;
  963. }
  964. }
  965. $boot_level = $phase;
  966. }
  967. return \Drupal::getContainer() ? DRUPAL_BOOTSTRAP_CODE : DRUPAL_BOOTSTRAP_CONFIGURATION;
  968. }
  969. /**
  970. * Returns the time zone of the current user.
  971. */
  972. function drupal_get_user_timezone() {
  973. global $user;
  974. $config = \Drupal::config('system.date');
  975. if ($user && $config->get('timezone.user.configurable') && $user->isAuthenticated() && $user->getTimezone()) {
  976. return $user->getTimezone();
  977. }
  978. else {
  979. // Ignore PHP strict notice if time zone has not yet been set in the php.ini
  980. // configuration.
  981. $config_data_default_timezone = $config->get('timezone.default');
  982. return !empty($config_data_default_timezone) ? $config_data_default_timezone : @date_default_timezone_get();
  983. }
  984. }
  985. /**
  986. * Provides custom PHP error handling.
  987. *
  988. * @param $error_level
  989. * The level of the error raised.
  990. * @param $message
  991. * The error message.
  992. * @param $filename
  993. * The filename that the error was raised in.
  994. * @param $line
  995. * The line number the error was raised at.
  996. * @param $context
  997. * An array that points to the active symbol table at the point the error
  998. * occurred.
  999. */
  1000. function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
  1001. require_once __DIR__ . '/errors.inc';
  1002. _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
  1003. }
  1004. /**
  1005. * Provides custom PHP exception handling.
  1006. *
  1007. * Uncaught exceptions are those not enclosed in a try/catch block. They are
  1008. * always fatal: the execution of the script will stop as soon as the exception
  1009. * handler exits.
  1010. *
  1011. * @param $exception
  1012. * The exception object that was thrown.
  1013. */
  1014. function _drupal_exception_handler($exception) {
  1015. require_once __DIR__ . '/errors.inc';
  1016. try {
  1017. // Log the message to the watchdog and return an error page to the user.
  1018. _drupal_log_error(Error::decodeException($exception), TRUE);
  1019. }
  1020. catch (Exception $exception2) {
  1021. // Another uncaught exception was thrown while handling the first one.
  1022. // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
  1023. if (error_displayable()) {
  1024. print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
  1025. print '<h2>Original</h2><p>' . Error::renderExceptionSafe($exception) . '</p>';
  1026. print '<h2>Additional</h2><p>' . Error::renderExceptionSafe($exception2) . '</p><hr />';
  1027. }
  1028. }
  1029. }
  1030. /**
  1031. * Returns the current bootstrap phase for this Drupal process.
  1032. *
  1033. * The current phase is the one most recently completed by drupal_bootstrap().
  1034. *
  1035. * @see drupal_bootstrap()
  1036. *
  1037. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  1038. */
  1039. function drupal_get_bootstrap_phase() {
  1040. return drupal_bootstrap();
  1041. }
  1042. /**
  1043. * Returns the list of enabled modules.
  1044. *
  1045. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  1046. * Use \Drupal::moduleHandler()->getModuleList().
  1047. *
  1048. * @see \Drupal\Core\Extension\ModuleHandler::getModuleList()
  1049. */
  1050. function module_list() {
  1051. $modules = array_keys(\Drupal::moduleHandler()->getModuleList());
  1052. return array_combine($modules, $modules);
  1053. }
  1054. /**
  1055. * Determines which modules are implementing a hook.
  1056. *
  1057. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  1058. * Use \Drupal::moduleHandler()->getImplementations($hook).
  1059. *
  1060. * @see \Drupal\Core\Extension\ModuleHandler::getImplementations()
  1061. */
  1062. function module_implements($hook) {
  1063. return \Drupal::moduleHandler()->getImplementations($hook);
  1064. }
  1065. /**
  1066. * Invokes a hook in a particular module.
  1067. *
  1068. * All arguments are passed by value. Use \Drupal::moduleHandler()->alter() if
  1069. * you need to pass arguments by reference.
  1070. *
  1071. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0. Use
  1072. * \Drupal::moduleHandler()->invoke($module, $hook, $args = array()).
  1073. *
  1074. * @see \Drupal\Core\Extension\ModuleHandler::alter()
  1075. * @see \Drupal\Core\Extension\ModuleHandler::invoke()
  1076. */
  1077. function module_invoke($module, $hook) {
  1078. $args = func_get_args();
  1079. // Remove $module and $hook from the arguments.
  1080. unset($args[0], $args[1]);
  1081. return \Drupal::moduleHandler()->invoke($module, $hook, $args);
  1082. }
  1083. /**
  1084. * Returns the test prefix if this is an internal request from SimpleTest.
  1085. *
  1086. * @param string $new_prefix
  1087. * Internal use only. A new prefix to be stored.
  1088. *
  1089. * @return string|FALSE
  1090. * Either the simpletest prefix (the string "simpletest" followed by any
  1091. * number of digits) or FALSE if the user agent does not contain a valid
  1092. * HMAC and timestamp.
  1093. */
  1094. function drupal_valid_test_ua($new_prefix = NULL) {
  1095. static $test_prefix;
  1096. if (isset($new_prefix)) {
  1097. $test_prefix = $new_prefix;
  1098. }
  1099. if (isset($test_prefix)) {
  1100. return $test_prefix;
  1101. }
  1102. // Unless the below User-Agent and HMAC validation succeeds, we are not in
  1103. // a test environment.
  1104. $test_prefix = FALSE;
  1105. // Perform a basic check on the User-Agent HTTP request header first. Any
  1106. // inbound request that uses the simpletest UA header needs to be validated.
  1107. if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
  1108. list(, $prefix, $time, $salt, $hmac) = $matches;
  1109. $check_string = $prefix . ';' . $time . ';' . $salt;
  1110. // Read the hash salt prepared by drupal_generate_test_ua().
  1111. // This function is called before settings.php is read and Drupal's error
  1112. // handlers are set up. While Drupal's error handling may be properly
  1113. // configured on production sites, the server's PHP error_reporting may not.
  1114. // Ensure that no information leaks on production sites.
  1115. $key_file = DRUPAL_ROOT . '/sites/simpletest/' . substr($prefix, 10) . '/.htkey';
  1116. if (!is_readable($key_file)) {
  1117. header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
  1118. exit;
  1119. }
  1120. $private_key = file_get_contents($key_file);
  1121. // The file properties add more entropy not easily accessible to others.
  1122. $key = $private_key . filectime(__FILE__) . fileinode(__FILE__);
  1123. $time_diff = REQUEST_TIME - $time;
  1124. $test_hmac = Crypt::hmacBase64($check_string, $key);
  1125. // Since we are making a local request a 5 second time window is allowed,
  1126. // and the HMAC must match.
  1127. if ($time_diff >= 0 && $time_diff <= 5 && $hmac === $test_hmac) {
  1128. $test_prefix = $prefix;
  1129. }
  1130. }
  1131. return $test_prefix;
  1132. }
  1133. /**
  1134. * Generates a user agent string with a HMAC and timestamp for simpletest.
  1135. */
  1136. function drupal_generate_test_ua($prefix) {
  1137. static $key, $last_prefix;
  1138. if (!isset($key) || $last_prefix != $prefix) {
  1139. $last_prefix = $prefix;
  1140. $key_file = DRUPAL_ROOT . '/sites/simpletest/' . substr($prefix, 10) . '/.htkey';
  1141. // When issuing an outbound HTTP client request from within an inbound test
  1142. // request, then the outbound request has to use the same User-Agent header
  1143. // as the inbound request. A newly generated private key for the same test
  1144. // prefix would invalidate all subsequent inbound requests.
  1145. // @see \Drupal\Core\Http\Plugin\SimpletestHttpRequestSubscriber
  1146. if (DRUPAL_TEST_IN_CHILD_SITE && $parent_prefix = drupal_valid_test_ua()) {
  1147. if ($parent_prefix != $prefix) {
  1148. throw new \RuntimeException("Malformed User-Agent: Expected '$parent_prefix' but got '$prefix'.");
  1149. }
  1150. // If the file is not readable, a PHP warning is expected in this case.
  1151. $private_key = file_get_contents($key_file);
  1152. }
  1153. else {
  1154. // Generate and save a new hash salt for a test run.
  1155. // Consumed by drupal_valid_test_ua() before settings.php is loaded.
  1156. $private_key = Crypt::randomBytesBase64(55);
  1157. file_put_contents($key_file, $private_key);
  1158. }
  1159. // The file properties add more entropy not easily accessible to others.
  1160. $key = $private_key . filectime(__FILE__) . fileinode(__FILE__);
  1161. }
  1162. // Generate a moderately secure HMAC based on the database credentials.
  1163. $salt = uniqid('', TRUE);
  1164. $check_string = $prefix . ';' . time() . ';' . $salt;
  1165. return $check_string . ';' . Crypt::hmacBase64($check_string, $key);
  1166. }
  1167. /**
  1168. * Enables use of the theme system without requiring database access.
  1169. *
  1170. * Loads and initializes the theme system for site installs, updates and when
  1171. * the site is in maintenance mode. This also applies when the database fails.
  1172. *
  1173. * @see _drupal_maintenance_theme()
  1174. */
  1175. function drupal_maintenance_theme() {
  1176. require_once __DIR__ . '/theme.maintenance.inc';
  1177. _drupal_maintenance_theme();
  1178. }
  1179. /**
  1180. * Returns TRUE if a Drupal installation is currently being attempted.
  1181. */
  1182. function drupal_installation_attempted() {
  1183. // This cannot rely on the MAINTENANCE_MODE constant, since that would prevent
  1184. // tests from using the non-interactive installer, in which case Drupal
  1185. // only happens to be installed within the same request, but subsequently
  1186. // executed code does not involve the installer at all.
  1187. // @see install_drupal()
  1188. return isset($GLOBALS['install_state']) && empty($GLOBALS['install_state']['installation_finished']);
  1189. }
  1190. /**
  1191. * Returns a list of languages set up on the site.
  1192. *
  1193. * @param $flags
  1194. * (optional) Specifies the state of the languages that have to be returned.
  1195. * It can be: LanguageInterface::STATE_CONFIGURABLE,
  1196. * LanguageInterface::STATE_LOCKED, LanguageInterface::STATE_ALL.
  1197. *
  1198. * @return array
  1199. * An associative array of languages, keyed by the language code, ordered by
  1200. * weight ascending and name ascending.
  1201. *
  1202. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  1203. * Use \Drupal::languageManager()->getLanguages().
  1204. */
  1205. function language_list($flags = LanguageInterface::STATE_CONFIGURABLE) {
  1206. return \Drupal::languageManager()->getLanguages($flags);
  1207. }
  1208. /**
  1209. * Loads a language object from the database.
  1210. *
  1211. * @param string $langcode
  1212. * The language code.
  1213. *
  1214. * @return \Drupal\core\Language\LanguageInterface|null
  1215. * A fully-populated language object or NULL.
  1216. *
  1217. * @see \Drupal\Core\Language\LanguageManager::getLanguage()
  1218. *
  1219. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  1220. * Use \Drupal::languageManager()->getLanguage().
  1221. */
  1222. function language_load($langcode) {
  1223. return \Drupal::languageManager()->getLanguage($langcode);
  1224. }
  1225. /**
  1226. * Returns the default language used on the site.
  1227. *
  1228. * @return \Drupal\Core\Language\LanguageInterface
  1229. * A language object.
  1230. *
  1231. * @see \Drupal\Core\Language\LanguageManager::getLanguage()
  1232. *
  1233. * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
  1234. * Use \Drupal::languageManager()->getDefaultLanguage().
  1235. */
  1236. function language_default() {
  1237. return \Drupal::languageManager()->getDefaultLanguage();
  1238. }
  1239. /**
  1240. * Returns the requested URL path of the page being viewed.
  1241. *
  1242. * Examples:
  1243. * - http://example.com/node/306 returns "node/306".
  1244. * - http://example.com/drupalfolder/node/306 returns "node/306" while
  1245. * base_path() returns "/drupalfolder/".
  1246. * - http://example.com/path/alias (which is a path alias for node/306) returns
  1247. * "path/alias" as opposed to the internal path.
  1248. * - http://example.com/index.php returns an empty string (meaning: front page).
  1249. * - http://example.com/index.php?page=1 returns an empty string.
  1250. *
  1251. * @return
  1252. * The requested Drupal URL path.
  1253. *
  1254. * @see current_path()
  1255. */
  1256. function request_path() {
  1257. static $path;
  1258. if (isset($path)) {
  1259. return $path;
  1260. }
  1261. // Get the part of the URI between the base path of the Drupal installation
  1262. // and the query string, and unescape it.
  1263. $request_path = request_uri(TRUE);
  1264. $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
  1265. $path = substr(urldecode($request_path), $base_path_len + 1);
  1266. // Depending on server configuration, the URI might or might not include the
  1267. // script name. For example, the front page might be accessed as
  1268. // http://example.com or as http://example.com/index.php, and the "user"
  1269. // page might be accessed as http://example.com/user or as
  1270. // http://example.com/index.php/user. Strip the script name from $path.
  1271. $script = basename($_SERVER['SCRIPT_NAME']);
  1272. if ($path == $script) {
  1273. $path = '';
  1274. }
  1275. elseif (strpos($path, $script . '/') === 0) {
  1276. $path = substr($path, strlen($script) + 1);
  1277. }
  1278. // Extra slashes can appear in URLs or under some conditions, added by Apache,
  1279. // so normalize.
  1280. $path = trim($path, '/');
  1281. return $path;
  1282. }
  1283. /**
  1284. * @todo This is a temporary function pending refactoring Drupal to use
  1285. * Symfony's Request object exclusively.
  1286. */
  1287. function _current_path($path = NULL) {
  1288. static $current_path = '';
  1289. if (isset($path)) {
  1290. $current_path = $path;
  1291. }
  1292. return $current_path;
  1293. }
  1294. /**
  1295. * Initializes and returns the class loader.
  1296. *
  1297. * The class loader is responsible for lazy-loading all PSR-0 compatible
  1298. * classes, interfaces, and traits (PHP 5.4 and later). It's only dependency
  1299. * is DRUPAL_ROOT. Otherwise it may be called as early as possible.
  1300. *
  1301. * @param $class_loader
  1302. * The name of class loader to use. This can be used to change the class
  1303. * loader class when calling drupal_classloader() from settings.php. It is
  1304. * ignored otherwise.
  1305. *
  1306. * @return \Composer\Autoload\ClassLoader
  1307. * A ClassLoader class instance (or extension thereof).
  1308. */
  1309. function drupal_classloader($class_loader = NULL) {
  1310. // By default, use the ClassLoader which is best for development, as it does
  1311. // not break when code is moved on the file system. However, as it is slow,
  1312. // allow to use the APC class loader in production.
  1313. static $loader;
  1314. if (!isset($loader)) {
  1315. // Retrieve the Composer ClassLoader for loading classes.
  1316. $loader = include __DIR__ . '/../vendor/autoload.php';
  1317. // Register the class loader.
  1318. // When configured to use APC, the ApcClassLoader is registered instead.
  1319. // Note that ApcClassLoader decorates ClassLoader and only provides the
  1320. // findFile() method, but none of the others. The actual registry is still
  1321. // in ClassLoader.
  1322. if (!isset($class_loader)) {
  1323. $class_loader = Settings::get('class_loader', 'default');
  1324. }
  1325. if ($class_loader === 'apc') {
  1326. require_once __DIR__ . '/../vendor/symfony/class-loader/Symfony/Component/ClassLoader/ApcClassLoader.php';
  1327. $apc_loader = new ApcClassLoader('drupal.' . Settings::getHashSalt(), $loader);
  1328. $loader->unregister();
  1329. $apc_loader->register();
  1330. }
  1331. }
  1332. return $loader;
  1333. }
  1334. /**
  1335. * Registers an additional namespace.
  1336. *
  1337. * @param string $name
  1338. * The namespace component to register; e.g., 'node'.
  1339. * @param string $path
  1340. * The relative path to the Drupal component in the filesystem.
  1341. */
  1342. function drupal_classloader_register($name, $path) {
  1343. $loader = drupal_classloader();
  1344. $loader->addPsr4('Drupal\\' . $name . '\\', DRUPAL_ROOT . '/' . $path . '/src');
  1345. }
  1346. /**
  1347. * Provides central static variable storage.
  1348. *
  1349. * All functions requiring a static variable to persist or cache data within
  1350. * a single page request are encouraged to use this function unless it is
  1351. * absolutely certain that the static variable will not need to be reset during
  1352. * the page request. By centralizing static variable storage through this
  1353. * function, other functions can rely on a consistent API for resetting any
  1354. * other function's static variables.
  1355. *
  1356. * Example:
  1357. * @code
  1358. * function example_list($field = 'default') {
  1359. * $examples = &drupal_static(__FUNCTION__);
  1360. * if (!isset($examples)) {
  1361. * // If this function is being called for the first time after a reset,
  1362. * // query the database and execute any other code needed to retrieve
  1363. * // information.
  1364. * ...
  1365. * }
  1366. * if (!isset($examples[$field])) {
  1367. * // If this function is being called for the first time for a particular
  1368. * // index field, then execute code needed to index the information already
  1369. * // available in $examples by the desired field.
  1370. * ...
  1371. * }
  1372. * // Subsequent invocations of this function for a particular index field
  1373. * // skip the above two code blocks and quickly return the already indexed
  1374. * // information.
  1375. * return $examples[$field];
  1376. * }
  1377. * function examples_admin_overview() {
  1378. * // When building the content for the overview page, make sure to get
  1379. * // completely fresh information.
  1380. * drupal_static_reset('example_list');
  1381. * ...
  1382. * }
  1383. * @endcode
  1384. *
  1385. * In a few cases, a function can have certainty that there is no legitimate
  1386. * use-case for resetting that function's static variable. This is rare,
  1387. * because when writing a function, it's hard to forecast all the situations in
  1388. * which it will be used. A guideline is that if a function's static variable
  1389. * does not depend on any information outside of the function that might change
  1390. * during a single page request, then it's ok to use the "static" keyword
  1391. * instead of the drupal_static() function.
  1392. *
  1393. * Example:
  1394. * @code
  1395. * function mymodule_log_stream_handle($new_handle = NULL) {
  1396. * static $handle;
  1397. * if (isset($new_handle)) {
  1398. * $handle = $new_handle;
  1399. * }
  1400. * return $handle;
  1401. * }
  1402. * @endcode
  1403. *
  1404. * In a few cases, a function needs a resettable static variable, but the
  1405. * function is called many times (100+) during a single page request, so
  1406. * every microsecond of execution time that can be removed from the function
  1407. * counts. These functions can use a more cumbersome, but faster variant of
  1408. * calling drupal_static(). It works by storing the reference returned by
  1409. * drupal_static() in the calling function's own static variable, thereby
  1410. * removing the need to call drupal_static() for each iteration of the function.
  1411. * Conceptually, it replaces:
  1412. * @code
  1413. * $foo = &drupal_static(__FUNCTION__);
  1414. * @endcode
  1415. * with:
  1416. * @code
  1417. * // Unfortunately, this does not work.
  1418. * static $foo = &drupal_static(__FUNCTION__);
  1419. * @endcode
  1420. * However, the above line of code does not work, because PHP only allows static
  1421. * variables to be initializied by literal values, and does not allow static
  1422. * variables to be assigned to references.
  1423. * - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
  1424. * - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
  1425. * The example below shows the syntax needed to work around both limitations.
  1426. * For benchmarks and more information, see http://drupal.org/node/619666.
  1427. *
  1428. * Example:
  1429. * @code
  1430. * function example_default_format_type() {
  1431. * // Use the advanced drupal_static() pattern, since this is called very often.
  1432. * static $drupal_static_fast;
  1433. * if (!isset($drupal_static_fast)) {
  1434. * $drupal_static_fast['format_type'] = &drupal_static(__FUNCTION__);
  1435. * }
  1436. * $format_type = &$drupal_static_fast['format_type'];
  1437. * ...
  1438. * }
  1439. * @endcode
  1440. *
  1441. * @param $name
  1442. * Globally unique name for the variable. For a function with only one static,
  1443. * variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
  1444. * is recommended. For a function with multiple static variables add a
  1445. * distinguishing suffix to the function name for each one.
  1446. * @param $default_value
  1447. * Optional default value.
  1448. * @param $reset
  1449. * TRUE to reset a specific named variable, or all variables if $name is NULL.
  1450. * Resetting every variable should only be used, for example, for running
  1451. * unit tests with a clean environment. Should be used only though via
  1452. * function drupal_static_reset() and the return value should not be used in
  1453. * this case.
  1454. *
  1455. * @return
  1456. * Returns a variable by reference.
  1457. *
  1458. * @see drupal_static_reset()
  1459. */
  1460. function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  1461. static $data = array(), $default = array();
  1462. // First check if dealing with a previously defined static variable.
  1463. if (isset($data[$name]) || array_key_exists($name, $data)) {
  1464. // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
  1465. if ($reset) {
  1466. // Reset pre-existing static variable to its default value.
  1467. $data[$name] = $default[$name];
  1468. }
  1469. return $data[$name];
  1470. }
  1471. // Neither $data[$name] nor $default[$name] static variables exist.
  1472. if (isset($name)) {
  1473. if ($reset) {
  1474. // Reset was called before a default is set and yet a variable must be
  1475. // returned.
  1476. return $data;
  1477. }
  1478. // First call with new non-NULL $name. Initialize a new static variable.
  1479. $default[$name] = $data[$name] = $default_value;
  1480. return $data[$name];
  1481. }
  1482. // Reset all: ($name == NULL). This needs to be done one at a time so that
  1483. // references returned by earlier invocations of drupal_static() also get
  1484. // reset.
  1485. foreach ($default as $name => $value) {
  1486. $data[$name] = $value;
  1487. }
  1488. // As the function returns a reference, the return should always be a
  1489. // variable.
  1490. return $data;
  1491. }
  1492. /**
  1493. * Resets one or all centrally stored static variable(s).
  1494. *
  1495. * @param $name
  1496. * Name of the static variable to reset. Omit to reset all variables.
  1497. */
  1498. function drupal_static_reset($name = NULL) {
  1499. drupal_static($name, NULL, TRUE);
  1500. }
  1501. /**
  1502. * Formats text for emphasized display in a placeholder inside a sentence.
  1503. *
  1504. * @see \Drupal\Component\Utility\String::placeholder()
  1505. */
  1506. function drupal_placeholder($text) {
  1507. return String::placeholder($text);
  1508. }
  1509. /**
  1510. * Registers a function for execution on shutdown.
  1511. *
  1512. * Wrapper for register_shutdown_function() that catches thrown exceptions to
  1513. * avoid "Exception thrown without a stack frame in Unknown".
  1514. *
  1515. * @param $callback
  1516. * The shutdown function to register.
  1517. * @param ...
  1518. * Additional arguments to pass to the shutdown function.
  1519. *
  1520. * @return
  1521. * Array of shutdown functions to be executed.
  1522. *
  1523. * @see register_shutdown_function()
  1524. * @ingroup php_wrappers
  1525. */
  1526. function &drupal_register_shutdown_function($callback = NULL) {
  1527. // We cannot use drupal_static() here because the static cache is reset during
  1528. // batch processing, which breaks batch handling.
  1529. static $callbacks = array();
  1530. if (isset($callback)) {
  1531. // Only register the internal shutdown function once.
  1532. if (empty($callbacks)) {
  1533. register_shutdown_function('_drupal_shutdown_function');
  1534. }
  1535. $args = func_get_args();
  1536. // Remove $callback from the arguments.
  1537. unset($args[0]);
  1538. // Save callback and arguments
  1539. $callbacks[] = array('callback' => $callback, 'arguments' => $args);
  1540. }
  1541. return $callbacks;
  1542. }
  1543. /**
  1544. * Executes registered shutdown functions.
  1545. */
  1546. function _drupal_shutdown_function() {
  1547. $callbacks = &drupal_register_shutdown_function();
  1548. // Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
  1549. // was in the normal context of execution.
  1550. chdir(DRUPAL_ROOT);
  1551. try {
  1552. while (list($key, $callback) = each($callbacks)) {
  1553. call_user_func_array($callback['callback'], $callback['arguments']);
  1554. }
  1555. }
  1556. catch (Exception $exception) {
  1557. // If using PHP-FPM then fastcgi_finish_request() will have been fired
  1558. // preventing further output to the browser.
  1559. if (!function_exists('fastcgi_finish_request')) {
  1560. // If we are displaying errors, then do so with no possibility of a
  1561. // further uncaught exception being thrown.
  1562. require_once __DIR__ . '/errors.inc';
  1563. if (error_displayable()) {
  1564. print '<h1>Uncaught exception thrown in shutdown function.</h1>';
  1565. print '<p>' . Error::renderExceptionSafe($exception) . '</p><hr />';
  1566. }
  1567. }
  1568. error_log($exception);
  1569. }
  1570. }