1. 8.2.x core/includes/bootstrap.inc
  2. 8.0.x core/includes/bootstrap.inc
  3. 8.1.x core/includes/bootstrap.inc
  4. 8.3.x core/includes/bootstrap.inc
  5. 4.6.x includes/bootstrap.inc
  6. 4.7.x includes/bootstrap.inc
  7. 5.x includes/bootstrap.inc
  8. 6.x includes/bootstrap.inc
  9. 7.x includes/bootstrap.inc

Functions that need to be loaded on every Drupal request.

File

includes/bootstrap.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions that need to be loaded on every Drupal request.
  5. */
  6. /**
  7. * Indicates that the item should never be removed unless explicitly told to
  8. * using cache_clear_all() with a cache ID.
  9. */
  10. define('CACHE_PERMANENT', 0);
  11. /**
  12. * Indicates that the item should be removed at the next general cache wipe.
  13. */
  14. define('CACHE_TEMPORARY', -1);
  15. /**
  16. * Indicates that page caching is disabled.
  17. */
  18. define('CACHE_DISABLED', 0);
  19. /**
  20. * Indicates that page caching is enabled, using "normal" mode.
  21. */
  22. define('CACHE_NORMAL', 1);
  23. /**
  24. * Indicates that page caching is using "aggressive" mode. This bypasses
  25. * loading any modules for additional speed, which may break functionality in
  26. * modules that expect to be run on each page load.
  27. */
  28. define('CACHE_AGGRESSIVE', 2);
  29. /**
  30. * Indicates a notice-level watchdog event; these are normally notifications
  31. * of normal system events that have occurred and can usually be safely ignored.
  32. */
  33. define('WATCHDOG_NOTICE', 0);
  34. /**
  35. * Indicates a warning-level watchdog event; this can be triggered by an error
  36. * in a module that does not impact the overall functionality of the site.
  37. */
  38. define('WATCHDOG_WARNING', 1);
  39. /**
  40. * Indicates an error-level watchdog event; could be indicative of an attempt
  41. * to compromise the security of the site, or a serious system error.
  42. */
  43. define('WATCHDOG_ERROR', 2);
  44. /**
  45. * First bootstrap phase: initialize configuration.
  46. */
  47. define('DRUPAL_BOOTSTRAP_CONFIGURATION', 0);
  48. /**
  49. * Second bootstrap phase: try to call a non-database cache
  50. * fetch routine.
  51. */
  52. define('DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE', 1);
  53. /**
  54. * Third bootstrap phase: initialize database layer.
  55. */
  56. define('DRUPAL_BOOTSTRAP_DATABASE', 2);
  57. /**
  58. * Fourth bootstrap phase: identify and reject banned hosts.
  59. */
  60. define('DRUPAL_BOOTSTRAP_ACCESS', 3);
  61. /**
  62. * Fifth bootstrap phase: initialize session handling.
  63. */
  64. define('DRUPAL_BOOTSTRAP_SESSION', 4);
  65. /**
  66. * Sixth bootstrap phase: load bootstrap.inc and module.inc, start
  67. * the variable system and try to serve a page from the cache.
  68. */
  69. define('DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE', 5);
  70. /**
  71. * Seventh bootstrap phase: set $_GET['q'] to Drupal path of request.
  72. */
  73. define('DRUPAL_BOOTSTRAP_PATH', 6);
  74. /**
  75. * Final bootstrap phase: Drupal is fully loaded; validate and fix
  76. * input data.
  77. */
  78. define('DRUPAL_BOOTSTRAP_FULL', 7);
  79. /**
  80. * Role ID for anonymous users; should match what's in the "role" table.
  81. */
  82. define('DRUPAL_ANONYMOUS_RID', 1);
  83. /**
  84. * Role ID for authenticated users; should match what's in the "role" table.
  85. */
  86. define('DRUPAL_AUTHENTICATED_RID', 2);
  87. /**
  88. * Start the timer with the specified name. If you start and stop
  89. * the same timer multiple times, the measured intervals will be
  90. * accumulated.
  91. *
  92. * @param name
  93. * The name of the timer.
  94. */
  95. function timer_start($name) {
  96. global $timers;
  97. list($usec, $sec) = explode(' ', microtime());
  98. $timers[$name]['start'] = (float)$usec + (float)$sec;
  99. $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
  100. }
  101. /**
  102. * Read the current timer value without stopping the timer.
  103. *
  104. * @param name
  105. * The name of the timer.
  106. * @return
  107. * The current timer value in ms.
  108. */
  109. function timer_read($name) {
  110. global $timers;
  111. if (isset($timers[$name]['start'])) {
  112. list($usec, $sec) = explode(' ', microtime());
  113. $stop = (float)$usec + (float)$sec;
  114. $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
  115. if (isset($timers[$name]['time'])) {
  116. $diff += $timers[$name]['time'];
  117. }
  118. return $diff;
  119. }
  120. }
  121. /**
  122. * Stop the timer with the specified name.
  123. *
  124. * @param name
  125. * The name of the timer.
  126. * @return
  127. * A timer array. The array contains the number of times the
  128. * timer has been started and stopped (count) and the accumulated
  129. * timer value in ms (time).
  130. */
  131. function timer_stop($name) {
  132. global $timers;
  133. $timers[$name]['time'] = timer_read($name);
  134. unset($timers[$name]['start']);
  135. return $timers[$name];
  136. }
  137. /**
  138. * Find the appropriate configuration directory.
  139. *
  140. * Try finding a matching configuration directory by stripping the website's
  141. * hostname from left to right and pathname from right to left. The first
  142. * configuration file found will be used; the remaining will ignored. If no
  143. * configuration file is found, return a default value '$confdir/default'.
  144. *
  145. * Example for a fictitious site installed at
  146. * http://www.drupal.org:8080/mysite/test/ the 'settings.php' is searched in
  147. * the following directories:
  148. *
  149. * 1. $confdir/8080.www.drupal.org.mysite.test
  150. * 2. $confdir/www.drupal.org.mysite.test
  151. * 3. $confdir/drupal.org.mysite.test
  152. * 4. $confdir/org.mysite.test
  153. *
  154. * 5. $confdir/8080.www.drupal.org.mysite
  155. * 6. $confdir/www.drupal.org.mysite
  156. * 7. $confdir/drupal.org.mysite
  157. * 8. $confdir/org.mysite
  158. *
  159. * 9. $confdir/8080.www.drupal.org
  160. * 10. $confdir/www.drupal.org
  161. * 11. $confdir/drupal.org
  162. * 12. $confdir/org
  163. *
  164. * 13. $confdir/default
  165. */
  166. function conf_path() {
  167. static $conf = '';
  168. if ($conf) {
  169. return $conf;
  170. }
  171. $confdir = 'sites';
  172. $uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
  173. $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
  174. for ($i = count($uri) - 1; $i > 0; $i--) {
  175. for ($j = count($server); $j > 0; $j--) {
  176. $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
  177. if (file_exists("$confdir/$dir/settings.php")) {
  178. $conf = "$confdir/$dir";
  179. return $conf;
  180. }
  181. }
  182. }
  183. $conf = "$confdir/default";
  184. return $conf;
  185. }
  186. /**
  187. * Unsets all disallowed global variables. See $allowed for what's allowed.
  188. */
  189. function drupal_unset_globals() {
  190. if (ini_get('register_globals')) {
  191. $allowed = array('_ENV' => 1, '_GET' => 1, '_POST' => 1, '_COOKIE' => 1, '_FILES' => 1, '_SERVER' => 1, '_REQUEST' => 1, 'access_check' => 1, 'GLOBALS' => 1);
  192. foreach ($GLOBALS as $key => $value) {
  193. if (!isset($allowed[$key])) {
  194. unset($GLOBALS[$key]);
  195. }
  196. }
  197. }
  198. }
  199. /**
  200. * Validate that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
  201. *
  202. * As $_SERVER['HTTP_HOST'] is user input, ensure it only contains characters
  203. * allowed in hostnames. See RFC 952 (and RFC 2181). $_SERVER['HTTP_HOST'] is
  204. * lowercased.
  205. *
  206. * @return
  207. * TRUE if only containing valid characters, or FALSE otherwise.
  208. */
  209. function drupal_valid_http_host($host) {
  210. return preg_match('/^\[?(?:[a-z0-9-:\]_]+\.?)+$/', $host);
  211. }
  212. /**
  213. * Loads the configuration and sets the base URL, cookie domain, and
  214. * session name correctly.
  215. */
  216. function conf_init() {
  217. global $base_url, $base_path, $base_root;
  218. // Export the following settings.php variables to the global namespace
  219. global $db_url, $db_prefix, $cookie_domain, $conf, $installed_profile;
  220. $conf = array();
  221. if (isset($_SERVER['HTTP_HOST'])) {
  222. // As HTTP_HOST is user input, ensure it only contains characters allowed
  223. // in hostnames. See RFC 952 (and RFC 2181).
  224. // $_SERVER['HTTP_HOST'] is lowercased here per specifications.
  225. $_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
  226. if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
  227. // HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
  228. header('HTTP/1.1 400 Bad Request');
  229. exit;
  230. }
  231. }
  232. else {
  233. // Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
  234. // defined for E_ALL compliance.
  235. $_SERVER['HTTP_HOST'] = '';
  236. }
  237. include_once './'. conf_path() .'/settings.php';
  238. if (isset($base_url)) {
  239. // Parse fixed base URL from settings.php.
  240. $parts = parse_url($base_url);
  241. if (!isset($parts['path'])) {
  242. $parts['path'] = '';
  243. }
  244. $base_path = $parts['path'] . '/';
  245. // Build $base_root (everything until first slash after "scheme://").
  246. $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
  247. }
  248. else {
  249. // Create base URL
  250. $base_root = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
  251. $base_url = $base_root .= '://'. $_SERVER['HTTP_HOST'];
  252. // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
  253. // be modified by a visitor.
  254. if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
  255. $base_path = "/$dir";
  256. $base_url .= $base_path;
  257. $base_path .= '/';
  258. }
  259. else {
  260. $base_path = '/';
  261. }
  262. }
  263. if (!$cookie_domain) {
  264. // If the $cookie_domain is empty, try to use the session.cookie_domain.
  265. $cookie_domain = ini_get('session.cookie_domain');
  266. }
  267. if ($cookie_domain) {
  268. // If the user specifies the cookie domain, also use it for session name.
  269. $session_name = $cookie_domain;
  270. }
  271. else {
  272. // Otherwise use $base_url as session name, without the protocol
  273. // to use the same session identifiers across http and https.
  274. list( , $session_name) = explode('://', $base_url, 2);
  275. // We try to set the cookie domain to the hostname.
  276. // We escape the hostname because it can be modified by a visitor.
  277. if (!empty($_SERVER['HTTP_HOST'])) {
  278. $cookie_domain = check_plain($_SERVER['HTTP_HOST']);
  279. }
  280. }
  281. // To prevent session cookies from being hijacked, a user can configure the
  282. // SSL version of their website to only transfer session cookies via SSL by
  283. // using PHP's session.cookie_secure setting. The browser will then use two
  284. // separate session cookies for the HTTPS and HTTP versions of the site. So we
  285. // must use different session identifiers for HTTPS and HTTP to prevent a
  286. // cookie collision.
  287. if (ini_get('session.cookie_secure')) {
  288. $session_name .= 'SSL';
  289. }
  290. // Strip leading periods, www., and port numbers from cookie domain.
  291. $cookie_domain = ltrim($cookie_domain, '.');
  292. if (strpos($cookie_domain, 'www.') === 0) {
  293. $cookie_domain = substr($cookie_domain, 4);
  294. }
  295. $cookie_domain = explode(':', $cookie_domain);
  296. $cookie_domain = '.'. $cookie_domain[0];
  297. // Per RFC 2109, cookie domains must contain at least one dot other than the
  298. // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
  299. if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
  300. ini_set('session.cookie_domain', $cookie_domain);
  301. }
  302. session_name('SESS'. md5($session_name));
  303. }
  304. /**
  305. * Returns and optionally sets the filename for a system item (module,
  306. * theme, etc.). The filename, whether provided, cached, or retrieved
  307. * from the database, is only returned if the file exists.
  308. *
  309. * This function plays a key role in allowing Drupal's resources (modules
  310. * and themes) to be located in different places depending on a site's
  311. * configuration. For example, a module 'foo' may legally be be located
  312. * in any of these three places:
  313. *
  314. * modules/foo/foo.module
  315. * sites/all/modules/foo/foo.module
  316. * sites/example.com/modules/foo/foo.module
  317. *
  318. * Calling drupal_get_filename('module', 'foo') will give you one of
  319. * the above, depending on where the module is located.
  320. *
  321. * @param $type
  322. * The type of the item (i.e. theme, theme_engine, module).
  323. * @param $name
  324. * The name of the item for which the filename is requested.
  325. * @param $filename
  326. * The filename of the item if it is to be set explicitly rather
  327. * than by consulting the database.
  328. *
  329. * @return
  330. * The filename of the requested item.
  331. */
  332. function drupal_get_filename($type, $name, $filename = NULL) {
  333. static $files = array();
  334. global $active_db;
  335. if (!isset($files[$type])) {
  336. $files[$type] = array();
  337. }
  338. if (!empty($filename) && file_exists($filename)) {
  339. $files[$type][$name] = $filename;
  340. }
  341. elseif (isset($files[$type][$name])) {
  342. // nothing
  343. }
  344. // Verify that we have an active database connection, before querying
  345. // the database. This is required because this function is called both
  346. // before we have a database connection (i.e. during installation) and
  347. // when a database connection fails.
  348. elseif ($active_db && (($file = db_result(db_query("SELECT filename FROM {system} WHERE name = '%s' AND type = '%s'", $name, $type))) && file_exists($file))) {
  349. $files[$type][$name] = $file;
  350. }
  351. else {
  352. // Fallback to searching the filesystem if the database connection is
  353. // not established or the requested file is not found.
  354. $config = conf_path();
  355. $dir = (($type == 'theme_engine') ? 'themes/engines' : "${type}s");
  356. $file = (($type == 'theme_engine') ? "$name.engine" : "$name.$type");
  357. foreach (array("$config/$dir/$file", "$config/$dir/$name/$file", "$dir/$file", "$dir/$name/$file") as $file) {
  358. if (file_exists($file)) {
  359. $files[$type][$name] = $file;
  360. break;
  361. }
  362. }
  363. }
  364. return $files[$type][$name];
  365. }
  366. /**
  367. * Load the persistent variable table.
  368. *
  369. * The variable table is composed of values that have been saved in the table
  370. * with variable_set() as well as those explicitly specified in the configuration
  371. * file.
  372. */
  373. function variable_init($conf = array()) {
  374. // NOTE: caching the variables improves performance by 20% when serving cached pages.
  375. if ($cached = cache_get('variables', 'cache')) {
  376. $variables = unserialize($cached->data);
  377. }
  378. else {
  379. $result = db_query('SELECT * FROM {variable}');
  380. while ($variable = db_fetch_object($result)) {
  381. $variables[$variable->name] = unserialize($variable->value);
  382. }
  383. cache_set('variables', 'cache', serialize($variables));
  384. }
  385. foreach ($conf as $name => $value) {
  386. $variables[$name] = $value;
  387. }
  388. return $variables;
  389. }
  390. /**
  391. * Return a persistent variable.
  392. *
  393. * @param $name
  394. * The name of the variable to return.
  395. * @param $default
  396. * The default value to use if this variable has never been set.
  397. * @return
  398. * The value of the variable.
  399. */
  400. function variable_get($name, $default) {
  401. global $conf;
  402. return isset($conf[$name]) ? $conf[$name] : $default;
  403. }
  404. /**
  405. * Set a persistent variable.
  406. *
  407. * @param $name
  408. * The name of the variable to set.
  409. * @param $value
  410. * The value to set. This can be any PHP data type; these functions take care
  411. * of serialization as necessary.
  412. */
  413. function variable_set($name, $value) {
  414. global $conf;
  415. db_lock_table('variable');
  416. db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
  417. db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, serialize($value));
  418. db_unlock_tables();
  419. cache_clear_all('variables', 'cache');
  420. $conf[$name] = $value;
  421. }
  422. /**
  423. * Unset a persistent variable.
  424. *
  425. * @param $name
  426. * The name of the variable to undefine.
  427. */
  428. function variable_del($name) {
  429. global $conf;
  430. db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
  431. cache_clear_all('variables', 'cache');
  432. unset($conf[$name]);
  433. }
  434. /**
  435. * Retrieve the current page from the cache.
  436. *
  437. * Note: we do not serve cached pages when status messages are waiting (from
  438. * a redirected form submission which was completed).
  439. */
  440. function page_get_cache() {
  441. global $user, $base_root;
  442. $cache = NULL;
  443. if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && count(drupal_set_message()) == 0) {
  444. $cache = cache_get($base_root . request_uri(), 'cache_page');
  445. if (empty($cache)) {
  446. ob_start();
  447. }
  448. }
  449. return $cache;
  450. }
  451. /**
  452. * Call all init or exit hooks without including all modules.
  453. *
  454. * @param $hook
  455. * The name of the bootstrap hook we wish to invoke.
  456. */
  457. function bootstrap_invoke_all($hook) {
  458. foreach (module_list(TRUE, TRUE) as $module) {
  459. drupal_load('module', $module);
  460. module_invoke($module, $hook);
  461. }
  462. }
  463. /**
  464. * Includes a file with the provided type and name. This prevents
  465. * including a theme, engine, module, etc., more than once.
  466. *
  467. * @param $type
  468. * The type of item to load (i.e. theme, theme_engine, module).
  469. * @param $name
  470. * The name of the item to load.
  471. *
  472. * @return
  473. * TRUE if the item is loaded or has already been loaded.
  474. */
  475. function drupal_load($type, $name) {
  476. static $files = array();
  477. if (isset($files[$type][$name])) {
  478. return TRUE;
  479. }
  480. $filename = drupal_get_filename($type, $name);
  481. if ($filename) {
  482. include_once "./$filename";
  483. $files[$type][$name] = TRUE;
  484. return TRUE;
  485. }
  486. return FALSE;
  487. }
  488. /**
  489. * Set HTTP headers in preparation for a page response.
  490. *
  491. * Authenticated users are always given a 'no-cache' header, and will
  492. * fetch a fresh page on every request. This prevents authenticated
  493. * users seeing locally cached pages that show them as logged out.
  494. *
  495. * @see page_set_cache
  496. */
  497. function drupal_page_header() {
  498. header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
  499. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  500. header("Cache-Control: store, no-cache, must-revalidate");
  501. header("Cache-Control: post-check=0, pre-check=0", FALSE);
  502. }
  503. /**
  504. * Set HTTP headers in preparation for a cached page response.
  505. *
  506. * The general approach here is that anonymous users can keep a local
  507. * cache of the page, but must revalidate it on every request. Then,
  508. * they are given a '304 Not Modified' response as long as they stay
  509. * logged out and the page has not been modified.
  510. *
  511. */
  512. function drupal_page_cache_header($cache) {
  513. // Set default values:
  514. $last_modified = gmdate('D, d M Y H:i:s', $cache->created) .' GMT';
  515. $etag = '"'.md5($last_modified).'"';
  516. // See if the client has provided the required HTTP headers:
  517. $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
  518. $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
  519. if ($if_modified_since && $if_none_match
  520. && $if_none_match == $etag // etag must match
  521. && $if_modified_since == $last_modified) { // if-modified-since must match
  522. header('HTTP/1.1 304 Not Modified');
  523. // All 304 responses must send an etag if the 200 response for the same object contained an etag
  524. header("Etag: $etag");
  525. return;
  526. }
  527. // Send appropriate response:
  528. header("Last-Modified: $last_modified");
  529. header("ETag: $etag");
  530. // The following headers force validation of cache:
  531. header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
  532. header("Cache-Control: must-revalidate");
  533. // Determine if the browser accepts gzipped data.
  534. if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === FALSE && function_exists('gzencode')) {
  535. // Strip the gzip header and run uncompress.
  536. $cache->data = gzinflate(substr(substr($cache->data, 10), 0, -8));
  537. }
  538. elseif (function_exists('gzencode')) {
  539. header('Content-Encoding: gzip');
  540. }
  541. // Send the original request's headers. We send them one after
  542. // another so PHP's header() function can deal with duplicate
  543. // headers.
  544. $headers = explode("\n", $cache->headers);
  545. foreach ($headers as $header) {
  546. header($header);
  547. }
  548. print $cache->data;
  549. }
  550. /**
  551. * Define the critical hooks that force modules to always be loaded.
  552. */
  553. function bootstrap_hooks() {
  554. return array('init', 'exit');
  555. }
  556. /**
  557. * Unserializes and appends elements from a serialized string.
  558. *
  559. * @param $obj
  560. * The object to which the elements are appended.
  561. * @param $field
  562. * The attribute of $obj whose value should be unserialized.
  563. */
  564. function drupal_unpack($obj, $field = 'data') {
  565. if ($obj->$field && $data = unserialize($obj->$field)) {
  566. foreach ($data as $key => $value) {
  567. if (!isset($obj->$key)) {
  568. $obj->$key = $value;
  569. }
  570. }
  571. }
  572. return $obj;
  573. }
  574. /**
  575. * Return the URI of the referring page.
  576. */
  577. function referer_uri() {
  578. if (isset($_SERVER['HTTP_REFERER'])) {
  579. return $_SERVER['HTTP_REFERER'];
  580. }
  581. }
  582. /**
  583. * Encode special characters in a plain-text string for display as HTML.
  584. *
  585. * Uses drupal_validate_utf8 to prevent cross site scripting attacks on
  586. * Internet Explorer 6.
  587. */
  588. function check_plain($text) {
  589. return drupal_validate_utf8($text) ? htmlspecialchars($text, ENT_QUOTES) : '';
  590. }
  591. /**
  592. * Checks whether a string is valid UTF-8.
  593. *
  594. * All functions designed to filter input should use drupal_validate_utf8
  595. * to ensure they operate on valid UTF-8 strings to prevent bypass of the
  596. * filter.
  597. *
  598. * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
  599. * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
  600. * bytes. When these subsequent bytes are HTML control characters such as
  601. * quotes or angle brackets, parts of the text that were deemed safe by filters
  602. * end up in locations that are potentially unsafe; An onerror attribute that
  603. * is outside of a tag, and thus deemed safe by a filter, can be interpreted
  604. * by the browser as if it were inside the tag.
  605. *
  606. * This function exploits preg_match behaviour (since PHP 4.3.5) when used
  607. * with the u modifier, as a fast way to find invalid UTF-8. When the matched
  608. * string contains an invalid byte sequence, it will fail silently.
  609. *
  610. * preg_match may not fail on 4 and 5 octet sequences, even though they
  611. * are not supported by the specification.
  612. *
  613. * The specific preg_match behaviour is present since PHP 4.3.5.
  614. *
  615. * @param $text
  616. * The text to check.
  617. * @return
  618. * TRUE if the text is valid UTF-8, FALSE if not.
  619. */
  620. function drupal_validate_utf8($text) {
  621. if (strlen($text) == 0) {
  622. return TRUE;
  623. }
  624. return (preg_match('/^./us', $text) == 1);
  625. }
  626. /**
  627. * Since $_SERVER['REQUEST_URI'] is only available on Apache, we
  628. * generate an equivalent using other environment variables.
  629. */
  630. function request_uri() {
  631. if (isset($_SERVER['REQUEST_URI'])) {
  632. $uri = $_SERVER['REQUEST_URI'];
  633. }
  634. else {
  635. if (isset($_SERVER['argv'])) {
  636. $uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['argv'][0];
  637. }
  638. else {
  639. $uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
  640. }
  641. }
  642. // Prevent multiple slashes to avoid cross site requests via the FAPI.
  643. $uri = '/'. ltrim($uri, '/');
  644. return $uri;
  645. }
  646. /**
  647. * Log a system message.
  648. *
  649. * @param $type
  650. * The category to which this message belongs.
  651. * @param $message
  652. * The message to store in the log.
  653. * @param $severity
  654. * The severity of the message. One of the following values:
  655. * - WATCHDOG_NOTICE
  656. * - WATCHDOG_WARNING
  657. * - WATCHDOG_ERROR
  658. * @param $link
  659. * A link to associate with the message.
  660. */
  661. function watchdog($type, $message, $severity = WATCHDOG_NOTICE, $link = NULL) {
  662. global $user, $base_root;
  663. $current_db = db_set_active();
  664. // Note: log the exact, entire absolute URL.
  665. $request_uri = $base_root . request_uri();
  666. db_query("INSERT INTO {watchdog} (uid, type, message, severity, link, location, referer, hostname, timestamp) VALUES (%d, '%s', '%s', %d, '%s', '%s', '%s', '%s', %d)", $user->uid, $type, $message, $severity, $link, $request_uri, referer_uri(), $_SERVER['REMOTE_ADDR'], time());
  667. if ($current_db) {
  668. db_set_active($current_db);
  669. }
  670. }
  671. /**
  672. * Set a message which reflects the status of the performed operation.
  673. *
  674. * If the function is called with no arguments, this function returns all set
  675. * messages without clearing them.
  676. *
  677. * @param $message
  678. * The message should begin with a capital letter and always ends with a
  679. * period '.'.
  680. * @param $type
  681. * The type of the message. One of the following values are possible:
  682. * - 'status'
  683. * - 'error'
  684. */
  685. function drupal_set_message($message = NULL, $type = 'status') {
  686. if ($message) {
  687. if (!isset($_SESSION['messages'])) {
  688. $_SESSION['messages'] = array();
  689. }
  690. if (!isset($_SESSION['messages'][$type])) {
  691. $_SESSION['messages'][$type] = array();
  692. }
  693. $_SESSION['messages'][$type][] = $message;
  694. }
  695. // messages not set when DB connection fails
  696. return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
  697. }
  698. /**
  699. * Return all messages that have been set.
  700. *
  701. * @param $type
  702. * (optional) Only return messages of this type.
  703. * @param $clear_queue
  704. * (optional) Set to FALSE if you do not want to clear the messages queue
  705. * @return
  706. * An associative array, the key is the message type, the value an array
  707. * of messages. If the $type parameter is passed, you get only that type,
  708. * or an empty array if there are no such messages. If $type is not passed,
  709. * all message types are returned, or an empty array if none exist.
  710. */
  711. function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
  712. if ($messages = drupal_set_message()) {
  713. if ($type) {
  714. if ($clear_queue) {
  715. unset($_SESSION['messages'][$type]);
  716. }
  717. if (isset($messages[$type])) {
  718. return array($type => $messages[$type]);
  719. }
  720. }
  721. else {
  722. if ($clear_queue) {
  723. unset($_SESSION['messages']);
  724. }
  725. return $messages;
  726. }
  727. }
  728. return array();
  729. }
  730. /**
  731. * Perform an access check for a given mask and rule type. Rules are usually
  732. * created via admin/user/rules page.
  733. *
  734. * If any allow rule matches, access is allowed. Otherwise, if any deny rule
  735. * matches, access is denied. If no rule matches, access is allowed.
  736. *
  737. * @param $type string
  738. * Type of access to check: Allowed values are:
  739. * - 'host': host name or IP address
  740. * - 'mail': e-mail address
  741. * - 'user': username
  742. * @param $mask string
  743. * String or mask to test: '_' matches any character, '%' matches any
  744. * number of characters.
  745. * @return bool
  746. * TRUE if access is denied, FALSE if access is allowed.
  747. */
  748. function drupal_is_denied($type, $mask) {
  749. // Because this function is called for every page request, both cached
  750. // and non-cached pages, we tried to optimize it as much as possible.
  751. // We deny access if the only matching records in the {access} table have
  752. // status 0. If any have status 1, or if there are no matching records,
  753. // we allow access. So, select matching records in decreasing order of
  754. // 'status', returning NOT(status) for the first. If any have status 1,
  755. // they come first, and we return NOT(status) = 0 (allowed). Otherwise,
  756. // if we have some with status 0, we return 1 (denied). If no matching
  757. // records, we get no return from db_result, so we return (bool)NULL = 0
  758. // (allowed).
  759. // The use of ORDER BY / LIMIT is more efficient than "MAX(status) = 0"
  760. // in PostgreSQL <= 8.0.
  761. return (bool) db_result(db_query_range("SELECT CASE WHEN status=1 THEN 0 ELSE 1 END FROM {access} WHERE type = '%s' AND LOWER('%s') LIKE LOWER(mask) ORDER BY status DESC", $type, $mask, 0, 1));
  762. }
  763. /**
  764. * Generates a default anonymous $user object.
  765. *
  766. * @return Object - the user object.
  767. */
  768. function drupal_anonymous_user($session = '') {
  769. $user = new stdClass();
  770. $user->uid = 0;
  771. $user->hostname = $_SERVER['REMOTE_ADDR'];
  772. $user->roles = array();
  773. $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
  774. $user->session = $session;
  775. $user->cache = 0;
  776. return $user;
  777. }
  778. /**
  779. * A string describing a phase of Drupal to load. Each phase adds to the
  780. * previous one, so invoking a later phase automatically runs the earlier
  781. * phases too. The most important usage is that if you want to access the
  782. * Drupal database from a script without loading anything else, you can
  783. * include bootstrap.inc, and call drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE).
  784. *
  785. * @param $phase
  786. * A constant. Allowed values are:
  787. * DRUPAL_BOOTSTRAP_CONFIGURATION: initialize configuration.
  788. * DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE: try to call a non-database cache fetch routine.
  789. * DRUPAL_BOOTSTRAP_DATABASE: initialize database layer.
  790. * DRUPAL_BOOTSTRAP_ACCESS: identify and reject banned hosts.
  791. * DRUPAL_BOOTSTRAP_SESSION: initialize session handling.
  792. * DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE: load bootstrap.inc and module.inc, start
  793. * the variable system and try to serve a page from the cache.
  794. * DRUPAL_BOOTSTRAP_PATH: set $_GET['q'] to Drupal path of request.
  795. * DRUPAL_BOOTSTRAP_FULL: Drupal is fully loaded, validate and fix input data.
  796. */
  797. function drupal_bootstrap($phase) {
  798. static $phases = array(DRUPAL_BOOTSTRAP_CONFIGURATION, DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE, DRUPAL_BOOTSTRAP_DATABASE, DRUPAL_BOOTSTRAP_ACCESS, DRUPAL_BOOTSTRAP_SESSION, DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE, DRUPAL_BOOTSTRAP_PATH, DRUPAL_BOOTSTRAP_FULL);
  799. while (!empty($phases) && $phase >= $phases[0]) {
  800. $current_phase = array_shift($phases);
  801. _drupal_bootstrap($current_phase);
  802. }
  803. }
  804. function _drupal_bootstrap($phase) {
  805. global $conf;
  806. switch ($phase) {
  807. case DRUPAL_BOOTSTRAP_CONFIGURATION:
  808. drupal_unset_globals();
  809. // Initialize the configuration
  810. conf_init();
  811. break;
  812. case DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE:
  813. _drupal_cache_init($phase);
  814. break;
  815. case DRUPAL_BOOTSTRAP_DATABASE:
  816. // Initialize the default database.
  817. require_once './includes/database.inc';
  818. db_set_active();
  819. break;
  820. case DRUPAL_BOOTSTRAP_ACCESS:
  821. // Deny access to hosts which were banned - t() is not yet available.
  822. if (drupal_is_denied('host', $_SERVER['REMOTE_ADDR'])) {
  823. header('HTTP/1.1 403 Forbidden');
  824. print 'Sorry, '. $_SERVER['REMOTE_ADDR']. ' has been banned.';
  825. exit();
  826. }
  827. break;
  828. case DRUPAL_BOOTSTRAP_SESSION:
  829. require_once variable_get('session_inc', './includes/session.inc');
  830. session_set_save_handler('sess_open', 'sess_close', 'sess_read', 'sess_write', 'sess_destroy_sid', 'sess_gc');
  831. session_start();
  832. break;
  833. case DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE:
  834. // Initialize configuration variables, using values from settings.php if available.
  835. $conf = variable_init(isset($conf) ? $conf : array());
  836. _drupal_cache_init($phase);
  837. // Start a page timer:
  838. timer_start('page');
  839. drupal_page_header();
  840. break;
  841. case DRUPAL_BOOTSTRAP_PATH:
  842. require_once './includes/path.inc';
  843. // Initialize $_GET['q'] prior to loading modules and invoking hook_init().
  844. drupal_init_path();
  845. break;
  846. case DRUPAL_BOOTSTRAP_FULL:
  847. require_once './includes/common.inc';
  848. _drupal_bootstrap_full();
  849. break;
  850. }
  851. }
  852. /**
  853. * Initialize the caching strategy, which loads at different stages within
  854. * Drupal's bootstrap process.
  855. */
  856. function _drupal_cache_init($phase) {
  857. require_once variable_get('cache_inc', './includes/cache.inc');
  858. if ($phase == DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE && variable_get('page_cache_fastpath', 0)) {
  859. if (page_cache_fastpath()) {
  860. exit();
  861. }
  862. }
  863. elseif ($phase == DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE) {
  864. if ($cache = page_get_cache()) {
  865. if (variable_get('cache', CACHE_DISABLED) == CACHE_AGGRESSIVE) {
  866. drupal_page_cache_header($cache);
  867. exit();
  868. }
  869. elseif (variable_get('cache', CACHE_DISABLED) == CACHE_NORMAL) {
  870. require_once './includes/module.inc';
  871. bootstrap_invoke_all('init');
  872. drupal_page_cache_header($cache);
  873. bootstrap_invoke_all('exit');
  874. exit();
  875. }
  876. }
  877. require_once './includes/module.inc';
  878. }
  879. }
  880. /**
  881. * Enables use of the theme system without requiring database access. Since
  882. * there is not database access no theme will be enabled and the default
  883. * themeable functions will be called. Some themeable functions can not be used
  884. * without the full Drupal API loaded. For example, theme_page() is
  885. * unavailable and theme_maintenance_page() must be used in its place.
  886. */
  887. function drupal_maintenance_theme() {
  888. global $theme;
  889. require_once './includes/path.inc';
  890. require_once './includes/theme.inc';
  891. require_once './includes/common.inc';
  892. require_once './includes/unicode.inc';
  893. require_once './modules/filter/filter.module';
  894. unicode_check();
  895. drupal_add_css(drupal_get_path('module', 'system') .'/defaults.css', 'module');
  896. drupal_add_css(drupal_get_path('module', 'system') .'/system.css', 'module');
  897. $theme = '';
  898. }
  899. /**
  900. * Return the name of the localisation function. Use in code that needs to
  901. * run both during installation and normal operation.
  902. */
  903. function get_t() {
  904. static $t;
  905. if (is_null($t)) {
  906. $t = function_exists('install_main') ? 'st' : 't';
  907. }
  908. return $t;
  909. }

