bootstrap.inc

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

Functions that need to be loaded on every Drupal request.

Functions & methods

NameDescription
argReturns a component of the current Drupal path.
bootstrap_hooksDefines the critical hooks that force modules to always be loaded.
bootstrap_invoke_allInvokes a bootstrap hook in all bootstrap modules that implement it.
check_plainEncodes special characters in a plain-text string for display as HTML.
conf_pathFinds the appropriate configuration directory.
drupal_add_http_headerSets an HTTP response header for the current page.
drupal_anonymous_userGenerates a default anonymous $user object.
drupal_array_merge_deepMerges multiple arrays, recursively, and returns the merged array.
drupal_array_merge_deep_arrayMerges multiple arrays, recursively, and returns the merged array.
drupal_autoload_classConfirms that a class is available.
drupal_autoload_interfaceConfirms that an interface is available.
drupal_block_deniedHandles denied users.
drupal_bootstrapEnsures Drupal is bootstrapped to the specified phase.
drupal_check_memory_limitCompares the memory required for an operation to the available memory.
drupal_classloaderInitializes and returns the class loader.
drupal_classloader_registerRegisters an additional namespace.
drupal_containerRetrieves the Drupal Container to standardize object construction.
drupal_environment_initializeInitializes the PHP environment.
drupal_fast_404Returns a simple 404 Not Found page.
drupal_generate_test_uaGenerates a user agent string with a HMAC and timestamp for simpletest.
drupal_get_bootstrap_phaseReturns the current bootstrap phase for this Drupal process.
drupal_get_filenameReturns and optionally sets the filename for a system resource.
drupal_get_http_headerGets the HTTP response headers for the current page.
drupal_get_messagesReturns all messages that have been set.
drupal_get_titleGets the title of the current page.
drupal_get_user_timezoneReturns the time zone of the current user.
drupal_hash_base64Calculates a base-64 encoded, URL-safe sha-256 hash.
drupal_hmac_base64Calculates a base-64 encoded, URL-safe sha-256 hmac.
drupal_installation_attemptedReturns TRUE if a Drupal installation is currently being attempted.
drupal_is_cliDetects whether the current script is running in a command-line environment.
drupal_is_deniedChecks to see if an IP address has been blocked.
drupal_language_initializeInitializes all the defined language types.
drupal_loadIncludes a file with the provided type and name.
drupal_maintenance_themeEnables use of the theme system without requiring database access.
drupal_override_server_variablesSets appropriate server variables needed for command line scripts to work.
drupal_page_get_cacheRetrieves the current page from the cache.
drupal_page_headerSets HTTP headers in preparation for a page response.
drupal_page_is_cacheableDetermines the cacheability of the current page.
drupal_placeholderFormats text for emphasized display in a placeholder inside a sentence.
drupal_random_bytesReturns a string of highly randomized bytes (over the full 8-bit range).
drupal_register_shutdown_functionRegisters a function for execution on shutdown.
drupal_send_headersSends the HTTP response headers that were previously set, adding defaults.
drupal_serve_page_from_cacheSets HTTP headers in preparation for a cached page response.
drupal_settings_initializeSets the base URL, cookie domain, and session name from configuration.
drupal_set_messageSets a message which reflects the status of the performed operation.
drupal_set_titleSets the title of the current page.
drupal_staticProvides central static variable storage.
drupal_static_resetResets one or all centrally stored static variable(s).
drupal_unpackUnserializes and appends elements from a serialized string.
drupal_validate_utf8Checks whether a string is valid UTF-8.
drupal_valid_http_hostValidates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
drupal_valid_test_uaReturns the test prefix if this is an internal request from SimpleTest.
find_conf_pathFinds the appropriate configuration directory for a given host and path.
format_stringReplaces placeholders with sanitized values in a string.
get_tReturns the name of the proper localization function.
ip_addressReturns the IP address of the client machine.
language_defaultReturns the default language used on the site.
language_listReturns a list of configured languages.
language_loadLoads a language object from the database.
language_multilingualReturns TRUE if there is more than one language enabled.
language_nameProduced the printed name for a language for display.
language_types_get_allReturns an array of the available language types.
language_types_get_defaultReturns a list of the built-in language types.
registry_rebuildRescans all enabled modules and rebuilds the registry.
registry_updateUpdates the registry based on the latest files listed in the database.
request_pathReturns the requested URL path of the page being viewed.
request_uriReturns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
tTranslates a string to the current language or to a given language.
timer_readReads the current timer value without stopping the timer.
timer_startStarts the timer with the specified name.
timer_stopStops the timer with the specified name.
variable_delUnsets a persistent variable.
variable_getReturns a persistent variable.
variable_initializeLoads the persistent variable table.
variable_setSets a persistent variable.
watchdogLogs a system message.
watchdog_exceptionLogs an exception.
_current_path@todo This is a temporary function pending refactoring Drupal to use Symfony's Request object exclusively.
_drupal_bootstrap_configurationSets up the script environment and loads settings.php.
_drupal_bootstrap_databaseInitializes the database system and registers autoload functions.
_drupal_bootstrap_page_cacheAttempts to serve a page from the cache.
_drupal_bootstrap_page_headerInvokes hook_boot(), initializes locking system, and sends HTTP headers.
_drupal_bootstrap_variablesLoads system variables and all enabled bootstrap modules.
_drupal_error_handlerProvides custom PHP error handling.
_drupal_exception_handlerProvides custom PHP exception handling.
_drupal_set_preferred_header_nameSets the preferred name for the HTTP header.
_drupal_shutdown_functionExecutes registered shutdown functions.
_registry_check_codeChecks for a resource in the registry.

