bootstrap.inc

Functions that need to be loaded on every Drupal request.

File

drupal/core/includes/bootstrap.inc
View source
  1. <?php
  2. use Drupal\Component\Utility\Crypt;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\Component\Utility\Settings;
  5. use Drupal\Component\Utility\String;
  6. use Drupal\Component\Utility\Timer;
  7. use Drupal\Component\Utility\Unicode;
  8. use Drupal\Component\Utility\UrlValidator;
  9. use Drupal\Core\DrupalKernel;
  10. use Drupal\Core\Database\Database;
  11. use Drupal\Core\DependencyInjection\ContainerBuilder;
  12. use Symfony\Component\ClassLoader\ClassLoader;
  13. use Symfony\Component\ClassLoader\ApcClassLoader;
  14. use Symfony\Component\DependencyInjection\ContainerInterface;
  15. use Symfony\Component\DependencyInjection\Container;
  16. use Symfony\Component\DependencyInjection\Reference;
  17. use Symfony\Component\DependencyInjection\Exception\RuntimeException as DependencyInjectionRuntimeException;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Drupal\Core\Language\Language;
  21. use Drupal\Core\Lock\DatabaseLockBackend;
  22. use Drupal\Core\Lock\LockBackendInterface;
  23. use Drupal\Core\Session\UserSession;
  24. /**
  25. * @file
  26. * Functions that need to be loaded on every Drupal request.
  27. */
  28. /**
  29. * The current system version.
  30. */
  31. const VERSION = '8.0-dev';
  32. /**
  33. * Core API compatibility.
  34. */
  35. const DRUPAL_CORE_COMPATIBILITY = '8.x';
  36. /**
  37. * Minimum supported version of PHP.
  38. */
  39. const DRUPAL_MINIMUM_PHP = '5.3.10';
  40. /**
  41. * Minimum recommended value of PHP memory_limit.
  42. */
  43. const DRUPAL_MINIMUM_PHP_MEMORY_LIMIT = '32M';
  44. /**
  45. * Error reporting level: display no errors.
  46. */
  47. const ERROR_REPORTING_HIDE = 'hide';
  48. /**
  49. * Error reporting level: display errors and warnings.
  50. */
  51. const ERROR_REPORTING_DISPLAY_SOME = 'some';
  52. /**
  53. * Error reporting level: display all messages.
  54. */
  55. const ERROR_REPORTING_DISPLAY_ALL = 'all';
  56. /**
  57. * Error reporting level: display all messages, plus backtrace information.
  58. */
  59. const ERROR_REPORTING_DISPLAY_VERBOSE = 'verbose';
  60. /**
  61. * @defgroup logging_severity_levels Logging severity levels
  62. * @{
  63. * Logging severity levels as defined in RFC 3164.
  64. *
  65. * The WATCHDOG_* constant definitions correspond to the logging severity levels
  66. * defined in RFC 3164, section 4.1.1. PHP supplies predefined LOG_* constants
  67. * for use in the syslog() function, but their values on Windows builds do not
  68. * correspond to RFC 3164. The associated PHP bug report was closed with the
  69. * comment, "And it's also not a bug, as Windows just have less log levels,"
  70. * and "So the behavior you're seeing is perfectly normal."
  71. *
  72. * @see http://www.faqs.org/rfcs/rfc3164.html
  73. * @see http://bugs.php.net/bug.php?id=18090
  74. * @see http://php.net/manual/function.syslog.php
  75. * @see http://php.net/manual/network.constants.php
  76. * @see watchdog()
  77. * @see watchdog_severity_levels()
  78. */
  79. /**
  80. * Log message severity -- Emergency: system is unusable.
  81. */
  82. const WATCHDOG_EMERGENCY = 0;
  83. /**
  84. * Log message severity -- Alert: action must be taken immediately.
  85. */
  86. const WATCHDOG_ALERT = 1;
  87. /**
  88. * Log message severity -- Critical conditions.
  89. */
  90. const WATCHDOG_CRITICAL = 2;
  91. /**
  92. * Log message severity -- Error conditions.
  93. */
  94. const WATCHDOG_ERROR = 3;
  95. /**
  96. * Log message severity -- Warning conditions.
  97. */
  98. const WATCHDOG_WARNING = 4;
  99. /**
  100. * Log message severity -- Normal but significant conditions.
  101. */
  102. const WATCHDOG_NOTICE = 5;
  103. /**
  104. * Log message severity -- Informational messages.
  105. */
  106. const WATCHDOG_INFO = 6;
  107. /**
  108. * Log message severity -- Debug-level messages.
  109. */
  110. const WATCHDOG_DEBUG = 7;
  111. /**
  112. * @} End of "defgroup logging_severity_levels".
  113. */
  114. /**
  115. * First bootstrap phase: initialize configuration.
  116. */
  117. const DRUPAL_BOOTSTRAP_CONFIGURATION = 0;
  118. /**
  119. * Second bootstrap phase, initalize a kernel.
  120. */
  121. const DRUPAL_BOOTSTRAP_KERNEL = 1;
  122. /**
  123. * Third bootstrap phase: try to serve a cached page.
  124. */
  125. const DRUPAL_BOOTSTRAP_PAGE_CACHE = 2;
  126. /**
  127. * Fourth bootstrap phase: initialize database layer.
  128. */
  129. const DRUPAL_BOOTSTRAP_DATABASE = 3;
  130. /**
  131. * Fifth bootstrap phase: initialize the variable system.
  132. */
  133. const DRUPAL_BOOTSTRAP_VARIABLES = 4;
  134. /**
  135. * Sixth bootstrap phase: initialize session handling.
  136. */
  137. const DRUPAL_BOOTSTRAP_SESSION = 5;
  138. /**
  139. * Eighth bootstrap phase: load code for subsystems and modules.
  140. */
  141. const DRUPAL_BOOTSTRAP_CODE = 6;
  142. /**
  143. * Final bootstrap phase: initialize language, path, theme, and modules.
  144. */
  145. const DRUPAL_BOOTSTRAP_FULL = 7;
  146. /**
  147. * Role ID for anonymous users; should match what's in the "role" table.
  148. */
  149. const DRUPAL_ANONYMOUS_RID = 'anonymous';
  150. /**
  151. * Role ID for authenticated users; should match what's in the "role" table.
  152. */
  153. const DRUPAL_AUTHENTICATED_RID = 'authenticated';
  154. /**
  155. * The number of bytes in a kilobyte.
  156. *
  157. * For more information, visit http://en.wikipedia.org/wiki/Kilobyte.
  158. */
  159. const DRUPAL_KILOBYTE = 1024;
  160. /**
  161. * Time of the current request in seconds elapsed since the Unix Epoch.
  162. *
  163. * This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
  164. * since PHP 5.4.0. Float timestamps confuse most PHP functions
  165. * (including date_create()).
  166. *
  167. * @see http://php.net/manual/reserved.variables.server.php
  168. * @see http://php.net/manual/function.time.php
  169. */
  170. define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);
  171. /**
  172. * Flag for drupal_set_title(); text is not sanitized, so run check_plain().
  173. */
  174. const CHECK_PLAIN = 0;
  175. /**
  176. * Flag for drupal_set_title(); text has already been sanitized.
  177. */
  178. const PASS_THROUGH = -1;
  179. /**
  180. * Regular expression to match PHP function names.
  181. *
  182. * @see http://php.net/manual/language.functions.php
  183. */
  184. const DRUPAL_PHP_FUNCTION_PATTERN = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
  185. /**
  186. * $config_directories key for active directory.
  187. *
  188. * @see config_get_config_directory()
  189. */
  190. const CONFIG_ACTIVE_DIRECTORY = 'active';
  191. /**
  192. * $config_directories key for staging directory.
  193. *
  194. * @see config_get_config_directory()
  195. */
  196. const CONFIG_STAGING_DIRECTORY = 'staging';
  197. /**
  198. * Defines the root directory of the Drupal installation.
  199. *
  200. * This strips two levels of directories off the current directory.
  201. */
  202. define('DRUPAL_ROOT', dirname(dirname(__DIR__)));
  203. /**
  204. * @deprecated as of Drupal 8.0.
  205. * @see \Drupal\Component\Utility\Timer::start
  206. */
  207. function timer_start($name) {
  208. Timer::start($name);
  209. }
  210. /**
  211. * @deprecated as of Drupal 8.0.
  212. * @see \Drupal\Component\Utility\Timer::read
  213. */
  214. function timer_read($name) {
  215. return Timer::read($name);
  216. }
  217. /**
  218. * @deprecated as of Drupal 8.0.
  219. * @see \Drupal\Component\Utility\Timer::stop
  220. */
  221. function timer_stop($name) {
  222. return Timer::stop($name);
  223. }
  224. /**
  225. * Returns the appropriate configuration directory.
  226. *
  227. * Returns the configuration path based on the site's hostname, port, and
  228. * pathname. Uses find_conf_path() to find the current configuration directory.
  229. * See default.settings.php for examples on how the URL is converted to a
  230. * directory.
  231. *
  232. * @param bool $require_settings
  233. * Only configuration directories with an existing settings.php file
  234. * will be recognized. Defaults to TRUE. During initial installation,
  235. * this is set to FALSE so that Drupal can detect a matching directory,
  236. * then create a new settings.php file in it.
  237. * @param bool $reset
  238. * Force a full search for matching directories even if one had been
  239. * found previously. Defaults to FALSE.
  240. *
  241. * @return
  242. * The path of the matching directory.
  243. *
  244. * @see default.settings.php
  245. */
  246. function conf_path($require_settings = TRUE, $reset = FALSE) {
  247. $conf_path = &drupal_static(__FUNCTION__, '');
  248. if ($conf_path && !$reset) {
  249. return $conf_path;
  250. }
  251. // Check for a simpletest override.
  252. if ($simpletest_conf_path = _drupal_simpletest_conf_path()) {
  253. $conf_path = $simpletest_conf_path;
  254. return $conf_path;
  255. }
  256. // Otherwise, use the normal $conf_path.
  257. $script_name = $_SERVER['SCRIPT_NAME'];
  258. if (!$script_name) {
  259. $script_name = $_SERVER['SCRIPT_FILENAME'];
  260. }
  261. $http_host = $_SERVER['HTTP_HOST'];
  262. $conf_path = find_conf_path($http_host, $script_name, $require_settings);
  263. return $conf_path;
  264. }
  265. /**
  266. * Determines whether to use an overridden value for conf_path().
  267. *
  268. * Simpletest may provide a secondary, test-specific settings.php file to load
  269. * after the primary one used by the parent site and override its variables.
  270. * - If the child settings.php does not override $conf_path, then this function
  271. * returns FALSE and conf_path() returns the directory of the primary
  272. * settings.php.
  273. * - If the child settings.php does override $conf_path, then
  274. * _drupal_load_test_overrides() sets the 'simpletest_conf_path' setting, and
  275. * this function returns that to conf_path(), causing installations and
  276. * upgrades to act on that one.
  277. *
  278. * @return string|false
  279. * The overridden $conf_path, or FALSE if the $conf_path should not currently
  280. * be overridden.
  281. *
  282. * @see conf_path()
  283. * @see _drupal_load_test_overrides()
  284. */
  285. function _drupal_simpletest_conf_path() {
  286. // Ensure that the settings object is available. conf_path() is called once
  287. // before the Settings class is included, and at that point it should still
  288. // load the primary $conf_path. See drupal_settings_initialize().
  289. if (!class_exists('Drupal\Component\Utility\Settings', FALSE)) {
  290. return FALSE;
  291. }
  292. // If no $simpletest_conf_path is set, use the normal $conf_path.
  293. if (!($simpletest_conf_path = settings()->get('simpletest_conf_path'))) {
  294. return FALSE;
  295. }
  296. // Ensure that this is actually a simpletest request. We can't check this
  297. // before settings.php is loaded.
  298. if (!drupal_valid_test_ua()) {
  299. return FALSE;
  300. }
  301. // When the $simpletest_conf_path is set in a valid test request,
  302. // return that path.
  303. return $simpletest_conf_path;
  304. }
  305. /**
  306. * Finds the appropriate configuration directory for a given host and path.
  307. *
  308. * Finds a matching configuration directory file by stripping the website's
  309. * hostname from left to right and pathname from right to left. By default,
  310. * the directory must contain a 'settings.php' file for it to match. If the
  311. * parameter $require_settings is set to FALSE, then a directory without a
  312. * 'settings.php' file will match as well. The first configuration
  313. * file found will be used and the remaining ones will be ignored. If no
  314. * configuration file is found, returns a default value '$confdir/default'. See
  315. * default.settings.php for examples on how the URL is converted to a directory.
  316. *
  317. * If a file named sites.php is present in the $confdir, it will be loaded
  318. * prior to scanning for directories. That file can define aliases in an
  319. * associative array named $sites. The array is written in the format
  320. * '<port>.<domain>.<path>' => 'directory'. As an example, to create a
  321. * directory alias for http://www.drupal.org:8080/mysite/test whose configuration
  322. * file is in sites/example.com, the array should be defined as:
  323. * @code
  324. * $sites = array(
  325. * '8080.www.drupal.org.mysite.test' => 'example.com',
  326. * );
  327. * @endcode
  328. *
  329. * @param $http_host
  330. * The hostname and optional port number, e.g. "www.example.com" or
  331. * "www.example.com:8080".
  332. * @param $script_name
  333. * The part of the URL following the hostname, including the leading slash.
  334. * @param $require_settings
  335. * Defaults to TRUE. If TRUE, then only match directories with a
  336. * 'settings.php' file. Otherwise match any directory.
  337. *
  338. * @return
  339. * The path of the matching configuration directory.
  340. *
  341. * @see default.settings.php
  342. * @see example.sites.php
  343. * @see conf_path()
  344. */
  345. function find_conf_path($http_host, $script_name, $require_settings = TRUE) {
  346. // Determine whether multi-site functionality is enabled.
  347. if (!file_exists(DRUPAL_ROOT . '/sites/sites.php')) {
  348. return 'sites/default';
  349. }
  350. $sites = array();
  351. include DRUPAL_ROOT . '/sites/sites.php';
  352. $uri = explode('/', $script_name);
  353. $server = explode('.', implode('.', array_reverse(explode(':', rtrim($http_host, '.')))));
  354. for ($i = count($uri) - 1; $i > 0; $i--) {
  355. for ($j = count($server); $j > 0; $j--) {
  356. $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
  357. if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/sites/' . $sites[$dir])) {
  358. $dir = $sites[$dir];
  359. }
  360. if (file_exists(DRUPAL_ROOT . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/sites/' . $dir))) {
  361. return "sites/$dir";
  362. }
  363. }
  364. }
  365. return 'sites/default';
  366. }
  367. /**
  368. * Returns the path of a configuration directory.
  369. *
  370. * @param string $type
  371. * (optional) The type of config directory to return. Drupal core provides
  372. * 'active' and 'staging'. Defaults to CONFIG_ACTIVE_DIRECTORY.
  373. *
  374. * @return string
  375. * The configuration directory path.
  376. */
  377. function config_get_config_directory($type = CONFIG_ACTIVE_DIRECTORY) {
  378. global $config_directories;
  379. if (!empty($config_directories[$type])) {
  380. // Allow a configuration directory path to be outside of webroot.
  381. if (empty($config_directories[$type]['absolute'])) {
  382. $path = conf_path() . '/files/' . $config_directories[$type]['path'];
  383. }
  384. else {
  385. $path = $config_directories[$type]['path'];
  386. }
  387. }
  388. else {
  389. throw new Exception(format_string('The configuration directory type %type does not exist.', array('%type' => $type)));
  390. }
  391. return $path;
  392. }
  393. /**
  394. * Sets appropriate server variables needed for command line scripts to work.
  395. *
  396. * This function can be called by command line scripts before bootstrapping
  397. * Drupal, to ensure that the page loads with the desired server parameters.
  398. * This is because many parts of Drupal assume that they are running in a web
  399. * browser and therefore use information from the global PHP $_SERVER variable
  400. * that does not get set when Drupal is run from the command line.
  401. *
  402. * In many cases, the default way in which this function populates the $_SERVER
  403. * variable is sufficient, and it can therefore be called without passing in
  404. * any input. However, command line scripts running on a multisite installation
  405. * (or on any installation that has settings.php stored somewhere other than
  406. * the sites/default folder) need to pass in the URL of the site to allow
  407. * Drupal to detect the correct location of the settings.php file. Passing in
  408. * the 'url' parameter is also required for functions like request_uri() to
  409. * return the expected values.
  410. *
  411. * Most other parameters do not need to be passed in, but may be necessary in
  412. * some cases; for example, if Drupal::request()->getClientIP()
  413. * needs to return anything but the standard localhost value ('127.0.0.1'),
  414. * the command line script should pass in the desired value via the
  415. * 'REMOTE_ADDR' key.
  416. *
  417. * @param $variables
  418. * (optional) An associative array of variables within $_SERVER that should
  419. * be replaced. If the special element 'url' is provided in this array, it
  420. * will be used to populate some of the server defaults; it should be set to
  421. * the URL of the current page request, excluding any $_GET request but
  422. * including the script name (e.g., http://www.example.com/mysite/index.php).
  423. *
  424. * @see conf_path()
  425. * @see request_uri()
  426. * @see \Symfony\Component\HttpFoundation\Request::getClientIP()
  427. */
  428. function drupal_override_server_variables($variables = array()) {
  429. // Allow the provided URL to override any existing values in $_SERVER.
  430. if (isset($variables['url'])) {
  431. $url = parse_url($variables['url']);
  432. if (isset($url['host'])) {
  433. $_SERVER['HTTP_HOST'] = $url['host'];
  434. }
  435. if (isset($url['path'])) {
  436. $_SERVER['SCRIPT_NAME'] = $url['path'];
  437. }
  438. unset($variables['url']);
  439. }
  440. // Define default values for $_SERVER keys. These will be used if $_SERVER
  441. // does not already define them and no other values are passed in to this
  442. // function.
  443. $defaults = array(
  444. 'HTTP_HOST' => 'localhost',
  445. 'SCRIPT_NAME' => NULL,
  446. 'REMOTE_ADDR' => '127.0.0.1',
  447. 'REQUEST_METHOD' => 'GET',
  448. 'SERVER_NAME' => NULL,
  449. 'SERVER_SOFTWARE' => NULL,
  450. 'HTTP_USER_AGENT' => NULL,
  451. );
  452. // Replace elements of the $_SERVER array, as appropriate.
  453. $_SERVER = $variables + $_SERVER + $defaults;
  454. }
  455. /**
  456. * Initializes the PHP environment.
  457. */
  458. function drupal_environment_initialize() {
  459. // Make sure the \Drupal class is available.
  460. require_once DRUPAL_ROOT . '/core/lib/Drupal.php';
  461. if (!isset($_SERVER['HTTP_REFERER'])) {
  462. $_SERVER['HTTP_REFERER'] = '';
  463. }
  464. if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
  465. $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
  466. }
  467. if (isset($_SERVER['HTTP_HOST'])) {
  468. // As HTTP_HOST is user input, ensure it only contains characters allowed
  469. // in hostnames. See RFC 952 (and RFC 2181).
  470. // $_SERVER['HTTP_HOST'] is lowercased here per specifications.
  471. $_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
  472. if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
  473. // HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
  474. header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
  475. exit;
  476. }
  477. }
  478. else {
  479. // Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
  480. // defined for E_ALL compliance.
  481. $_SERVER['HTTP_HOST'] = '';
  482. }
  483. // @todo Refactor with the Symfony Request object.
  484. _current_path(request_path());
  485. // Enforce E_STRICT, but allow users to set levels not part of E_STRICT.
  486. error_reporting(E_STRICT | E_ALL | error_reporting());
  487. // Override PHP settings required for Drupal to work properly.
  488. // sites/default/default.settings.php contains more runtime settings.
  489. // The .htaccess file contains settings that cannot be changed at runtime.
  490. // Deny execution with enabled "magic quotes" (both GPC and runtime).
  491. if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) {
  492. header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
  493. print "PHP's 'magic_quotes_gpc' and 'magic_quotes_runtime' settings are not supported and must be disabled.";
  494. exit;
  495. }
  496. // Use session cookies, not transparent sessions that puts the session id in
  497. // the query string.
  498. ini_set('session.use_cookies', '1');
  499. ini_set('session.use_only_cookies', '1');
  500. ini_set('session.use_trans_sid', '0');
  501. // Don't send HTTP headers using PHP's session handler.
  502. // Send an empty string to disable the cache limiter.
  503. ini_set('session.cache_limiter', '');
  504. // Use httponly session cookies.
  505. ini_set('session.cookie_httponly', '1');
  506. // Set sane locale settings, to ensure consistent string, dates, times and
  507. // numbers handling.
  508. setlocale(LC_ALL, 'C');
  509. }
  510. /**
  511. * Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
  512. *
  513. * @return
  514. * TRUE if only containing valid characters, or FALSE otherwise.
  515. */
  516. function drupal_valid_http_host($host) {
  517. return preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host);
  518. }
  519. /**
  520. * Sets the base URL, cookie domain, and session name from configuration.
  521. */
  522. function drupal_settings_initialize() {
  523. global $base_url, $base_path, $base_root, $script_path;
  524. // Export these settings.php variables to the global namespace.
  525. global $databases, $cookie_domain, $conf, $db_prefix, $drupal_hash_salt, $base_secure_url, $base_insecure_url, $config_directories;
  526. $conf = array();
  527. // Make conf_path() available as local variable in settings.php.
  528. $conf_path = conf_path();
  529. if (is_readable(DRUPAL_ROOT . '/' . $conf_path . '/settings.php')) {
  530. include_once DRUPAL_ROOT . '/' . $conf_path . '/settings.php';
  531. }
  532. require_once DRUPAL_ROOT . '/core/lib/Drupal/Component/Utility/Settings.php';
  533. new Settings(isset($settings) ? $settings : array());
  534. $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
  535. if (isset($base_url)) {
  536. // Parse fixed base URL from settings.php.
  537. $parts = parse_url($base_url);
  538. if (!isset($parts['path'])) {
  539. $parts['path'] = '';
  540. }
  541. $base_path = $parts['path'] . '/';
  542. // Build $base_root (everything until first slash after "scheme://").
  543. $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
  544. }
  545. else {
  546. // Create base URL
  547. $http_protocol = $is_https ? 'https' : 'http';
  548. $base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];
  549. $base_url = $base_root;
  550. // For a request URI of '/index.php/foo', $_SERVER['SCRIPT_NAME'] is
  551. // '/index.php', whereas $_SERVER['PHP_SELF'] is '/index.php/foo'.
  552. if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
  553. // Remove "core" directory if present, allowing install.php, update.php,
  554. // and others to auto-detect a base path.
  555. $core_position = strrpos($dir, '/core');
  556. if ($core_position !== FALSE && strlen($dir) - 5 == $core_position) {
  557. $base_path = substr($dir, 0, $core_position);
  558. }
  559. else {
  560. $base_path = $dir;
  561. }
  562. $base_url .= $base_path;
  563. $base_path .= '/';
  564. }
  565. else {
  566. $base_path = '/';
  567. }
  568. }
  569. $base_secure_url = str_replace('http://', 'https://', $base_url);
  570. $base_insecure_url = str_replace('https://', 'http://', $base_url);
  571. // Determine the path of the script relative to the base path, and add a
  572. // trailing slash. This is needed for creating URLs to Drupal pages.
  573. if (!isset($script_path)) {
  574. $script_path = '';
  575. // We don't expect scripts outside of the base path, but sanity check
  576. // anyway.
  577. if (strpos($_SERVER['SCRIPT_NAME'], $base_path) === 0) {
  578. $script_path = substr($_SERVER['SCRIPT_NAME'], strlen($base_path)) . '/';
  579. // If the request URI does not contain the script name, then clean URLs
  580. // are in effect and the script path can be similarly dropped from URL
  581. // generation. For servers that don't provide $_SERVER['REQUEST_URI'], we
  582. // do not know the actual URI requested by the client, and request_uri()
  583. // returns a URI with the script name, resulting in non-clean URLs unless
  584. // there's other code that intervenes.
  585. if (strpos(request_uri(TRUE) . '/', $base_path . $script_path) !== 0) {
  586. $script_path = '';
  587. }
  588. // @todo Temporary BC for install.php, update.php, and other scripts.
  589. // - http://drupal.org/node/1547184
  590. // - http://drupal.org/node/1546082
  591. if ($script_path !== 'index.php/') {
  592. $script_path = '';
  593. }
  594. }
  595. }
  596. if ($cookie_domain) {
  597. // If the user specifies the cookie domain, also use it for session name.
  598. $session_name = $cookie_domain;
  599. }
  600. else {
  601. // Otherwise use $base_url as session name, without the protocol
  602. // to use the same session identifiers across HTTP and HTTPS.
  603. list( , $session_name) = explode('://', $base_url, 2);
  604. // HTTP_HOST can be modified by a visitor, but we already sanitized it
  605. // in drupal_settings_initialize().
  606. if (!empty($_SERVER['HTTP_HOST'])) {
  607. $cookie_domain = $_SERVER['HTTP_HOST'];
  608. // Strip leading periods, www., and port numbers from cookie domain.
  609. $cookie_domain = ltrim($cookie_domain, '.');
  610. if (strpos($cookie_domain, 'www.') === 0) {
  611. $cookie_domain = substr($cookie_domain, 4);
  612. }
  613. $cookie_domain = explode(':', $cookie_domain);
  614. $cookie_domain = '.' . $cookie_domain[0];
  615. }
  616. }
  617. // Per RFC 2109, cookie domains must contain at least one dot other than the
  618. // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
  619. if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
  620. ini_set('session.cookie_domain', $cookie_domain);
  621. }
  622. // To prevent session cookies from being hijacked, a user can configure the
  623. // SSL version of their website to only transfer session cookies via SSL by
  624. // using PHP's session.cookie_secure setting. The browser will then use two
  625. // separate session cookies for the HTTPS and HTTP versions of the site. So we
  626. // must use different session identifiers for HTTPS and HTTP to prevent a
  627. // cookie collision.
  628. if ($is_https) {
  629. ini_set('session.cookie_secure', TRUE);
  630. }
  631. $prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS';
  632. session_name($prefix . substr(hash('sha256', $session_name), 0, 32));
  633. }
  634. /**
  635. * Returns and optionally sets the filename for a system resource.
  636. *
  637. * The filename, whether provided, cached, or retrieved from the database, is
  638. * only returned if the file exists.
  639. *
  640. * This function plays a key role in allowing Drupal's resources (modules
  641. * and themes) to be located in different places depending on a site's
  642. * configuration. For example, a module 'foo' may legally be be located
  643. * in any of these three places:
  644. *
  645. * core/modules/foo/foo.module
  646. * modules/foo/foo.module
  647. * sites/example.com/modules/foo/foo.module
  648. *
  649. * Calling drupal_get_filename('module', 'foo') will give you one of
  650. * the above, depending on where the module is located.
  651. *
  652. * @param $type
  653. * The type of the item (i.e. theme, theme_engine, module, profile).
  654. * @param $name
  655. * The name of the item for which the filename is requested.
  656. * @param $filename
  657. * The filename of the item if it is to be set explicitly rather
  658. * than by consulting the database.
  659. *
  660. * @return
  661. * The filename of the requested item or NULL if the item is not found.
  662. */
  663. function drupal_get_filename($type, $name, $filename = NULL) {
  664. // The location of files will not change during the request, so do not use
  665. // drupal_static().
  666. static $files = array(), $dirs = array();
  667. // Profiles are converted into modules in system_rebuild_module_data().
  668. // @todo Remove false-exposure of profiles as modules.
  669. $original_type = $type;
  670. if ($type == 'profile') {
  671. $type = 'module';
  672. }
  673. if (!isset($files[$type])) {
  674. $files[$type] = array();
  675. }
  676. if (!empty($filename) && file_exists($filename)) {
  677. $files[$type][$name] = $filename;
  678. }
  679. elseif (isset($files[$type][$name])) {
  680. // nothing
  681. }
  682. else {
  683. // Verify that we have an keyvalue service before using it. This is required
  684. // because this function is called during installation.
  685. // @todo Inject database connection into KeyValueStore\DatabaseStorage.
  686. if (($container = drupal_container()) && $container->has('keyvalue') && function_exists('db_query')) {
  687. if ($type == 'module') {
  688. if (empty($files[$type])) {
  689. $files[$type] = Drupal::moduleHandler()->getModuleList();
  690. }
  691. if (isset($files[$type][$name])) {
  692. return $files[$type][$name];
  693. }
  694. }
  695. try {
  696. $file_list = Drupal::state()->get('system.' . $type . '.files');
  697. if ($file_list && isset($file_list[$name]) && file_exists(DRUPAL_ROOT . '/' . $file_list[$name])) {
  698. $files[$type][$name] = $file_list[$name];
  699. }
  700. }
  701. catch (Exception $e) {
  702. // The keyvalue service raised an exception because the backend might
  703. // be down. We have a fallback for this case so we hide the error
  704. // completely.
  705. }
  706. }
  707. // Fallback to searching the filesystem if the database could not find the
  708. // file or the file returned by the database is not found.
  709. if (!isset($files[$type][$name])) {
  710. // We have consistent directory naming: modules, themes...
  711. $dir = $type . 's';
  712. if ($type == 'theme_engine') {
  713. $dir = 'themes/engines';
  714. $extension = 'engine';
  715. }
  716. elseif ($type == 'theme') {
  717. $extension = 'info.yml';
  718. }
  719. // Profiles are converted into modules in system_rebuild_module_data().
  720. // @todo Remove false-exposure of profiles as modules.
  721. elseif ($original_type == 'profile') {
  722. $dir = 'profiles';
  723. $extension = 'profile';
  724. }
  725. else {
  726. $extension = $type;
  727. }
  728. if (!isset($dirs[$dir][$extension])) {
  729. $dirs[$dir][$extension] = TRUE;
  730. if (!function_exists('drupal_system_listing')) {
  731. require_once __DIR__ . '/common.inc';
  732. }
  733. // Scan the appropriate directories for all files with the requested
  734. // extension, not just the file we are currently looking for. This
  735. // prevents unnecessary scans from being repeated when this function is
  736. // called more than once in the same page request.
  737. $matches = drupal_system_listing("/^" . DRUPAL_PHP_FUNCTION_PATTERN . "\.$extension$/", $dir);
  738. foreach ($matches as $matched_name => $file) {
  739. $files[$type][$matched_name] = $file->uri;
  740. }
  741. }
  742. }
  743. }
  744. if (isset($files[$type][$name])) {
  745. return $files[$type][$name];
  746. }
  747. }
  748. /**
  749. * Returns a setting.
  750. *
  751. * Settings can be set in settings.php in the $settings array and requested
  752. * by this function. Settings should be used over configuration for read-only,
  753. * possibly low bootstrap configuration that is environment specific.
  754. *
  755. * @return \Drupal\Component\Utility\Settings
  756. * The settings object.
  757. */
  758. function settings() {
  759. return Settings::getSingleton();
  760. }
  761. /**
  762. * Loads the persistent variable table.
  763. *
  764. * The variable table is composed of values that have been saved in the table
  765. * with variable_set() as well as those explicitly specified in the
  766. * configuration file.
  767. */
  768. function variable_initialize($conf = array()) {
  769. // NOTE: caching the variables improves performance by 20% when serving
  770. // cached pages.
  771. if ($cached = cache('bootstrap')->get('variables')) {
  772. $variables = $cached->data;
  773. }
  774. else {
  775. // Cache miss. Avoid a stampede.
  776. $name = 'variable_init';
  777. $lock = Drupal::lock();
  778. if (!$lock->acquire($name, 1)) {
  779. // Another request is building the variable cache.
  780. // Wait, then re-run this function.
  781. $lock->wait($name);
  782. return variable_initialize($conf);
  783. }
  784. else {
  785. // Proceed with variable rebuild.
  786. $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
  787. cache('bootstrap')->set('variables', $variables);
  788. $lock->release($name);
  789. }
  790. }
  791. foreach ($conf as $name => $value) {
  792. $variables[$name] = $value;
  793. }
  794. return $variables;
  795. }
  796. /**
  797. * Returns a persistent variable.
  798. *
  799. * Case-sensitivity of the variable_* functions depends on the database
  800. * collation used. To avoid problems, always use lower case for persistent
  801. * variable names.
  802. *
  803. * @param $name
  804. * The name of the variable to return.
  805. * @param $default
  806. * The default value to use if this variable has never been set.
  807. *
  808. * @return
  809. * The value of the variable. Unserialization is taken care of as necessary.
  810. *
  811. * @see variable_del()
  812. * @see variable_set()
  813. */
  814. function variable_get($name, $default = NULL) {
  815. global $conf;
  816. return isset($conf[$name]) ? $conf[$name] : $default;
  817. }
  818. /**
  819. * Sets a persistent variable.
  820. *
  821. * Case-sensitivity of the variable_* functions depends on the database
  822. * collation used. To avoid problems, always use lower case for persistent
  823. * variable names.
  824. *
  825. * @param $name
  826. * The name of the variable to set.
  827. * @param $value
  828. * The value to set. This can be any PHP data type; these functions take care
  829. * of serialization as necessary.
  830. *
  831. * @see variable_del()
  832. * @see variable_get()
  833. */
  834. function variable_set($name, $value) {
  835. global $conf;
  836. db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();
  837. cache('bootstrap')->delete('variables');
  838. $conf[$name] = $value;
  839. }
  840. /**
  841. * Unsets a persistent variable.
  842. *
  843. * Case-sensitivity of the variable_* functions depends on the database
  844. * collation used. To avoid problems, always use lower case for persistent
  845. * variable names.
  846. *
  847. * @param $name
  848. * The name of the variable to undefine.
  849. *
  850. * @see variable_get()
  851. * @see variable_set()
  852. */
  853. function variable_del($name) {
  854. global $conf;
  855. db_delete('variable')
  856. ->condition('name', $name)
  857. ->execute();
  858. cache('bootstrap')->delete('variables');
  859. unset($conf[$name]);
  860. }
  861. /**
  862. * Retrieves the current page from the cache.
  863. *
  864. * Note: we do not serve cached pages to authenticated users, or to anonymous
  865. * users when $_SESSION is non-empty. $_SESSION may contain status messages
  866. * from a form submission, the contents of a shopping cart, or other user-
  867. * specific content that should not be cached and displayed to other users.
  868. *
  869. * @param $check_only
  870. * (optional) Set to TRUE to only return whether a previous call found a
  871. * cache entry.
  872. *
  873. * @return
  874. * The cache object, if the page was found in the cache, NULL otherwise.
  875. */
  876. function drupal_page_get_cache($check_only = FALSE) {
  877. global $base_root;
  878. static $cache_hit = FALSE;
  879. if ($check_only) {
  880. return $cache_hit;
  881. }
  882. if (drupal_page_is_cacheable()) {
  883. $cache = cache('page')->get($base_root . request_uri());
  884. if ($cache !== FALSE) {
  885. $cache_hit = TRUE;
  886. }
  887. return $cache;
  888. }
  889. }
  890. /**
  891. * Determines the cacheability of the current page.
  892. *
  893. * @param $allow_caching
  894. * Set to FALSE if you want to prevent this page to get cached.
  895. *
  896. * @return
  897. * TRUE if the current page can be cached, FALSE otherwise.
  898. */
  899. function drupal_page_is_cacheable($allow_caching = NULL) {
  900. $allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
  901. if (isset($allow_caching)) {
  902. $allow_caching_static = $allow_caching;
  903. }
  904. return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
  905. && !drupal_is_cli();
  906. }
  907. /**
  908. * Invokes a bootstrap hook in all bootstrap modules that implement it.
  909. *
  910. * @param $hook
  911. * The name of the bootstrap hook to invoke.
  912. *
  913. * @see bootstrap_hooks()
  914. */
  915. function bootstrap_invoke_all($hook) {
  916. $module_handler = Drupal::moduleHandler();
  917. foreach ($module_handler->getBootstrapModules() as $module) {
  918. $module_handler->load($module);
  919. module_invoke($module, $hook);
  920. }
  921. }
  922. /**
  923. * Includes a file with the provided type and name.
  924. *
  925. * This prevents including a theme, engine, module, etc., more than once.
  926. *
  927. * @param $type
  928. * The type of item to load (i.e. theme, theme_engine, module).
  929. * @param $name
  930. * The name of the item to load.
  931. *
  932. * @return
  933. * TRUE if the item is loaded or has already been loaded.
  934. */
  935. function drupal_load($type, $name) {
  936. if ($type == 'module' && Drupal::moduleHandler()->moduleExists($name)) {
  937. return Drupal::moduleHandler()->load($name);
  938. }
  939. // Once a file is included this can't be reversed during a request so do not
  940. // use drupal_static() here.
  941. static $files = array();
  942. if (isset($files[$type][$name])) {
  943. return TRUE;
  944. }
  945. $filename = drupal_get_filename($type, $name);
  946. if ($filename) {
  947. include_once DRUPAL_ROOT . '/' . $filename;
  948. $files[$type][$name] = TRUE;
  949. return TRUE;
  950. }
  951. return FALSE;
  952. }
  953. /**
  954. * Sets an HTTP response header for the current page.
  955. *
  956. * Note: When sending a Content-Type header, always include a 'charset' type,
  957. * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
  958. *
  959. * @param $name
  960. * The HTTP header name, or the special 'Status' header name.
  961. * @param $value
  962. * The HTTP header value; if equal to FALSE, the specified header is unset.
  963. * If $name is 'Status', this is expected to be a status code followed by a
  964. * reason phrase, e.g. "404 Not Found".
  965. * @param $append
  966. * Whether to append the value to an existing header or to replace it.
  967. *
  968. * @deprecated Header handling is being shifted to a Symfony response object.
  969. */
  970. function drupal_add_http_header($name, $value, $append = FALSE) {
  971. // The headers as name/value pairs.
  972. $headers = &drupal_static('drupal_http_headers', array());
  973. $name_lower = strtolower($name);
  974. _drupal_set_preferred_header_name($name);
  975. if ($value === FALSE) {
  976. $headers[$name_lower] = FALSE;
  977. }
  978. elseif (isset($headers[$name_lower]) && $append) {
  979. // Multiple headers with identical names may be combined using comma (RFC
  980. // 2616, section 4.2).
  981. $headers[$name_lower] .= ',' . $value;
  982. }
  983. else {
  984. $headers[$name_lower] = $value;
  985. }
  986. }
  987. /**
  988. * Gets the HTTP response headers for the current page.
  989. *
  990. * @param $name
  991. * An HTTP header name. If omitted, all headers are returned as name/value
  992. * pairs. If an array value is FALSE, the header has been unset.
  993. *
  994. * @return
  995. * A string containing the header value, or FALSE if the header has been set,
  996. * or NULL if the header has not been set.
  997. *
  998. * @deprecated Header handling is being shifted to a Symfony response object.
  999. */
  1000. function drupal_get_http_header($name = NULL) {
  1001. $headers = &drupal_static('drupal_http_headers', array());
  1002. if (isset($name)) {
  1003. $name = strtolower($name);
  1004. return isset($headers[$name]) ? $headers[$name] : NULL;
  1005. }
  1006. else {
  1007. return $headers;
  1008. }
  1009. }
  1010. /**
  1011. * Sets the preferred name for the HTTP header.
  1012. *
  1013. * Header names are case-insensitive, but for maximum compatibility they should
  1014. * follow "common form" (see RFC 2616, section 4.2).
  1015. *
  1016. * @deprecated Header handling is being shifted to a Symfony response object.
  1017. */
  1018. function _drupal_set_preferred_header_name($name = NULL) {
  1019. static $header_names = array();
  1020. if (!isset($name)) {
  1021. return $header_names;
  1022. }
  1023. $header_names[strtolower($name)] = $name;
  1024. }
  1025. /**
  1026. * Sends the HTTP response headers that were previously set, adding defaults.
  1027. *
  1028. * Headers are set in drupal_add_http_header(). Default headers are not set
  1029. * if they have been replaced or unset using drupal_add_http_header().
  1030. *
  1031. * @param array $default_headers
  1032. * (optional) An array of headers as name/value pairs.
  1033. * @param bool $only_default
  1034. * (optional) If TRUE and headers have already been sent, send only the
  1035. * specified headers.
  1036. *
  1037. * @deprecated Header handling is being shifted to a Symfony response object.
  1038. */
  1039. function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
  1040. $headers_sent = &drupal_static(__FUNCTION__, FALSE);
  1041. $headers = drupal_get_http_header();
  1042. if ($only_default && $headers_sent) {
  1043. $headers = array();
  1044. }
  1045. $headers_sent = TRUE;
  1046. $header_names = _drupal_set_preferred_header_name();
  1047. foreach ($default_headers as $name => $value) {
  1048. $name_lower = strtolower($name);
  1049. if (!isset($headers[$name_lower])) {
  1050. $headers[$name_lower] = $value;
  1051. $header_names[$name_lower] = $name;
  1052. }
  1053. }
  1054. foreach ($headers as $name_lower => $value) {
  1055. if ($name_lower == 'status') {
  1056. header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
  1057. }
  1058. // Skip headers that have been unset.
  1059. elseif ($value !== FALSE) {
  1060. header($header_names[$name_lower] . ': ' . $value);
  1061. }
  1062. }
  1063. }
  1064. /**
  1065. * Sets HTTP headers in preparation for a page response.
  1066. *
  1067. * Authenticated users are always given a 'no-cache' header, and will fetch a
  1068. * fresh page on every request. This prevents authenticated users from seeing
  1069. * locally cached pages.
  1070. *
  1071. * Also give each page a unique ETag. This will force clients to include both
  1072. * an If-Modified-Since header and an If-None-Match header when doing
  1073. * conditional requests for the page (required by RFC 2616, section 13.3.4),
  1074. * making the validation more robust. This is a workaround for a bug in Mozilla
  1075. * Firefox that is triggered when Drupal's caching is enabled and the user
  1076. * accesses Drupal via an HTTP proxy (see
  1077. * https://bugzilla.mozilla.org/show_bug.cgi?id=269303): When an authenticated
  1078. * user requests a page, and then logs out and requests the same page again,
  1079. * Firefox may send a conditional request based on the page that was cached
  1080. * locally when the user was logged in. If this page did not have an ETag
  1081. * header, the request only contains an If-Modified-Since header. The date will
  1082. * be recent, because with authenticated users the Last-Modified header always
  1083. * refers to the time of the request. If the user accesses Drupal via a proxy
  1084. * server, and the proxy already has a cached copy of the anonymous page with an
  1085. * older Last-Modified date, the proxy may respond with 304 Not Modified, making
  1086. * the client think that the anonymous and authenticated pageviews are
  1087. * identical.
  1088. *
  1089. * @see drupal_page_set_cache()
  1090. *
  1091. * @deprecated Header handling is being shifted to a Symfony response object.
  1092. */
  1093. function drupal_page_header() {
  1094. $headers_sent = &drupal_static(__FUNCTION__, FALSE);
  1095. if ($headers_sent) {
  1096. return TRUE;
  1097. }
  1098. $headers_sent = TRUE;
  1099. $default_headers = array(
  1100. 'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
  1101. 'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),
  1102. 'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0',
  1103. 'ETag' => '"' . REQUEST_TIME . '"',
  1104. );
  1105. drupal_send_headers($default_headers);
  1106. }
  1107. /**
  1108. * Sets HTTP headers in preparation for a cached page response.
  1109. *
  1110. * The headers allow as much as possible in proxies and browsers without any
  1111. * particular knowledge about the pages. Modules can override these headers
  1112. * using drupal_add_http_header().
  1113. *
  1114. * If the request is conditional (using If-Modified-Since and If-None-Match),
  1115. * and the conditions match those currently in the cache, a 304 Not Modified
  1116. * response is sent.
  1117. */
  1118. function drupal_serve_page_from_cache(stdClass $cache, Response $response, Request $request) {
  1119. $config = config('system.performance');
  1120. // First half: we must determine if we should be returning a 304.
  1121. // Negotiate whether to use compression.
  1122. $page_compression = $config->get('response.gzip') && extension_loaded('zlib');
  1123. $return_compressed = $page_compression && $request->server->has('HTTP_ACCEPT_ENCODING') && strpos($request->server->get('HTTP_ACCEPT_ENCODING'), 'gzip') !== FALSE;
  1124. // Get headers. Keys are lower-case.
  1125. $boot_headers = drupal_get_http_header();
  1126. foreach ($cache->data['headers'] as $name => $value) {
  1127. // In the case of a 304 response, certain headers must be sent, and the
  1128. // remaining may not (see RFC 2616, section 10.3.5).
  1129. $name_lower = strtolower($name);
  1130. if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($boot_headers[$name_lower])) {
  1131. $response->headers->set($name, $value);
  1132. unset($cache->data['headers'][$name]);
  1133. }
  1134. }
  1135. // If the client sent a session cookie, a cached copy will only be served
  1136. // to that one particular client due to Vary: Cookie. Thus, do not set
  1137. // max-age > 0, allowing the page to be cached by external proxies, when a
  1138. // session cookie is present unless the Vary header has been replaced.
  1139. $max_age = !$request->cookies->has(session_name()) || isset($boot_headers['vary']) ? $config->get('cache.page.max_age') : 0;
  1140. $response->headers->set('Cache-Control', 'public, max-age=' . $max_age);
  1141. // Entity tag should change if the output changes.
  1142. $response->setEtag($cache->created);
  1143. // See if the client has provided the required HTTP headers.
  1144. $if_modified_since = $request->server->has('HTTP_IF_MODIFIED_SINCE') ? strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE')) : FALSE;
  1145. $if_none_match = $request->server->has('HTTP_IF_NONE_MATCH') ? stripslashes($request->server->get('HTTP_IF_NONE_MATCH')) : FALSE;
  1146. if ($if_modified_since && $if_none_match
  1147. && $if_none_match == $response->headers->get('etag') // etag must match
  1148. && $if_modified_since == $cache->created) { // if-modified-since must match
  1149. $response->setStatusCode(304);
  1150. return;
  1151. }
  1152. // Second half: we're not returning a 304, so put in other headers.
  1153. // Send the remaining headers.
  1154. foreach ($cache->data['headers'] as $name => $value) {
  1155. $response->headers->set($name, $value);
  1156. drupal_add_http_header($name, $value);
  1157. }
  1158. $response->setLastModified(\DateTime::createFromFormat('U', $cache->created));
  1159. // HTTP/1.0 proxies does not support the Vary header, so prevent any caching
  1160. // by sending an Expires date in the past. HTTP/1.1 clients ignores the
  1161. // Expires header if a Cache-Control: max-age= directive is specified (see RFC
  1162. // 2616, section 14.9.3).
  1163. if (!$response->getExpires()) {
  1164. $response->setExpires(\DateTime::createFromFormat('j-M-Y H:i:s T', '19-Nov-1978 05:00:00 GMT'));
  1165. }
  1166. // Allow HTTP proxies to cache pages for anonymous users without a session
  1167. // cookie. The Vary header is used to indicates the set of request-header
  1168. // fields that fully determines whether a cache is permitted to use the
  1169. // response to reply to a subsequent request for a given URL without
  1170. // revalidation.
  1171. if (!isset($boot_headers['vary']) && !settings()->get('omit_vary_cookie')) {
  1172. $response->setVary('Cookie', FALSE);
  1173. }
  1174. if ($page_compression) {
  1175. $response->setVary('accept-encoding', FALSE);
  1176. // If page_compression is enabled, the cache contains gzipped data.
  1177. if ($return_compressed) {
  1178. // $cache->data['body'] is already gzip'ed, so make sure
  1179. // zlib.output_compression does not compress it once more.
  1180. ini_set('zlib.output_compression', '0');
  1181. $response->headers->set('content-encoding', 'gzip');
  1182. }
  1183. else {
  1184. // The client does not support compression, so unzip the data in the
  1185. // cache. Strip the gzip header and run uncompress.
  1186. $cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
  1187. }
  1188. }
  1189. $response->setContent($cache->data['body']);
  1190. }
  1191. /**
  1192. * Defines the critical hooks that force modules to always be loaded.
  1193. */
  1194. function bootstrap_hooks() {
  1195. return array('watchdog');
  1196. }
  1197. /**
  1198. * Translates a string to the current language or to a given language.
  1199. *
  1200. * The t() function serves two purposes. First, at run-time it translates
  1201. * user-visible text into the appropriate language. Second, various mechanisms
  1202. * that figure out what text needs to be translated work off t() -- the text
  1203. * inside t() calls is added to the database of strings to be translated.
  1204. * These strings are expected to be in English, so the first argument should
  1205. * always be in English. To enable a fully-translatable site, it is important
  1206. * that all human-readable text that will be displayed on the site or sent to
  1207. * a user is passed through the t() function, or a related function. See the
  1208. * @link http://drupal.org/node/322729 Localization API @endlink pages for
  1209. * more information, including recommendations on how to break up or not
  1210. * break up strings for translation.
  1211. *
  1212. * @section sec_translating_vars Translating Variables
  1213. * You should never use t() to translate variables, such as calling
  1214. * @code t($text); @endcode, unless the text that the variable holds has been
  1215. * passed through t() elsewhere (e.g., $text is one of several translated
  1216. * literal strings in an array). It is especially important never to call
  1217. * @code t($user_text); @endcode, where $user_text is some text that a user
  1218. * entered - doing that can lead to cross-site scripting and other security
  1219. * problems. However, you can use variable substitution in your string, to put
  1220. * variable text such as user names or link URLs into translated text. Variable
  1221. * substitution looks like this:
  1222. * @code
  1223. * $text = t("@name's blog", array('@name' => user_format_name($account)));
  1224. * @endcode
  1225. * Basically, you can put variables like @name into your string, and t() will
  1226. * substitute their sanitized values at translation time. (See the
  1227. * Localization API pages referenced above and the documentation of
  1228. * format_string() for details about how to define variables in your string.)
  1229. * Translators can then rearrange the string as necessary for the language
  1230. * (e.g., in Spanish, it might be "blog de @name").
  1231. *
  1232. * @section sec_alt_funcs_install Use During Installation Phase
  1233. * During the Drupal installation phase, some resources used by t() wil not be
  1234. * available to code that needs localization. See st() and get_t() for
  1235. * alternatives.
  1236. *
  1237. * @param $string
  1238. * A string containing the English string to translate.
  1239. * @param $args
  1240. * An associative array of replacements to make after translation. Based
  1241. * on the first character of the key, the value is escaped and/or themed.
  1242. * See format_string() for details.
  1243. * @param $options
  1244. * An associative array of additional options, with the following elements:
  1245. * - 'langcode' (defaults to the current language): The language code to
  1246. * translate to a language other than what is used to display the page.
  1247. * - 'context' (defaults to the empty context): The context the source string
  1248. * belongs to.
  1249. *
  1250. * @return
  1251. * The translated string.
  1252. *
  1253. * @see st()
  1254. * @see get_t()
  1255. * @see format_string()
  1256. * @ingroup sanitization
  1257. */
  1258. function t($string, array $args = array(), array $options = array()) {
  1259. return Drupal::translation()->translate($string, $args, $options);
  1260. }
  1261. /**
  1262. * Formats a string for HTML display by replacing variable placeholders.
  1263. *
  1264. * @see \Drupal\Component\Utility\String::format()
  1265. * @see t()
  1266. * @ingroup sanitization
  1267. */
  1268. function format_string($string, array $args = array()) {
  1269. return String::format($string, $args);
  1270. }
  1271. /**
  1272. * Encodes special characters in a plain-text string for display as HTML.
  1273. *
  1274. * @see \Drupal\Component\Utility\String::checkPlain()
  1275. * @see drupal_validate_utf8()
  1276. * @ingroup sanitization
  1277. */
  1278. function check_plain($text) {
  1279. return String::checkPlain($text);
  1280. }
  1281. /**
  1282. * Checks whether a string is valid UTF-8.
  1283. *
  1284. * All functions designed to filter input should use drupal_validate_utf8
  1285. * to ensure they operate on valid UTF-8 strings to prevent bypass of the
  1286. * filter.
  1287. *
  1288. * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
  1289. * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
  1290. * bytes. When these subsequent bytes are HTML control characters such as
  1291. * quotes or angle brackets, parts of the text that were deemed safe by filters
  1292. * end up in locations that are potentially unsafe; An onerror attribute that
  1293. * is outside of a tag, and thus deemed safe by a filter, can be interpreted
  1294. * by the browser as if it were inside the tag.
  1295. *
  1296. * The function does not return FALSE for strings containing character codes
  1297. * above U+10FFFF, even though these are prohibited by RFC 3629.
  1298. *
  1299. * @param $text
  1300. * The text to check.
  1301. *
  1302. * @return
  1303. * TRUE if the text is valid UTF-8, FALSE if not.
  1304. *
  1305. * @see \Drupal\Component\Utility\Unicode::validateUtf8()
  1306. */
  1307. function drupal_validate_utf8($text) {
  1308. return Unicode::validateUtf8($text);
  1309. }
  1310. /**
  1311. * Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
  1312. *
  1313. * Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
  1314. * equivalent using other environment variables.
  1315. *
  1316. * @todo The above comment is incorrect: http://drupal.org/node/1547294.
  1317. */
  1318. function request_uri($omit_query_string = FALSE) {
  1319. if (isset($_SERVER['REQUEST_URI'])) {
  1320. $uri = $_SERVER['REQUEST_URI'];
  1321. }
  1322. else {
  1323. if (isset($_SERVER['argv'][0])) {
  1324. $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
  1325. }
  1326. elseif (isset($_SERVER['QUERY_STRING'])) {
  1327. $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
  1328. }
  1329. else {
  1330. $uri = $_SERVER['SCRIPT_NAME'];
  1331. }
  1332. }
  1333. // Prevent multiple slashes to avoid cross site requests via the Form API.
  1334. $uri = '/' . ltrim($uri, '/');
  1335. return $omit_query_string ? strtok($uri, '?') : $uri;
  1336. }
  1337. /**
  1338. * Logs an exception.
  1339. *
  1340. * This is a wrapper function for watchdog() which automatically decodes an
  1341. * exception.
  1342. *
  1343. * @param $type
  1344. * The category to which this message belongs.
  1345. * @param $exception
  1346. * The exception that is going to be logged.
  1347. * @param $message
  1348. * The message to store in the log. If empty, a text that contains all useful
  1349. * information about the passed-in exception is used.
  1350. * @param $variables
  1351. * Array of variables to replace in the message on display or
  1352. * NULL if message is already translated or not possible to
  1353. * translate.
  1354. * @param $severity
  1355. * The severity of the message, as per RFC 3164.
  1356. * @param $link
  1357. * A link to associate with the message.
  1358. *
  1359. * @see watchdog()
  1360. * @see _drupal_decode_exception()
  1361. */
  1362. function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {
  1363. // Use a default value if $message is not set.
  1364. if (empty($message)) {
  1365. // The exception message is run through check_plain() by _drupal_decode_exception().
  1366. $message = '%type: !message in %function (line %line of %file).';
  1367. }
  1368. // $variables must be an array so that we can add the exception information.
  1369. if (!is_array($variables)) {
  1370. $variables = array();
  1371. }
  1372. require_once __DIR__ . '/errors.inc';
  1373. $variables += _drupal_decode_exception($exception);
  1374. watchdog($type, $message, $variables, $severity, $link);
  1375. }
  1376. /**
  1377. * Logs a system message.
  1378. *
  1379. * @param $type
  1380. * The category to which this message belongs. Can be any string, but the
  1381. * general practice is to use the name of the module calling watchdog().
  1382. * @param $message
  1383. * The message to store in the log. Keep $message translatable
  1384. * by not concatenating dynamic values into it! Variables in the
  1385. * message should be added by using placeholder strings alongside
  1386. * the variables argument to declare the value of the placeholders.
  1387. * See t() for documentation on how $message and $variables interact.
  1388. * @param $variables
  1389. * Array of variables to replace in the message on display or array() if
  1390. * message is already translated or not possible to translate.
  1391. * @param $severity
  1392. * The severity of the message; one of the following values as defined in
  1393. * @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
  1394. * - WATCHDOG_EMERGENCY: Emergency, system is unusable.
  1395. * - WATCHDOG_ALERT: Alert, action must be taken immediately.
  1396. * - WATCHDOG_CRITICAL: Critical conditions.
  1397. * - WATCHDOG_ERROR: Error conditions.
  1398. * - WATCHDOG_WARNING: Warning conditions.
  1399. * - WATCHDOG_NOTICE: (default) Normal but significant conditions.
  1400. * - WATCHDOG_INFO: Informational messages.
  1401. * - WATCHDOG_DEBUG: Debug-level messages.
  1402. * @param $link
  1403. * A link to associate with the message.
  1404. *
  1405. * @see watchdog_severity_levels()
  1406. * @see hook_watchdog()
  1407. */
  1408. function watchdog($type, $message, array $variables = NULL, $severity = WATCHDOG_NOTICE, $link = NULL) {
  1409. global $user, $base_root;
  1410. static $in_error_state = FALSE;
  1411. // It is possible that the error handling will itself trigger an error. In that case, we could
  1412. // end up in an infinite loop. To avoid that, we implement a simple static semaphore.
  1413. if (!$in_error_state && function_exists('module_implements')) {
  1414. $in_error_state = TRUE;
  1415. // The user object may not exist in all conditions, so 0 is substituted if needed.
  1416. $user_uid = isset($user->uid) ? $user->uid : 0;
  1417. // Prepare the fields to be logged
  1418. $log_entry = array(
  1419. 'type' => $type,
  1420. 'message' => $message,
  1421. 'variables' => $variables,
  1422. 'severity' => $severity,
  1423. 'link' => $link,
  1424. 'user' => $user,
  1425. 'uid' => $user_uid,
  1426. 'request_uri' => $base_root . request_uri(),
  1427. 'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
  1428. 'ip' => Drupal::request()->getClientIP(),
  1429. // Request time isn't accurate for long processes, use time() instead.
  1430. 'timestamp' => time(),
  1431. );
  1432. // Call the logging hooks to log/process the message
  1433. foreach (module_implements('watchdog') as $module) {
  1434. $function = $module . '_watchdog';
  1435. $function($log_entry);
  1436. }
  1437. // It is critical that the semaphore is only cleared here, in the parent
  1438. // watchdog() call (not outside the loop), to prevent recursive execution.
  1439. $in_error_state = FALSE;
  1440. }
  1441. }
  1442. /**
  1443. * Sets a message to display to the user.
  1444. *
  1445. * Messages are stored in a session variable and displayed in the page template
  1446. * via the $messages theme variable.
  1447. *
  1448. * Example usage:
  1449. * @code
  1450. * drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
  1451. * @endcode
  1452. *
  1453. * @param string $message
  1454. * (optional) The translated message to be displayed to the user. For
  1455. * consistency with other messages, it should begin with a capital letter and
  1456. * end with a period.
  1457. * @param string $type
  1458. * (optional) The message's type. Defaults to 'status'. These values are
  1459. * supported:
  1460. * - 'status'
  1461. * - 'warning'
  1462. * - 'error'
  1463. * @param bool $repeat
  1464. * (optional) If this is FALSE and the message is already set, then the
  1465. * message won't be repeated. Defaults to FALSE.
  1466. *
  1467. * @return array|null
  1468. * A multidimensional array with keys corresponding to the set message types.
  1469. * The indexed array values of each contain the set messages for that type.
  1470. * Or, if there are no messages set, the function returns NULL.
  1471. *
  1472. * @see drupal_get_messages()
  1473. * @see theme_status_messages()
  1474. */
  1475. function drupal_set_message($message = NULL, $type = 'status', $repeat = FALSE) {
  1476. if ($message) {
  1477. if (!isset($_SESSION['messages'][$type])) {
  1478. $_SESSION['messages'][$type] = array();
  1479. }
  1480. if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
  1481. $_SESSION['messages'][$type][] = $message;
  1482. }
  1483. // Mark this page as being uncacheable.
  1484. drupal_page_is_cacheable(FALSE);
  1485. }
  1486. // Messages not set when DB connection fails.
  1487. return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
  1488. }
  1489. /**
  1490. * Returns all messages that have been set with drupal_set_message().
  1491. *
  1492. * @param string $type
  1493. * (optional) Limit the messages returned by type. Defaults to NULL, meaning
  1494. * all types. These values are supported:
  1495. * - NULL
  1496. * - 'status'
  1497. * - 'warning'
  1498. * - 'error'
  1499. * @param bool $clear_queue
  1500. * (optional) If this is TRUE, the queue will be cleared of messages of the
  1501. * type specified in the $type parameter. Otherwise the queue will be left
  1502. * intact. Defaults to TRUE.
  1503. *
  1504. * @return array
  1505. * A multidimensional array with keys corresponding to the set message types.
  1506. * The indexed array values of each contain the set messages for that type.
  1507. * The messages returned are limited to the type specified in the $type
  1508. * parameter. If there are no messages of the specified type, an empty array
  1509. * is returned.
  1510. *
  1511. * @see drupal_set_message()
  1512. * @see theme_status_messages()
  1513. */
  1514. function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
  1515. if ($messages = drupal_set_message()) {
  1516. if ($type) {
  1517. if ($clear_queue) {
  1518. unset($_SESSION['messages'][$type]);
  1519. }
  1520. if (isset($messages[$type])) {
  1521. return array($type => $messages[$type]);
  1522. }
  1523. }
  1524. else {
  1525. if ($clear_queue) {
  1526. unset($_SESSION['messages']);
  1527. }
  1528. return $messages;
  1529. }
  1530. }
  1531. return array();
  1532. }
  1533. /**
  1534. * Gets the title of the current page.
  1535. *
  1536. * The title is displayed on the page and in the title bar.
  1537. *
  1538. * @return
  1539. * The current page's title.
  1540. */
  1541. function drupal_get_title() {
  1542. $title = drupal_set_title();
  1543. // During a bootstrap, menu.inc is not included and thus we cannot provide a title.
  1544. if (!isset($title) && function_exists('menu_get_active_title')) {
  1545. $title = check_plain(menu_get_active_title());
  1546. }
  1547. return $title;
  1548. }
  1549. /**
  1550. * Sets the title of the current page.
  1551. *
  1552. * The title is displayed on the page and in the title bar.
  1553. *
  1554. * @param $title
  1555. * Optional string value to assign to the page title; or if set to NULL
  1556. * (default), leaves the current title unchanged.
  1557. * @param $output
  1558. * Optional flag - normally should be left as CHECK_PLAIN. Only set to
  1559. * PASS_THROUGH if you have already removed any possibly dangerous code
  1560. * from $title using a function like check_plain() or filter_xss(). With this
  1561. * flag the string will be passed through unchanged.
  1562. *
  1563. * @return
  1564. * The updated title of the current page.
  1565. */
  1566. function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
  1567. $stored_title = &drupal_static(__FUNCTION__);
  1568. if (isset($title)) {
  1569. $stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
  1570. }
  1571. return $stored_title;
  1572. }
  1573. /**
  1574. * Generates a default anonymous $user object.
  1575. *
  1576. * @return \Drupal\Core\Session\AccountInterface
  1577. * The user session object.
  1578. */
  1579. function drupal_anonymous_user() {
  1580. $values = array(
  1581. 'uid' => 0,
  1582. 'hostname' => Drupal::request()->getClientIP(),
  1583. 'roles' => array(DRUPAL_ANONYMOUS_RID),
  1584. );
  1585. return new UserSession($values);
  1586. }
  1587. /**
  1588. * Ensures Drupal is bootstrapped to the specified phase.
  1589. *
  1590. * In order to bootstrap Drupal from another PHP script, you can use this code:
  1591. * @code
  1592. * define('DRUPAL_ROOT', '/path/to/drupal');
  1593. * require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
  1594. * drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  1595. * @endcode
  1596. *
  1597. * @param $phase
  1598. * A constant telling which phase to bootstrap to. When you bootstrap to a
  1599. * particular phase, all earlier phases are run automatically. Possible
  1600. * values:
  1601. * - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
  1602. * - DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
  1603. * - DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
  1604. * - DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
  1605. * - DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
  1606. * - DRUPAL_BOOTSTRAP_CODE: Loads code for subsystems and modules.
  1607. * - DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input
  1608. * data.
  1609. * @param $new_phase
  1610. * A boolean, set to FALSE if calling drupal_bootstrap from inside a
  1611. * function called from drupal_bootstrap (recursion).
  1612. *
  1613. * @return
  1614. * The most recently completed phase.
  1615. */
  1616. function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
  1617. // Not drupal_static(), because does not depend on any run-time information.
  1618. static $phases = array(
  1619. DRUPAL_BOOTSTRAP_CONFIGURATION,
  1620. DRUPAL_BOOTSTRAP_KERNEL,
  1621. DRUPAL_BOOTSTRAP_PAGE_CACHE,
  1622. DRUPAL_BOOTSTRAP_DATABASE,
  1623. DRUPAL_BOOTSTRAP_VARIABLES,
  1624. DRUPAL_BOOTSTRAP_SESSION,
  1625. DRUPAL_BOOTSTRAP_CODE,
  1626. DRUPAL_BOOTSTRAP_FULL,
  1627. );
  1628. // Not drupal_static(), because the only legitimate API to control this is to
  1629. // call drupal_bootstrap() with a new phase parameter.
  1630. static $final_phase = -1;
  1631. // Not drupal_static(), because it's impossible to roll back to an earlier
  1632. // bootstrap state.
  1633. static $stored_phase = -1;
  1634. // When not recursing, store the phase name so it's not forgotten during
  1635. // recursion. Additionally, ensure that $final_phase is never rolled back to an
  1636. // earlier bootstrap state.
  1637. if ($new_phase && $phase > $final_phase) {
  1638. $final_phase = $phase;
  1639. }
  1640. if (isset($phase)) {
  1641. // Call a phase if it has not been called before and is below the requested
  1642. // phase.
  1643. while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
  1644. $current_phase = array_shift($phases);
  1645. // This function is re-entrant. Only update the completed phase when the
  1646. // current call actually resulted in a progress in the bootstrap process.
  1647. if ($current_phase > $stored_phase) {
  1648. $stored_phase = $current_phase;
  1649. }
  1650. switch ($current_phase) {
  1651. case DRUPAL_BOOTSTRAP_CONFIGURATION:
  1652. _drupal_bootstrap_configuration();
  1653. break;
  1654. case DRUPAL_BOOTSTRAP_KERNEL:
  1655. _drupal_bootstrap_kernel();
  1656. break;
  1657. case DRUPAL_BOOTSTRAP_PAGE_CACHE:
  1658. _drupal_bootstrap_page_cache();
  1659. break;
  1660. case DRUPAL_BOOTSTRAP_DATABASE:
  1661. _drupal_bootstrap_database();
  1662. break;
  1663. case DRUPAL_BOOTSTRAP_VARIABLES:
  1664. _drupal_bootstrap_variables();
  1665. break;
  1666. case DRUPAL_BOOTSTRAP_SESSION:
  1667. require_once DRUPAL_ROOT . '/' . settings()->get('session_inc', 'core/includes/session.inc');
  1668. drupal_session_initialize();
  1669. break;
  1670. case DRUPAL_BOOTSTRAP_CODE:
  1671. require_once __DIR__ . '/common.inc';
  1672. _drupal_bootstrap_code();
  1673. break;
  1674. case DRUPAL_BOOTSTRAP_FULL:
  1675. _drupal_bootstrap_full();
  1676. break;
  1677. }
  1678. }
  1679. }
  1680. return $stored_phase;
  1681. }
  1682. /**
  1683. * Handles an entire PHP request.
  1684. *
  1685. * This function may be called by PHP scripts (e.g., Drupal's index.php) that
  1686. * want Drupal to take over the entire PHP processing of the request. The only
  1687. * expectation is that PHP's superglobals are initialized as desired (PHP does
  1688. * this automatically, but some scripts might want to alter them) and that the
  1689. * DRUPAL_ROOT constant is defined and set to the absolute server directory of
  1690. * Drupal's codebase.
  1691. *
  1692. * Scripts and applications that want to invoke multiple Drupal requests within
  1693. * a single PHP request, or Drupal request handling within some larger workflow,
  1694. * should not call this function, but instead instantiate and use
  1695. * \Drupal\Core\DrupalKernel as needed.
  1696. *
  1697. * @param boolean $test_only
  1698. * Whether to restrict handling to only requests invoked by SimpleTest.
  1699. *
  1700. * @see index.php
  1701. */
  1702. function drupal_handle_request($test_only = FALSE) {
  1703. // Initialize the environment, load settings.php, and activate a PSR-0 class
  1704. // autoloader with required namespaces registered.
  1705. drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
  1706. // Exit if we should be in a test environment but aren't.
  1707. if ($test_only && !drupal_valid_test_ua()) {
  1708. header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
  1709. exit;
  1710. }
  1711. // @todo Figure out how best to handle the Kernel constructor parameters.
  1712. $kernel = new DrupalKernel('prod', FALSE, drupal_classloader(), !$test_only);
  1713. // @todo Remove this once everything in the bootstrap has been
  1714. // converted to services in the DIC.
  1715. $kernel->boot();
  1716. drupal_bootstrap(DRUPAL_BOOTSTRAP_CODE);
  1717. // Create a request object from the HttpFoundation.
  1718. $request = Request::createFromGlobals();
  1719. $response = $kernel->handle($request)->prepare($request)->send();
  1720. $kernel->terminate($request, $response);
  1721. }
  1722. /**
  1723. * Returns the time zone of the current user.
  1724. */
  1725. function drupal_get_user_timezone() {
  1726. global $user;
  1727. $config = config('system.timezone');
  1728. if ($config->get('user.configurable') && $user->uid && $user->timezone) {
  1729. return $user->timezone;
  1730. }
  1731. else {
  1732. // Ignore PHP strict notice if time zone has not yet been set in the php.ini
  1733. // configuration.
  1734. $config_data_default_timezone = $config->get('default');
  1735. return !empty($config_data_default_timezone) ? $config_data_default_timezone : @date_default_timezone_get();
  1736. }
  1737. }
  1738. /**
  1739. * Gets a salt useful for hardening against SQL injection.
  1740. *
  1741. * @return
  1742. * A salt based on information in settings.php, not in the database.
  1743. */
  1744. function drupal_get_hash_salt() {
  1745. global $drupal_hash_salt, $databases;
  1746. // If the $drupal_hash_salt variable is empty, a hash of the serialized
  1747. // database credentials is used as a fallback salt.
  1748. return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
  1749. }
  1750. /**
  1751. * Provides custom PHP error handling.
  1752. *
  1753. * @param $error_level
  1754. * The level of the error raised.
  1755. * @param $message
  1756. * The error message.
  1757. * @param $filename
  1758. * The filename that the error was raised in.
  1759. * @param $line
  1760. * The line number the error was raised at.
  1761. * @param $context
  1762. * An array that points to the active symbol table at the point the error
  1763. * occurred.
  1764. */
  1765. function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
  1766. require_once __DIR__ . '/errors.inc';
  1767. _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
  1768. }
  1769. /**
  1770. * Provides custom PHP exception handling.
  1771. *
  1772. * Uncaught exceptions are those not enclosed in a try/catch block. They are
  1773. * always fatal: the execution of the script will stop as soon as the exception
  1774. * handler exits.
  1775. *
  1776. * @param $exception
  1777. * The exception object that was thrown.
  1778. */
  1779. function _drupal_exception_handler($exception) {
  1780. require_once __DIR__ . '/errors.inc';
  1781. try {
  1782. // Log the message to the watchdog and return an error page to the user.
  1783. _drupal_log_error(_drupal_decode_exception($exception), TRUE);
  1784. }
  1785. catch (Exception $exception2) {
  1786. // Another uncaught exception was thrown while handling the first one.
  1787. // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
  1788. if (error_displayable()) {
  1789. print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
  1790. print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
  1791. print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
  1792. }
  1793. }
  1794. }
  1795. /**
  1796. * Sets up the script environment and loads settings.php.
  1797. */
  1798. function _drupal_bootstrap_configuration() {
  1799. drupal_environment_initialize();
  1800. // Initialize the configuration, including variables from settings.php.
  1801. drupal_settings_initialize();
  1802. // Make sure we are using the test database prefix in child Drupal sites.
  1803. _drupal_initialize_db_test_prefix();
  1804. // Activate the class loader.
  1805. drupal_classloader();
  1806. // Start a page timer:
  1807. Timer::start('page');
  1808. // Detect string handling method.
  1809. Unicode::check();
  1810. // Load the procedural configuration system helper functions.
  1811. require_once __DIR__ . '/config.inc';
  1812. // Set the Drupal custom error handler. (requires config())
  1813. set_error_handler('_drupal_error_handler');
  1814. set_exception_handler('_drupal_exception_handler');
  1815. // Redirect the user to the installation script if Drupal has not been
  1816. // installed yet (i.e., if no $databases array has been defined in the
  1817. // settings.php file) and we are not already installing.
  1818. if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
  1819. include_once __DIR__ . '/install.inc';
  1820. install_goto('core/install.php');
  1821. }
  1822. }
  1823. /**
  1824. * Initialize the kernel / service container.
  1825. */
  1826. function _drupal_bootstrap_kernel() {
  1827. // Normally, index.php puts a container in drupal_container() by creating a
  1828. // kernel. If there is no container yet, create one.
  1829. if (!drupal_container()) {
  1830. $kernel = new DrupalKernel('prod', FALSE, drupal_classloader());
  1831. $kernel->boot();
  1832. }
  1833. }
  1834. /**
  1835. * Attempts to serve a page from the cache.
  1836. */
  1837. function _drupal_bootstrap_page_cache() {
  1838. global $user;
  1839. // Allow specifying special cache handlers in settings.php, like
  1840. // using memcached or files for storing cache information.
  1841. require_once __DIR__ . '/cache.inc';
  1842. foreach (variable_get('cache_backends', array()) as $include) {
  1843. require_once DRUPAL_ROOT . '/' . $include;
  1844. }
  1845. // Check for a cache mode force from settings.php.
  1846. if (settings()->get('page_cache_without_database')) {
  1847. $cache_enabled = TRUE;
  1848. }
  1849. else {
  1850. drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
  1851. $config = config('system.performance');
  1852. $cache_enabled = $config->get('cache.page.use_internal');
  1853. }
  1854. // @todo this is *criminal*. but, necessary, until we fix bootstrap ordering.
  1855. $request = Request::createFromGlobals();
  1856. // If there is no session cookie and cache is enabled (or forced), try
  1857. // to serve a cached page.
  1858. if (!$request->cookies->has(session_name()) && $cache_enabled) {
  1859. // Make sure there is a user object because its timestamp will be checked.
  1860. $user = drupal_anonymous_user();
  1861. // Get the page from the cache.
  1862. $cache = drupal_page_get_cache();
  1863. // If there is a cached page, display it.
  1864. if (is_object($cache)) {
  1865. $response = new Response();
  1866. $response->headers->set('X-Drupal-Cache', 'HIT');
  1867. // Restore the metadata cached with the page.
  1868. _current_path($cache->data['path']);
  1869. drupal_set_title($cache->data['title'], PASS_THROUGH);
  1870. date_default_timezone_set(drupal_get_user_timezone());
  1871. drupal_serve_page_from_cache($cache, $response, $request);
  1872. // We are done.
  1873. $response->prepare($request);
  1874. $response->send();
  1875. exit;
  1876. }
  1877. else {
  1878. drupal_add_http_header('X-Drupal-Cache', 'MISS');
  1879. }
  1880. }
  1881. }
  1882. /**
  1883. * In a test environment, get the test db prefix and set it in $databases.
  1884. */
  1885. function _drupal_initialize_db_test_prefix() {
  1886. // The user agent header is used to pass a database prefix in the request when
  1887. // running tests. However, for security reasons, it is imperative that we
  1888. // validate we ourselves made the request.
  1889. if ($test_prefix = drupal_valid_test_ua()) {
  1890. // Set the test run id for use in other parts of Drupal.
  1891. $test_info = &$GLOBALS['drupal_test_info'];
  1892. $test_info['test_run_id'] = $test_prefix;
  1893. $test_info['in_child_site'] = TRUE;
  1894. foreach ($GLOBALS['databases']['default'] as &$value) {
  1895. // Extract the current default database prefix.
  1896. if (!isset($value['prefix'])) {
  1897. $current_prefix = '';
  1898. }
  1899. elseif (is_array($value['prefix'])) {
  1900. $current_prefix = $value['prefix']['default'];
  1901. }
  1902. else {
  1903. $current_prefix = $value['prefix'];
  1904. }
  1905. // Remove the current database prefix and replace it by our own.
  1906. $value['prefix'] = array(
  1907. 'default' => $current_prefix . $test_prefix,
  1908. );
  1909. }
  1910. }
  1911. }
  1912. /**
  1913. * Initializes the database system by loading database.inc.
  1914. */
  1915. function _drupal_bootstrap_database() {
  1916. // Initialize the database system. Note that the connection
  1917. // won't be initialized until it is actually requested.
  1918. require_once __DIR__ . '/database.inc';
  1919. }
  1920. /**
  1921. * Loads system variables and all enabled bootstrap modules.
  1922. */
  1923. function _drupal_bootstrap_variables() {
  1924. global $conf;
  1925. // Load variables from the database, but do not overwrite variables set in settings.php.
  1926. $conf = variable_initialize(isset($conf) ? $conf : array());
  1927. // Load bootstrap modules.
  1928. require_once __DIR__ . '/module.inc';
  1929. Drupal::moduleHandler()->loadBootstrapModules();
  1930. }
  1931. /**
  1932. * Returns the current bootstrap phase for this Drupal process.
  1933. *
  1934. * The current phase is the one most recently completed by drupal_bootstrap().
  1935. *
  1936. * @see drupal_bootstrap()
  1937. */
  1938. function drupal_get_bootstrap_phase() {
  1939. return drupal_bootstrap();
  1940. }
  1941. /**
  1942. * Retrieves the Drupal Container to standardize object construction.
  1943. *
  1944. * @deprecated This function has been replaced by the \Drupal class. Use that
  1945. * instead.
  1946. *
  1947. * @return Symfony\Component\DependencyInjection\ContainerInterface|bool
  1948. * The instance of the ContainerInterface used to set up and maintain
  1949. * object instances or FALSE if none exist yet.
  1950. */
  1951. function drupal_container() {
  1952. return Drupal::getContainer();
  1953. }
  1954. /**
  1955. * Returns the list of enabled modules.
  1956. *
  1957. * @deprecated as of Drupal 8.0. Use
  1958. * Drupal::moduleHandler()->getModuleList().
  1959. *
  1960. * @see \Drupal\Core\Extension\ModuleHandler::getModuleList()
  1961. */
  1962. function module_list() {
  1963. $modules = array_keys(Drupal::moduleHandler()->getModuleList());
  1964. return array_combine($modules, $modules);
  1965. }
  1966. /**
  1967. * Determines which modules are implementing a hook.
  1968. *
  1969. * @deprecated as of Drupal 8.0. Use
  1970. * Drupal::moduleHandler()->getImplementations($hook).
  1971. *
  1972. * @see \Drupal\Core\Extension\ModuleHandler::getImplementations()
  1973. */
  1974. function module_implements($hook) {
  1975. return Drupal::moduleHandler()->getImplementations($hook);
  1976. }
  1977. /**
  1978. * Invokes a hook in a particular module.
  1979. *
  1980. * All arguments are passed by value. Use drupal_alter() if you need to pass
  1981. * arguments by reference.
  1982. *
  1983. * @deprecated as of Drupal 8.0. Use
  1984. * Drupal::moduleHandler()->invoke($module, $hook, $args = array()).
  1985. *
  1986. * @see drupal_alter()
  1987. * @see \Drupal\Core\Extension\ModuleHandler::invoke()
  1988. */
  1989. function module_invoke($module, $hook) {
  1990. $args = func_get_args();
  1991. // Remove $module and $hook from the arguments.
  1992. unset($args[0], $args[1]);
  1993. return Drupal::moduleHandler()->invoke($module, $hook, $args);
  1994. }
  1995. /**
  1996. * Invokes a hook in all enabled modules that implement it.
  1997. *
  1998. * All arguments are passed by value. Use drupal_alter() if you need to pass
  1999. * arguments by reference.
  2000. *
  2001. * @deprecated as of Drupal 8.0. Use
  2002. * Drupal::moduleHandler()->invokeAll($hook).
  2003. *
  2004. * @see drupal_alter()
  2005. * @see \Drupal\Core\Extension\ModuleHandler::invokeAll()
  2006. */
  2007. function module_invoke_all($hook) {
  2008. $args = func_get_args();
  2009. // Remove $hook from the arguments.
  2010. array_shift($args);
  2011. return Drupal::moduleHandler()->invokeAll($hook, $args);
  2012. }
  2013. /**
  2014. * Passes alterable variables to specific hook_TYPE_alter() implementations.
  2015. *
  2016. * @deprecated as of Drupal 8.0. Use
  2017. * Drupal::moduleHandler()->alter($hook).
  2018. *
  2019. * @see \Drupal\Core\Extension\ModuleHandler::alter()
  2020. */
  2021. function drupal_alter($type, &$data, &$context1 = NULL, &$context2 = NULL) {
  2022. return Drupal::moduleHandler()->alter($type, $data, $context1, $context2);
  2023. }
  2024. /**
  2025. * Determines whether a given module exists.
  2026. *
  2027. * @deprecated as of Drupal 8.0. Use
  2028. * Drupal::moduleHandler()->moduleExists($hook).
  2029. *
  2030. * @see \Drupal\Core\Extension\ModuleHandler::moduleExists()
  2031. */
  2032. function module_exists($module) {
  2033. return Drupal::moduleHandler()->moduleExists($module);
  2034. }
  2035. /**
  2036. * Determines whether a module implements a hook.
  2037. *
  2038. * @deprecated as of Drupal 8.0. Use
  2039. * Drupal::moduleHandler()->implementsHook($module, $hook).
  2040. *
  2041. * @see \Drupal\Core\Extension\ModuleHandler::implementsHook()
  2042. */
  2043. function module_hook($module, $hook) {
  2044. return Drupal::moduleHandler()->implementsHook($module, $hook);
  2045. }
  2046. /**
  2047. * Returns the test prefix if this is an internal request from SimpleTest.
  2048. *
  2049. * @param string $new_prefix
  2050. * Internal use only. A new prefix to be stored. Passed in by tests that use
  2051. * the test runner from within a test.
  2052. *
  2053. * @return
  2054. * Either the simpletest prefix (the string "simpletest" followed by any
  2055. * number of digits) or FALSE if the user agent does not contain a valid
  2056. * HMAC and timestamp.
  2057. */
  2058. function drupal_valid_test_ua($new_prefix = NULL) {
  2059. static $test_prefix;
  2060. if (isset($new_prefix)) {
  2061. $test_prefix = $new_prefix;
  2062. }
  2063. if (isset($test_prefix)) {
  2064. return $test_prefix;
  2065. }
  2066. if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
  2067. list(, $prefix, $time, $salt, $hmac) = $matches;
  2068. $check_string = $prefix . ';' . $time . ';' . $salt;
  2069. // We use the salt from settings.php to make the HMAC key, since
  2070. // the database is not yet initialized and we can't access any Drupal variables.
  2071. // The file properties add more entropy not easily accessible to others.
  2072. $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
  2073. $time_diff = REQUEST_TIME - $time;
  2074. // We cant use Crypt::hmacBase64() yet because this can be called in very
  2075. // early bootstrap when autoloader has not been initialized yet.
  2076. $test_hmac = base64_encode(hash_hmac('sha256', $check_string, $key, TRUE));
  2077. $test_hmac = strtr($test_hmac, array('+' => '-', '/' => '_', '=' => ''));
  2078. // Since we are making a local request a 5 second time window is allowed,
  2079. // and the HMAC must match.
  2080. if ($time_diff >= 0 && $time_diff <= 5 && $hmac == $test_hmac) {
  2081. $test_prefix = $prefix;
  2082. _drupal_load_test_overrides($test_prefix);
  2083. return $test_prefix;
  2084. }
  2085. }
  2086. $test_prefix = FALSE;
  2087. return $test_prefix;
  2088. }
  2089. /**
  2090. * Overrides low-level and environment-specific configuration.
  2091. *
  2092. * Very strictly for internal use only.
  2093. *
  2094. * Loads settings.php from the simpletest public files directory. These files
  2095. * can change the global $conf, the global $config_directories, the return
  2096. * value of conf_path(), and settings().
  2097. *
  2098. * @param string $test_prefix
  2099. * The simpletest prefix.
  2100. */
  2101. function _drupal_load_test_overrides($test_prefix) {
  2102. global $conf, $config_directories;
  2103. // Do not use the parent site's config directories. Use only the child site's.
  2104. // @see Drupal\simpletest\TestBase::prepareConfigDirectories()
  2105. $path_prefix = 'simpletest/' . substr($test_prefix, 10);
  2106. $config_directories = array();
  2107. foreach (array(CONFIG_ACTIVE_DIRECTORY, CONFIG_STAGING_DIRECTORY) as $type) {
  2108. $config_directories[$type] = array('path' => $path_prefix . '/config_' . $type);
  2109. }
  2110. // Check for and load a settings.php file in the simpletest files directory.
  2111. $filename = conf_path() . '/files/' . $path_prefix . '/settings.php';
  2112. if (file_exists($filename)) {
  2113. $settings = settings()->getAll();
  2114. $conf_path = &drupal_static('conf_path');
  2115. // This can override $conf, $conf_path, $settings, and $config_directories.
  2116. include $filename;
  2117. // Keep the overriden $conf_path alive across drupal_static_reset() calls.
  2118. // @see conf_path()
  2119. $settings['simpletest_conf_path'] = $conf_path;
  2120. new Settings($settings);
  2121. }
  2122. }
  2123. /**
  2124. * Generates a user agent string with a HMAC and timestamp for simpletest.
  2125. */
  2126. function drupal_generate_test_ua($prefix) {
  2127. static $key;
  2128. if (!isset($key)) {
  2129. // We use the salt from settings.php to make the HMAC key, since
  2130. // the database is not yet initialized and we can't access any Drupal variables.
  2131. // The file properties add more entropy not easily accessible to others.
  2132. $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
  2133. }
  2134. // Generate a moderately secure HMAC based on the database credentials.
  2135. $salt = uniqid('', TRUE);
  2136. $check_string = $prefix . ';' . time() . ';' . $salt;
  2137. return $check_string . ';' . Crypt::hmacBase64($check_string, $key);
  2138. }
  2139. /**
  2140. * Enables use of the theme system without requiring database access.
  2141. *
  2142. * Loads and initializes the theme system for site installs, updates and when
  2143. * the site is in maintenance mode. This also applies when the database fails.
  2144. *
  2145. * @see _drupal_maintenance_theme()
  2146. */
  2147. function drupal_maintenance_theme() {
  2148. require_once __DIR__ . '/theme.maintenance.inc';
  2149. _drupal_maintenance_theme();
  2150. }
  2151. /**
  2152. * Returns TRUE if a Drupal installation is currently being attempted.
  2153. */
  2154. function drupal_installation_attempted() {
  2155. // This cannot rely on the MAINTENANCE_MODE constant, since that would prevent
  2156. // tests from using the non-interactive installer, in which case Drupal
  2157. // only happens to be installed within the same request, but subsequently
  2158. // executed code does not involve the installer at all.
  2159. // @see install_drupal()
  2160. return isset($GLOBALS['install_state']) && empty($GLOBALS['install_state']['installation_finished']);
  2161. }
  2162. /**
  2163. * Returns the name of the proper localization function.
  2164. *
  2165. * get_t() exists to support localization for code that might run during
  2166. * the installation phase, when some elements of the system might not have
  2167. * loaded.
  2168. *
  2169. * This would include implementations of hook_install(), which could run
  2170. * during the Drupal installation phase, and might also be run during
  2171. * non-installation time, such as while installing the module from the the
  2172. * module administration page.
  2173. *
  2174. * Example usage:
  2175. * @code
  2176. * $t = get_t();
  2177. * $translated = $t('translate this');
  2178. * @endcode
  2179. *
  2180. * Use t() if your code will never run during the Drupal installation phase.
  2181. * Use st() if your code will only run during installation and never any other
  2182. * time. Use get_t() if your code could run in either circumstance.
  2183. *
  2184. * @todo Remove this in favor of t().
  2185. *
  2186. * @see t()
  2187. * @see st()
  2188. * @ingroup sanitization
  2189. */
  2190. function get_t() {
  2191. return 't';
  2192. }
  2193. /**
  2194. * Initializes all the defined language types and sets the default langcode.
  2195. */
  2196. function drupal_language_initialize() {
  2197. $language_manager = Drupal::service('language_manager');
  2198. $language_manager->init();
  2199. Drupal::translation()->setDefaultLangcode($language_manager->getLanguage(Language::TYPE_INTERFACE)->langcode);
  2200. }
  2201. /**
  2202. * Returns the language object for a given language type.
  2203. *
  2204. * @see Drupal\Core\Language\LanguageManager
  2205. *
  2206. * @param string $type
  2207. * The type of language object needed, e.g. Language::TYPE_INTERFACE.
  2208. *
  2209. * @deprecated as of Drupal 8.0. Use
  2210. * Drupal::service('language_manager')->getLanguage($type).
  2211. */
  2212. function language($type) {
  2213. return Drupal::service('language_manager')->getLanguage($type);
  2214. }
  2215. /**
  2216. * Returns an array of the available language types.
  2217. *
  2218. * @return array
  2219. * An array of all language types where the keys of each are the language type
  2220. * name and its value is its configurability (TRUE/FALSE).
  2221. */
  2222. function language_types_get_all() {
  2223. return array_keys(variable_get('language_types', language_types_get_default()));
  2224. }
  2225. /**
  2226. * Returns a list of the built-in language types.
  2227. *
  2228. * @return array
  2229. * An array of key-values pairs where the key is the language type name and
  2230. * the value is its configurability (TRUE/FALSE).
  2231. */
  2232. function language_types_get_default() {
  2233. return array(
  2234. Language::TYPE_INTERFACE => TRUE,
  2235. Language::TYPE_CONTENT => FALSE,
  2236. Language::TYPE_URL => FALSE,
  2237. );
  2238. }
  2239. /**
  2240. * Returns TRUE if there is more than one language enabled.
  2241. *
  2242. * @return bool
  2243. * TRUE if more than one language is enabled.
  2244. */
  2245. function language_multilingual() {
  2246. // The "language_count" variable stores the number of enabled languages to
  2247. // avoid unnecessarily querying the database when building the list of
  2248. // enabled languages on monolingual sites.
  2249. return variable_get('language_count', 1) > 1;
  2250. }
  2251. /**
  2252. * Returns a list of languages set up on the site.
  2253. *
  2254. * @param $flags
  2255. * (optional) Specifies the state of the languages that have to be returned.
  2256. * It can be: Language::STATE_CONFIGURABLE, Language::STATE_LOCKED,
  2257. * Language::STATE_ALL.
  2258. *
  2259. * @return array
  2260. * An associative array of languages, keyed by the language code, ordered by
  2261. * weight ascending and name ascending.
  2262. */
  2263. function language_list($flags = Language::STATE_CONFIGURABLE) {
  2264. $languages = &drupal_static(__FUNCTION__);
  2265. // Initialize master language list.
  2266. if (!isset($languages)) {
  2267. // Initialize local language list cache.
  2268. $languages = array();
  2269. // Fill in master language list based on current configuration.
  2270. $default = language_default();
  2271. if (language_multilingual() || module_exists('language')) {
  2272. // Use language module configuration if available.
  2273. $languages = db_query('SELECT * FROM {language} ORDER BY weight ASC, name ASC')->fetchAllAssoc('langcode', PDO::FETCH_ASSOC);
  2274. // Initialize default property so callers have an easy reference and can
  2275. // save the same object without data loss.
  2276. foreach ($languages as $langcode => $info) {
  2277. $info['default'] = ($langcode == $default->langcode);
  2278. $languages[$langcode] = new Language($info);
  2279. }
  2280. }
  2281. else {
  2282. // No language module, so use the default language only.
  2283. $languages = array($default->langcode => $default);
  2284. // Add the special languages, they will be filtered later if needed.
  2285. $languages += language_default_locked_languages($default->weight);
  2286. }
  2287. }
  2288. // Filter the full list of languages based on the value of the $all flag. By
  2289. // default we remove the locked languages, but the caller may request for
  2290. // those languages to be added as well.
  2291. $filtered_languages = array();
  2292. // Add the site's default language if flagged as allowed value.
  2293. if ($flags & Language::STATE_SITE_DEFAULT) {
  2294. $default = isset($default) ? $default : language_default();
  2295. // Rename the default language.
  2296. $default->name = t("Site's default language (@lang_name)", array('@lang_name' => $default->name));
  2297. $filtered_languages['site_default'] = $default;
  2298. }
  2299. foreach ($languages as $langcode => $language) {
  2300. if (($language->locked && !($flags & Language::STATE_LOCKED)) || (!$language->locked && !($flags & Language::STATE_CONFIGURABLE))) {
  2301. continue;
  2302. }
  2303. $filtered_languages[$langcode] = $language;
  2304. }
  2305. return $filtered_languages;
  2306. }
  2307. /**
  2308. * Returns a list of the default locked languages.
  2309. *
  2310. * @param int $weight
  2311. * An integer value that is used as the start value for the weights of the
  2312. * locked languages.
  2313. *
  2314. * @return array
  2315. * An array of language objects.
  2316. */
  2317. function language_default_locked_languages($weight = 0) {
  2318. $locked_language = array(
  2319. 'default' => FALSE,
  2320. 'locked' => TRUE,
  2321. 'enabled' => TRUE,
  2322. );
  2323. $languages = array();
  2324. $languages[Language::LANGCODE_NOT_SPECIFIED] = new Language(array(
  2325. 'langcode' => Language::LANGCODE_NOT_SPECIFIED,
  2326. 'name' => t('Not specified'),
  2327. 'weight' => ++$weight,
  2328. ) + $locked_language);
  2329. $languages[Language::LANGCODE_NOT_APPLICABLE] = new Language(array(
  2330. 'langcode' => Language::LANGCODE_NOT_APPLICABLE,
  2331. 'name' => t('Not applicable'),
  2332. 'weight' => ++$weight,
  2333. ) + $locked_language);
  2334. return $languages;
  2335. }
  2336. /**
  2337. * Loads a language object from the database.
  2338. *
  2339. * @param string $langcode
  2340. * The language code.
  2341. *
  2342. * @return Drupal\core\Language\Language | FALSE
  2343. * A fully-populated language object or FALSE.
  2344. */
  2345. function language_load($langcode) {
  2346. $languages = language_list(Language::STATE_ALL);
  2347. return isset($languages[$langcode]) ? $languages[$langcode] : FALSE;
  2348. }
  2349. /**
  2350. * Produced the printed name for a language for display.
  2351. *
  2352. * @param string $langcode
  2353. * The language code.
  2354. *
  2355. * @return string
  2356. * The printed name of the language.
  2357. */
  2358. function language_name($langcode) {
  2359. if ($langcode == Language::LANGCODE_NOT_SPECIFIED) {
  2360. return t('None');
  2361. }
  2362. if ($language = language_load($langcode)) {
  2363. return $language->name;
  2364. }
  2365. if (empty($langcode)) {
  2366. return t('Unknown');
  2367. }
  2368. return t('Unknown (@langcode)', array('@langcode' => $langcode));
  2369. }
  2370. /**
  2371. * Checks if a language is locked.
  2372. *
  2373. * @param string $langcode
  2374. * The language code.
  2375. *
  2376. * @return bool
  2377. * Returns whether the language is locked.
  2378. */
  2379. function language_is_locked($langcode) {
  2380. $language = language_load($langcode);
  2381. return ($language ? $language->locked : FALSE);
  2382. }
  2383. /**
  2384. * Returns the default language used on the site.
  2385. *
  2386. * @return Drupal\Core\Language\Language
  2387. * A language object.
  2388. */
  2389. function language_default() {
  2390. $info = variable_get('language_default', array(
  2391. 'langcode' => 'en',
  2392. 'name' => 'English',
  2393. 'direction' => 0,
  2394. 'weight' => 0,
  2395. 'locked' => 0,
  2396. ));
  2397. $info['default'] = TRUE;
  2398. return new Language($info);
  2399. }
  2400. /**
  2401. * Stores or retrieves the path derived during language negotiation.
  2402. *
  2403. * @param string $new_path
  2404. * The altered path.
  2405. *
  2406. * @todo Replace this with a path processor in language module. See
  2407. * http://drupal.org/node/1888424.
  2408. */
  2409. function _language_resolved_path($new_path = NULL) {
  2410. $path = &drupal_static(__FUNCTION__, NULL);
  2411. if ($new_path === NULL) {
  2412. return $path;
  2413. }
  2414. $path = $new_path;
  2415. return $path;
  2416. }
  2417. /**
  2418. * Returns the requested URL path of the page being viewed.
  2419. *
  2420. * Examples:
  2421. * - http://example.com/node/306 returns "node/306".
  2422. * - http://example.com/drupalfolder/node/306 returns "node/306" while
  2423. * base_path() returns "/drupalfolder/".
  2424. * - http://example.com/path/alias (which is a path alias for node/306) returns
  2425. * "path/alias" as opposed to the internal path.
  2426. * - http://example.com/index.php returns an empty string (meaning: front page).
  2427. * - http://example.com/index.php?page=1 returns an empty string.
  2428. *
  2429. * @return
  2430. * The requested Drupal URL path.
  2431. *
  2432. * @see current_path()
  2433. */
  2434. function request_path() {
  2435. static $path;
  2436. if (isset($path)) {
  2437. return $path;
  2438. }
  2439. // Get the part of the URI between the base path of the Drupal installation
  2440. // and the query string, and unescape it.
  2441. $request_path = request_uri(TRUE);
  2442. $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
  2443. $path = substr(urldecode($request_path), $base_path_len + 1);
  2444. // Depending on server configuration, the URI might or might not include the
  2445. // script name. For example, the front page might be accessed as
  2446. // http://example.com or as http://example.com/index.php, and the "user"
  2447. // page might be accessed as http://example.com/user or as
  2448. // http://example.com/index.php/user. Strip the script name from $path.
  2449. $script = basename($_SERVER['SCRIPT_NAME']);
  2450. if ($path == $script) {
  2451. $path = '';
  2452. }
  2453. elseif (strpos($path, $script . '/') === 0) {
  2454. $path = substr($path, strlen($script) + 1);
  2455. }
  2456. // Extra slashes can appear in URLs or under some conditions, added by Apache,
  2457. // so normalize.
  2458. $path = trim($path, '/');
  2459. return $path;
  2460. }
  2461. /**
  2462. * @todo This is a temporary function pending refactoring Drupal to use
  2463. * Symfony's Request object exclusively.
  2464. */
  2465. function _current_path($path = NULL) {
  2466. static $current_path = '';
  2467. if (isset($path)) {
  2468. $current_path = $path;
  2469. }
  2470. return $current_path;
  2471. }
  2472. /**
  2473. * Returns a component of the current Drupal path.
  2474. *
  2475. * When viewing a page at the path "admin/structure/types", for example, arg(0)
  2476. * returns "admin", arg(1) returns "structure", and arg(2) returns "types".
  2477. *
  2478. * Avoid use of this function where possible, as resulting code is hard to
  2479. * read. In menu callback functions, attempt to use named arguments. See the
  2480. * explanation in menu.inc for how to construct callbacks that take arguments.
  2481. * When attempting to use this function to load an element from the current
  2482. * path, e.g. loading the node on a node page, use menu_get_object() instead.
  2483. *
  2484. * @param $index
  2485. * The index of the component, where each component is separated by a '/'
  2486. * (forward-slash), and where the first component has an index of 0 (zero).
  2487. * @param $path
  2488. * A path to break into components. Defaults to the path of the current page.
  2489. *
  2490. * @return
  2491. * The component specified by $index, or NULL if the specified component was
  2492. * not found. If called without arguments, it returns an array containing all
  2493. * the components of the current path.
  2494. */
  2495. function arg($index = NULL, $path = NULL) {
  2496. // Even though $arguments doesn't need to be resettable for any functional
  2497. // reasons (the result of explode() does not depend on any run-time
  2498. // information), it should be resettable anyway in case a module needs to
  2499. // free up the memory used by it.
  2500. // Use the advanced drupal_static() pattern, since this is called very often.
  2501. static $drupal_static_fast;
  2502. if (!isset($drupal_static_fast)) {
  2503. $drupal_static_fast['arguments'] = &drupal_static(__FUNCTION__);
  2504. }
  2505. $arguments = &$drupal_static_fast['arguments'];
  2506. if (!isset($path)) {
  2507. // @todo The public function current_path() is not available during early
  2508. // bootstrap.
  2509. $path = _current_path();
  2510. }
  2511. if (!isset($arguments[$path])) {
  2512. $arguments[$path] = explode('/', $path);
  2513. }
  2514. if (!isset($index)) {
  2515. return $arguments[$path];
  2516. }
  2517. if (isset($arguments[$path][$index])) {
  2518. return $arguments[$path][$index];
  2519. }
  2520. }
  2521. /**
  2522. * Initializes and returns the class loader.
  2523. *
  2524. * The class loader is responsible for lazy-loading all PSR-0 compatible
  2525. * classes, interfaces, and traits (PHP 5.4 and later). It's only dependency
  2526. * is DRUPAL_ROOT. Otherwise it may be called as early as possible.
  2527. *
  2528. * @param $class_loader
  2529. * The name of class loader to use. This can be used to change the class
  2530. * loader class when calling drupal_classloader() from settings.php. It is
  2531. * ignored otherwise.
  2532. *
  2533. * @return \Symfony\Component\ClassLoader\ClassLoader
  2534. * A ClassLoader class instance (or extension thereof).
  2535. */
  2536. function drupal_classloader($class_loader = NULL) {
  2537. // By default, use the ClassLoader which is best for development, as it does
  2538. // not break when code is moved on the file system. However, as it is slow,
  2539. // allow to use the APC class loader in production.
  2540. static $loader;
  2541. if (!isset($loader)) {
  2542. // Include the Symfony ClassLoader for loading PSR-0-compatible classes.
  2543. require_once DRUPAL_ROOT . '/core/vendor/symfony/class-loader/Symfony/Component/ClassLoader/ClassLoader.php';
  2544. $loader = new ClassLoader();
  2545. // Register the class loader.
  2546. // When configured to use APC, the ApcClassLoader is registered instead.
  2547. // Note that ApcClassLoader decorates ClassLoader and only provides the
  2548. // findFile() method, but none of the others. The actual registry is still
  2549. // in ClassLoader.
  2550. if (!isset($class_loader)) {
  2551. $class_loader = settings()->get('class_loader', 'default');
  2552. }
  2553. if ($class_loader === 'apc') {
  2554. require_once DRUPAL_ROOT . '/core/vendor/symfony/class-loader/Symfony/Component/ClassLoader/ApcClassLoader.php';
  2555. $apc_loader = new ApcClassLoader('drupal.' . drupal_get_hash_salt(), $loader);
  2556. $apc_loader->register();
  2557. }
  2558. else {
  2559. $loader->register();
  2560. }
  2561. // Register namespaces for vendor libraries managed by Composer.
  2562. $prefixes_and_namespaces = require DRUPAL_ROOT . '/core/vendor/composer/autoload_namespaces.php';
  2563. $loader->addPrefixes($prefixes_and_namespaces);
  2564. // Register the loader with PHP.
  2565. $loader->register();
  2566. }
  2567. return $loader;
  2568. }
  2569. /**
  2570. * Registers an additional namespace.
  2571. *
  2572. * @param string $name
  2573. * The namespace component to register; e.g., 'node'.
  2574. * @param string $path
  2575. * The relative path to the Drupal component in the filesystem.
  2576. */
  2577. function drupal_classloader_register($name, $path) {
  2578. $loader = drupal_classloader();
  2579. $loader->addPrefix('Drupal\\' . $name, DRUPAL_ROOT . '/' . $path . '/lib');
  2580. }
  2581. /**
  2582. * Provides central static variable storage.
  2583. *
  2584. * All functions requiring a static variable to persist or cache data within
  2585. * a single page request are encouraged to use this function unless it is
  2586. * absolutely certain that the static variable will not need to be reset during
  2587. * the page request. By centralizing static variable storage through this
  2588. * function, other functions can rely on a consistent API for resetting any
  2589. * other function's static variables.
  2590. *
  2591. * Example:
  2592. * @code
  2593. * function example_list($field = 'default') {
  2594. * $examples = &drupal_static(__FUNCTION__);
  2595. * if (!isset($examples)) {
  2596. * // If this function is being called for the first time after a reset,
  2597. * // query the database and execute any other code needed to retrieve
  2598. * // information.
  2599. * ...
  2600. * }
  2601. * if (!isset($examples[$field])) {
  2602. * // If this function is being called for the first time for a particular
  2603. * // index field, then execute code needed to index the information already
  2604. * // available in $examples by the desired field.
  2605. * ...
  2606. * }
  2607. * // Subsequent invocations of this function for a particular index field
  2608. * // skip the above two code blocks and quickly return the already indexed
  2609. * // information.
  2610. * return $examples[$field];
  2611. * }
  2612. * function examples_admin_overview() {
  2613. * // When building the content for the overview page, make sure to get
  2614. * // completely fresh information.
  2615. * drupal_static_reset('example_list');
  2616. * ...
  2617. * }
  2618. * @endcode
  2619. *
  2620. * In a few cases, a function can have certainty that there is no legitimate
  2621. * use-case for resetting that function's static variable. This is rare,
  2622. * because when writing a function, it's hard to forecast all the situations in
  2623. * which it will be used. A guideline is that if a function's static variable
  2624. * does not depend on any information outside of the function that might change
  2625. * during a single page request, then it's ok to use the "static" keyword
  2626. * instead of the drupal_static() function.
  2627. *
  2628. * Example:
  2629. * @code
  2630. * function system_get_module_info($property) {
  2631. * static $info;
  2632. * if (!isset($info)) {
  2633. * $info = new ModuleInfo('system_info', 'cache');
  2634. * }
  2635. * return $info[$property];
  2636. * }
  2637. * @endcode
  2638. *
  2639. * In a few cases, a function needs a resettable static variable, but the
  2640. * function is called many times (100+) during a single page request, so
  2641. * every microsecond of execution time that can be removed from the function
  2642. * counts. These functions can use a more cumbersome, but faster variant of
  2643. * calling drupal_static(). It works by storing the reference returned by
  2644. * drupal_static() in the calling function's own static variable, thereby
  2645. * removing the need to call drupal_static() for each iteration of the function.
  2646. * Conceptually, it replaces:
  2647. * @code
  2648. * $foo = &drupal_static(__FUNCTION__);
  2649. * @endcode
  2650. * with:
  2651. * @code
  2652. * // Unfortunately, this does not work.
  2653. * static $foo = &drupal_static(__FUNCTION__);
  2654. * @endcode
  2655. * However, the above line of code does not work, because PHP only allows static
  2656. * variables to be initializied by literal values, and does not allow static
  2657. * variables to be assigned to references.
  2658. * - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
  2659. * - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
  2660. * The example below shows the syntax needed to work around both limitations.
  2661. * For benchmarks and more information, see http://drupal.org/node/619666.
  2662. *
  2663. * Example:
  2664. * @code
  2665. * function user_access($string, $account = NULL) {
  2666. * // Use the advanced drupal_static() pattern, since this is called very often.
  2667. * static $drupal_static_fast;
  2668. * if (!isset($drupal_static_fast)) {
  2669. * $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  2670. * }
  2671. * $perm = &$drupal_static_fast['perm'];
  2672. * ...
  2673. * }
  2674. * @endcode
  2675. *
  2676. * @param $name
  2677. * Globally unique name for the variable. For a function with only one static,
  2678. * variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
  2679. * is recommended. For a function with multiple static variables add a
  2680. * distinguishing suffix to the function name for each one.
  2681. * @param $default_value
  2682. * Optional default value.
  2683. * @param $reset
  2684. * TRUE to reset a specific named variable, or all variables if $name is NULL.
  2685. * Resetting every variable should only be used, for example, for running
  2686. * unit tests with a clean environment. Should be used only though via
  2687. * function drupal_static_reset() and the return value should not be used in
  2688. * this case.
  2689. *
  2690. * @return
  2691. * Returns a variable by reference.
  2692. *
  2693. * @see drupal_static_reset()
  2694. */
  2695. function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  2696. static $data = array(), $default = array();
  2697. // First check if dealing with a previously defined static variable.
  2698. if (isset($data[$name]) || array_key_exists($name, $data)) {
  2699. // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
  2700. if ($reset) {
  2701. // Reset pre-existing static variable to its default value.
  2702. $data[$name] = $default[$name];
  2703. }
  2704. return $data[$name];
  2705. }
  2706. // Neither $data[$name] nor $default[$name] static variables exist.
  2707. if (isset($name)) {
  2708. if ($reset) {
  2709. // Reset was called before a default is set and yet a variable must be
  2710. // returned.
  2711. return $data;
  2712. }
  2713. // First call with new non-NULL $name. Initialize a new static variable.
  2714. $default[$name] = $data[$name] = $default_value;
  2715. return $data[$name];
  2716. }
  2717. // Reset all: ($name == NULL). This needs to be done one at a time so that
  2718. // references returned by earlier invocations of drupal_static() also get
  2719. // reset.
  2720. foreach ($default as $name => $value) {
  2721. $data[$name] = $value;
  2722. }
  2723. // As the function returns a reference, the return should always be a
  2724. // variable.
  2725. return $data;
  2726. }
  2727. /**
  2728. * Resets one or all centrally stored static variable(s).
  2729. *
  2730. * @param $name
  2731. * Name of the static variable to reset. Omit to reset all variables.
  2732. */
  2733. function drupal_static_reset($name = NULL) {
  2734. drupal_static($name, NULL, TRUE);
  2735. }
  2736. /**
  2737. * Detects whether the current script is running in a command-line environment.
  2738. */
  2739. function drupal_is_cli() {
  2740. return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
  2741. }
  2742. /**
  2743. * Formats text for emphasized display in a placeholder inside a sentence.
  2744. *
  2745. * @see \Drupal\Component\Utility\String::placeholder()
  2746. */
  2747. function drupal_placeholder($text) {
  2748. return String::placeholder($text);
  2749. }
  2750. /**
  2751. * Registers a function for execution on shutdown.
  2752. *
  2753. * Wrapper for register_shutdown_function() that catches thrown exceptions to
  2754. * avoid "Exception thrown without a stack frame in Unknown".
  2755. *
  2756. * @param $callback
  2757. * The shutdown function to register.
  2758. * @param ...
  2759. * Additional arguments to pass to the shutdown function.
  2760. *
  2761. * @return
  2762. * Array of shutdown functions to be executed.
  2763. *
  2764. * @see register_shutdown_function()
  2765. * @ingroup php_wrappers
  2766. */
  2767. function &drupal_register_shutdown_function($callback = NULL) {
  2768. // We cannot use drupal_static() here because the static cache is reset during
  2769. // batch processing, which breaks batch handling.
  2770. static $callbacks = array();
  2771. if (isset($callback)) {
  2772. // Only register the internal shutdown function once.
  2773. if (empty($callbacks)) {
  2774. register_shutdown_function('_drupal_shutdown_function');
  2775. }
  2776. $args = func_get_args();
  2777. array_shift($args);
  2778. // Save callback and arguments
  2779. $callbacks[] = array('callback' => $callback, 'arguments' => $args);
  2780. }
  2781. return $callbacks;
  2782. }
  2783. /**
  2784. * Executes registered shutdown functions.
  2785. */
  2786. function _drupal_shutdown_function() {
  2787. $callbacks = &drupal_register_shutdown_function();
  2788. // Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
  2789. // was in the normal context of execution.
  2790. chdir(DRUPAL_ROOT);
  2791. try {
  2792. while (list($key, $callback) = each($callbacks)) {
  2793. call_user_func_array($callback['callback'], $callback['arguments']);
  2794. }
  2795. }
  2796. catch (Exception $exception) {
  2797. // If we are displaying errors, then do so with no possibility of a further
  2798. // uncaught exception being thrown.
  2799. require_once __DIR__ . '/errors.inc';
  2800. if (error_displayable()) {
  2801. print '<h1>Uncaught exception thrown in shutdown function.</h1>';
  2802. print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
  2803. }
  2804. error_log($exception);
  2805. }
  2806. }
  2807. /**
  2808. * Compares the memory required for an operation to the available memory.
  2809. *
  2810. * @param $required
  2811. * The memory required for the operation, expressed as a number of bytes with
  2812. * optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
  2813. * 9mbytes).
  2814. * @param $memory_limit
  2815. * (optional) The memory limit for the operation, expressed as a number of
  2816. * bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
  2817. * 6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
  2818. * memory_limit will be used. Defaults to NULL.
  2819. *
  2820. * @return
  2821. * TRUE if there is sufficient memory to allow the operation, or FALSE
  2822. * otherwise.
  2823. */
  2824. function drupal_check_memory_limit($required, $memory_limit = NULL) {
  2825. if (!isset($memory_limit)) {
  2826. $memory_limit = ini_get('memory_limit');
  2827. }
  2828. // There is sufficient memory if:
  2829. // - No memory limit is set.
  2830. // - The memory limit is set to unlimited (-1).
  2831. // - The memory limit is greater than or equal to the memory required for
  2832. // the operation.
  2833. return ((!$memory_limit) || ($memory_limit == -1) || (parse_size($memory_limit) >= parse_size($required)));
  2834. }
  2835. /**
  2836. * @defgroup lock Locking mechanisms
  2837. * @{
  2838. * Functions to coordinate long-running operations across requests.
  2839. *
  2840. * In most environments, multiple Drupal page requests (a.k.a. threads or
  2841. * processes) will execute in parallel. This leads to potential conflicts or
  2842. * race conditions when two requests execute the same code at the same time. A
  2843. * common example of this is a rebuild like menu_router_rebuild() where we
  2844. * invoke many hook implementations to get and process data from all active
  2845. * modules, and then delete the current data in the database to insert the new
  2846. * afterwards.
  2847. *
  2848. * This is a cooperative, advisory lock system. Any long-running operation
  2849. * that could potentially be attempted in parallel by multiple requests should
  2850. * try to acquire a lock before proceeding. By obtaining a lock, one request
  2851. * notifies any other requests that a specific operation is in progress which
  2852. * must not be executed in parallel.
  2853. *
  2854. * To use this API, pick a unique name for the lock. A sensible choice is the
  2855. * name of the function performing the operation. A very simple example use of
  2856. * this API:
  2857. * @code
  2858. * function mymodule_long_operation() {
  2859. * if (lock()->acquire('mymodule_long_operation')) {
  2860. * // Do the long operation here.
  2861. * // ...
  2862. * lock()->release('mymodule_long_operation');
  2863. * }
  2864. * }
  2865. * @endcode
  2866. *
  2867. * If a function acquires a lock it should always release it when the
  2868. * operation is complete by calling lock()->release(), as in the example.
  2869. *
  2870. * A function that has acquired a lock may attempt to renew a lock (extend the
  2871. * duration of the lock) by calling lock()->acquire() again during the operation.
  2872. * Failure to renew a lock is indicative that another request has acquired
  2873. * the lock, and that the current operation may need to be aborted.
  2874. *
  2875. * If a function fails to acquire a lock it may either immediately return, or
  2876. * it may call lock()->wait() if the rest of the current page request requires
  2877. * that the operation in question be complete. After lock()->wait() returns,
  2878. * the function may again attempt to acquire the lock, or may simply allow the
  2879. * page request to proceed on the assumption that a parallel request completed
  2880. * the operation.
  2881. *
  2882. * lock()->acquire() and lock()->wait() will automatically break (delete) a lock
  2883. * whose duration has exceeded the timeout specified when it was acquired.
  2884. */
  2885. /**
  2886. * Get locking layer instance.
  2887. *
  2888. * @deprecated Use Drupal::lock() instead, or even better have the lock service
  2889. * injected into your object.
  2890. *
  2891. * @return Drupal\Core\Lock\LockBackendInterface
  2892. */
  2893. function lock() {
  2894. return Drupal::lock();
  2895. }
  2896. /**
  2897. * @} End of "defgroup lock".
  2898. */