Functions

Namesort descending Description
bootstrap_hooks Define the critical hooks that force modules to always be loaded.
bootstrap_invoke_all Call all init or exit hooks without including all modules.
check_plain Encode special characters in a plain-text string for display as HTML.
conf_init Loads the configuration and sets the base URL, cookie domain, and session name correctly.
conf_path Find the appropriate configuration directory.
drupal_anonymous_user Generates a default anonymous $user object.
drupal_bootstrap A string describing a phase of Drupal to load. Each phase adds to the previous one, so invoking a later phase automatically runs the earlier phases too. The most important usage is that if you want to access the Drupal database from a script without…
drupal_get_filename Returns and optionally sets the filename for a system item (module, theme, etc.). The filename, whether provided, cached, or retrieved from the database, is only returned if the file exists.
drupal_get_messages Return all messages that have been set.
drupal_is_denied Perform an access check for a given mask and rule type. Rules are usually created via admin/user/rules page.
drupal_load Includes a file with the provided type and name. This prevents including a theme, engine, module, etc., more than once.
drupal_maintenance_theme Enables use of the theme system without requiring database access. Since there is not database access no theme will be enabled and the default themeable functions will be called. Some themeable functions can not be used without the full Drupal API…
drupal_page_cache_header Set HTTP headers in preparation for a cached page response.
drupal_page_header Set HTTP headers in preparation for a page response.
drupal_set_message Set a message which reflects the status of the performed operation.
drupal_unpack Unserializes and appends elements from a serialized string.
drupal_unset_globals Unsets all disallowed global variables. See $allowed for what's allowed.
drupal_validate_utf8 Checks whether a string is valid UTF-8.
drupal_valid_http_host Validate that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
get_t Return the name of the localisation function. Use in code that needs to run both during installation and normal operation.
page_get_cache Retrieve the current page from the cache.
referer_uri Return the URI of the referring page.
request_uri Since $_SERVER['REQUEST_URI'] is only available on Apache, we generate an equivalent using other environment variables.
timer_read Read the current timer value without stopping the timer.
timer_start Start the timer with the specified name. If you start and stop the same timer multiple times, the measured intervals will be accumulated.
timer_stop Stop the timer with the specified name.
variable_del Unset a persistent variable.
variable_get Return a persistent variable.
variable_init Load the persistent variable table.
variable_set Set a persistent variable.
watchdog Log a system message.
_drupal_bootstrap
_drupal_cache_init Initialize the caching strategy, which loads at different stages within Drupal's bootstrap process.

