Projet

Général

Profil

Paste
Télécharger (117 ko) Statistiques
| Branche: | Révision:

root / htmltest / includes / bootstrap.inc @ a5572547

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