Functions

Namesort descending Description
arg Returns a component of the current Drupal path.
bootstrap_hooks Defines the critical hooks that force modules to always be loaded.
bootstrap_invoke_all Invokes a bootstrap hook in all bootstrap modules that implement it.
check_plain Encodes special characters in a plain-text string for display as HTML.
config_get_config_directory Returns the path of a configuration directory.
conf_path Returns the appropriate configuration directory.
drupal_add_http_header Deprecated Sets an HTTP response header for the current page.
drupal_alter Deprecated Passes alterable variables to specific hook_TYPE_alter() implementations.
drupal_anonymous_user Generates a default anonymous $user object.
drupal_bootstrap Ensures Drupal is bootstrapped to the specified phase.
drupal_check_memory_limit Compares the memory required for an operation to the available memory.
drupal_classloader Initializes and returns the class loader.
drupal_classloader_register Registers an additional namespace.
drupal_container Deprecated Retrieves the Drupal Container to standardize object construction.
drupal_environment_initialize Initializes the PHP environment.
drupal_generate_test_ua Generates a user agent string with a HMAC and timestamp for simpletest.
drupal_get_bootstrap_phase Returns the current bootstrap phase for this Drupal process.
drupal_get_filename Returns and optionally sets the filename for a system resource.
drupal_get_hash_salt Gets a salt useful for hardening against SQL injection.
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_title Gets the title of the current page.
drupal_get_user_timezone Returns the time zone of the current user.
drupal_handle_request Handles an entire PHP request.
drupal_installation_attempted Returns TRUE if a Drupal installation is currently being attempted.
drupal_is_cli Detects whether the current script is running in a command-line environment.
drupal_language_initialize Initializes all the defined language types and sets the default langcode.
drupal_load Includes a file with the provided type and name.
drupal_maintenance_theme Enables use of the theme system without requiring database access.
drupal_override_server_variables Sets appropriate server variables needed for command line scripts to work.
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_settings_initialize Sets the base URL, cookie domain, and session name from configuration.
drupal_set_message Sets a message to display to the user.
drupal_set_title Sets the title of the current page.
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_http_host Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
drupal_valid_test_ua Returns the test prefix if this is an internal request from SimpleTest.
find_conf_path Finds the appropriate configuration directory for a given host and path.
format_string Formats a string for HTML display by replacing variable placeholders.
get_t Returns the name of the proper localization function.
language Deprecated Returns the language object for a given language type.
language_default Returns the default language used on the site.
language_default_locked_languages Returns a list of the default locked languages.
language_is_locked Checks if a language is locked.
language_list Returns a list of languages set up on the site.
language_load Loads a language object from the database.
language_multilingual Returns TRUE if there is more than one language enabled.
language_name Produced the printed name for a language for display.
language_types_get_all Returns an array of the available language types.
language_types_get_default Returns a list of the built-in language types.
lock Deprecated Get locking layer instance.
module_exists Deprecated Determines whether a given module exists.
module_hook Deprecated Determines whether a module implements a hook.
module_implements Deprecated Determines which modules are implementing a hook.
module_invoke Deprecated Invokes a hook in a particular module.
module_invoke_all Deprecated Invokes a hook in all enabled modules that implement it.
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.
settings Returns a setting.
t Translates a string to the current language or to a given language.
timer_read Deprecated
timer_start Deprecated
timer_stop Deprecated
variable_del Unsets a persistent variable.
variable_get Returns a persistent variable.
variable_initialize Loads the persistent variable table.
variable_set Sets a persistent variable.
watchdog 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_bootstrap_configuration Sets up the script environment and loads settings.php.
_drupal_bootstrap_database Initializes the database system by loading database.inc.
_drupal_bootstrap_kernel Initialize the kernel / service container.
_drupal_bootstrap_page_cache Attempts to serve a page from the cache.
_drupal_bootstrap_variables Loads system variables and all enabled bootstrap modules.
_drupal_error_handler Provides custom PHP error handling.
_drupal_exception_handler Provides custom PHP exception handling.
_drupal_initialize_db_test_prefix In a test environment, get the test db prefix and set it in $databases.
_drupal_load_test_overrides Overrides low-level and environment-specific configuration.
_drupal_set_preferred_header_name Deprecated Sets the preferred name for the HTTP header.
_drupal_shutdown_function Executes registered shutdown functions.
_drupal_simpletest_conf_path Determines whether to use an overridden value for conf_path().
_language_resolved_path Stores or retrieves the path derived during language negotiation.