Constants

NameDescription
CACHE_PERMANENTIndicates that the item should never be removed unless explicitly selected.
CACHE_TEMPORARYIndicates that the item should be removed at the next general cache wipe.
CHECK_PLAINFlag for drupal_set_title(); text is not sanitized, so run check_plain().
DRUPAL_ANONYMOUS_RIDRole ID for anonymous users; should match what's in the "role" table.
DRUPAL_AUTHENTICATED_RIDRole ID for authenticated users; should match what's in the "role" table.
DRUPAL_BOOTSTRAP_CONFIGURATIONFirst bootstrap phase: initialize configuration.
DRUPAL_BOOTSTRAP_DATABASEThird bootstrap phase: initialize database layer.
DRUPAL_BOOTSTRAP_FULLFinal bootstrap phase: Drupal is fully loaded; validate and fix input data.
DRUPAL_BOOTSTRAP_LANGUAGESeventh bootstrap phase: find out language of the page.
DRUPAL_BOOTSTRAP_PAGE_CACHESecond bootstrap phase: try to serve a cached page.
DRUPAL_BOOTSTRAP_PAGE_HEADERSixth bootstrap phase: set up the page header.
DRUPAL_BOOTSTRAP_SESSIONFifth bootstrap phase: initialize session handling.
DRUPAL_BOOTSTRAP_VARIABLESFourth bootstrap phase: initialize the variable system.
DRUPAL_CORE_COMPATIBILITYCore API compatibility.
DRUPAL_KILOBYTEThe number of bytes in a kilobyte.
DRUPAL_MINIMUM_PHPMinimum supported version of PHP.
DRUPAL_MINIMUM_PHP_MEMORY_LIMITMinimum recommended value of PHP memory_limit.
DRUPAL_PHP_FUNCTION_PATTERNRegular expression to match PHP function names.
LANGUAGE_LTRLanguage written left to right. Possible value of $language->direction.
LANGUAGE_MULTIPLEThe language code used when multiple languages could be applied.
LANGUAGE_NOT_APPLICABLEThe language code used when the marked object has no linguistic content.
LANGUAGE_NOT_SPECIFIEDThe language code used when no language is explicitly assigned (yet).
LANGUAGE_RTLLanguage written right to left. Possible value of $language->direction.
LANGUAGE_SYSTEMSpecial system language code (only applicable to UI language).
LANGUAGE_TYPE_CONTENTThe type of language used to define the content language.
LANGUAGE_TYPE_INTERFACEThe type of language used to select the user interface.
LANGUAGE_TYPE_URLThe type of language used for URLs.
PASS_THROUGHFlag for drupal_set_title(); text has already been sanitized.
REGISTRY_RESET_LOOKUP_CACHESignals that the registry lookup cache should be reset.
REGISTRY_WRITE_LOOKUP_CACHESignals that the registry lookup cache should be written to storage.
REQUEST_TIMETime of the current request in seconds elapsed since the Unix Epoch.
VERSIONThe current system version.
WATCHDOG_ALERTLog message severity -- Alert: action must be taken immediately.
WATCHDOG_CRITICALLog message severity -- Critical conditions.
WATCHDOG_DEBUGLog message severity -- Debug-level messages.
WATCHDOG_EMERGENCYLog message severity -- Emergency: system is unusable.
WATCHDOG_ERRORLog message severity -- Error conditions.
WATCHDOG_INFOLog message severity -- Informational messages.
WATCHDOG_NOTICELog message severity -- Normal but significant conditions.
WATCHDOG_WARNINGLog message severity -- Warning conditions.

File

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