Constants

Namesort descending Description
CACHE_AGGRESSIVE Indicates that page caching is using "aggressive" mode. This bypasses loading any modules for additional speed, which may break functionality in modules that expect to be run on each page load.
CACHE_DISABLED Indicates that page caching is disabled.
CACHE_NORMAL Indicates that page caching is enabled, using "normal" mode.
CACHE_PERMANENT Indicates that the item should never be removed unless explicitly told to using cache_clear_all() with a cache ID.
CACHE_TEMPORARY Indicates that the item should be removed at the next general cache wipe.
DRUPAL_ANONYMOUS_RID Role ID for anonymous users; should match what's in the "role" table.
DRUPAL_AUTHENTICATED_RID Role ID for authenticated users; should match what's in the "role" table.
DRUPAL_BOOTSTRAP_ACCESS Fourth bootstrap phase: identify and reject banned hosts.
DRUPAL_BOOTSTRAP_CONFIGURATION First bootstrap phase: initialize configuration.
DRUPAL_BOOTSTRAP_DATABASE Third bootstrap phase: initialize database layer.
DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE Second bootstrap phase: try to call a non-database cache fetch routine.
DRUPAL_BOOTSTRAP_FULL Final bootstrap phase: Drupal is fully loaded; validate and fix input data.
DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE Sixth bootstrap phase: load bootstrap.inc and module.inc, start the variable system and try to serve a page from the cache.
DRUPAL_BOOTSTRAP_PATH Seventh bootstrap phase: set $_GET['q'] to Drupal path of request.
DRUPAL_BOOTSTRAP_SESSION Fifth bootstrap phase: initialize session handling.
WATCHDOG_ERROR Indicates an error-level watchdog event; could be indicative of an attempt to compromise the security of the site, or a serious system error.
WATCHDOG_NOTICE Indicates a notice-level watchdog event; these are normally notifications of normal system events that have occurred and can usually be safely ignored.
WATCHDOG_WARNING Indicates a warning-level watchdog event; this can be triggered by an error in a module that does not impact the overall functionality of the site.