Constants

Namesort descending Description
CHECK_PLAIN Flag for drupal_set_title(); text is not sanitized, so run check_plain().
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 Eighth bootstrap phase: load code for subsystems and modules.
DRUPAL_BOOTSTRAP_CONFIGURATION First bootstrap phase: initialize configuration.
DRUPAL_BOOTSTRAP_DATABASE Fourth bootstrap phase: initialize database layer.
DRUPAL_BOOTSTRAP_FULL Final bootstrap phase: initialize language, path, theme, and modules.
DRUPAL_BOOTSTRAP_KERNEL Second bootstrap phase, initalize a kernel.
DRUPAL_BOOTSTRAP_PAGE_CACHE Third bootstrap phase: try to serve a cached page.
DRUPAL_BOOTSTRAP_SESSION Sixth bootstrap phase: initialize session handling.
DRUPAL_BOOTSTRAP_VARIABLES Fifth bootstrap phase: initialize the variable system.
DRUPAL_CORE_COMPATIBILITY Core API compatibility.
DRUPAL_KILOBYTE The number of bytes in a kilobyte.
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.
PASS_THROUGH Flag for drupal_set_title(); text has already been sanitized.
REQUEST_TIME Time of the current request in seconds elapsed since the Unix Epoch.
VERSION The current system version.
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.