Projet

Général

Profil

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

root / drupal7 / includes / bootstrap.inc @ d20f5bc6

1
<?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
define('VERSION', '7.31');
12

    
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
  // Limit the length of the host name to 1000 bytes to prevent DoS attacks with
704
  // long host names.
705
  return strlen($host) <= 1000
706
    // Limit the number of subdomains and port separators to prevent DoS attacks
707
    // in conf_path().
708
    && substr_count($host, '.') <= 100
709
    && substr_count($host, ':') <= 100
710
    && preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host);
711
}
712

    
713
/**
714
 * Sets the base URL, cookie domain, and session name from configuration.
715
 */
716
function drupal_settings_initialize() {
717
  global $base_url, $base_path, $base_root;
718

    
719
  // Export these settings.php variables to the global namespace.
720
  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;
721
  $conf = array();
722

    
723
  if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.php')) {
724
    include_once DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
725
  }
726
  $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
727

    
728
  if (isset($base_url)) {
729
    // Parse fixed base URL from settings.php.
730
    $parts = parse_url($base_url);
731
    if (!isset($parts['path'])) {
732
      $parts['path'] = '';
733
    }
734
    $base_path = $parts['path'] . '/';
735
    // Build $base_root (everything until first slash after "scheme://").
736
    $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
737
  }
738
  else {
739
    // Create base URL.
740
    $http_protocol = $is_https ? 'https' : 'http';
741
    $base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];
742

    
743
    $base_url = $base_root;
744

    
745
    // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
746
    // be modified by a visitor.
747
    if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
748
      $base_path = $dir;
749
      $base_url .= $base_path;
750
      $base_path .= '/';
751
    }
752
    else {
753
      $base_path = '/';
754
    }
755
  }
756
  $base_secure_url = str_replace('http://', 'https://', $base_url);
757
  $base_insecure_url = str_replace('https://', 'http://', $base_url);
758

    
759
  if ($cookie_domain) {
760
    // If the user specifies the cookie domain, also use it for session name.
761
    $session_name = $cookie_domain;
762
  }
763
  else {
764
    // Otherwise use $base_url as session name, without the protocol
765
    // to use the same session identifiers across HTTP and HTTPS.
766
    list( , $session_name) = explode('://', $base_url, 2);
767
    // HTTP_HOST can be modified by a visitor, but we already sanitized it
768
    // in drupal_settings_initialize().
769
    if (!empty($_SERVER['HTTP_HOST'])) {
770
      $cookie_domain = $_SERVER['HTTP_HOST'];
771
      // Strip leading periods, www., and port numbers from cookie domain.
772
      $cookie_domain = ltrim($cookie_domain, '.');
773
      if (strpos($cookie_domain, 'www.') === 0) {
774
        $cookie_domain = substr($cookie_domain, 4);
775
      }
776
      $cookie_domain = explode(':', $cookie_domain);
777
      $cookie_domain = '.' . $cookie_domain[0];
778
    }
779
  }
780
  // Per RFC 2109, cookie domains must contain at least one dot other than the
781
  // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
782
  if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
783
    ini_set('session.cookie_domain', $cookie_domain);
784
  }
785
  // To prevent session cookies from being hijacked, a user can configure the
786
  // SSL version of their website to only transfer session cookies via SSL by
787
  // using PHP's session.cookie_secure setting. The browser will then use two
788
  // separate session cookies for the HTTPS and HTTP versions of the site. So we
789
  // must use different session identifiers for HTTPS and HTTP to prevent a
790
  // cookie collision.
791
  if ($is_https) {
792
    ini_set('session.cookie_secure', TRUE);
793
  }
794
  $prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS';
795
  session_name($prefix . substr(hash('sha256', $session_name), 0, 32));
796
}
797

    
798
/**
799
 * Returns and optionally sets the filename for a system resource.
800
 *
801
 * The filename, whether provided, cached, or retrieved from the database, is
802
 * only returned if the file exists.
803
 *
804
 * This function plays a key role in allowing Drupal's resources (modules
805
 * and themes) to be located in different places depending on a site's
806
 * configuration. For example, a module 'foo' may legally be located
807
 * in any of these three places:
808
 *
809
 * modules/foo/foo.module
810
 * sites/all/modules/foo/foo.module
811
 * sites/example.com/modules/foo/foo.module
812
 *
813
 * Calling drupal_get_filename('module', 'foo') will give you one of
814
 * the above, depending on where the module is located.
815
 *
816
 * @param $type
817
 *   The type of the item (theme, theme_engine, module, profile).
818
 * @param $name
819
 *   The name of the item for which the filename is requested.
820
 * @param $filename
821
 *   The filename of the item if it is to be set explicitly rather
822
 *   than by consulting the database.
823
 *
824
 * @return
825
 *   The filename of the requested item or NULL if the item is not found.
826
 */
827
function drupal_get_filename($type, $name, $filename = NULL) {
828
  // The location of files will not change during the request, so do not use
829
  // drupal_static().
830
  static $files = array(), $dirs = array();
831

    
832
  // Profiles are a special case: they have a fixed location and naming.
833
  if ($type == 'profile') {
834
    $profile_filename = "profiles/$name/$name.profile";
835
    $files[$type][$name] = file_exists($profile_filename) ? $profile_filename : FALSE;
836
  }
837
  if (!isset($files[$type])) {
838
    $files[$type] = array();
839
  }
840

    
841
  if (!empty($filename) && file_exists($filename)) {
842
    $files[$type][$name] = $filename;
843
  }
844
  elseif (isset($files[$type][$name])) {
845
    // nothing
846
  }
847
  // Verify that we have an active database connection, before querying
848
  // the database. This is required because this function is called both
849
  // before we have a database connection (i.e. during installation) and
850
  // when a database connection fails.
851
  else {
852
    try {
853
      if (function_exists('db_query')) {
854
        $file = db_query("SELECT filename FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
855
        if (file_exists(DRUPAL_ROOT . '/' . $file)) {
856
          $files[$type][$name] = $file;
857
        }
858
      }
859
    }
860
    catch (Exception $e) {
861
      // The database table may not exist because Drupal is not yet installed,
862
      // or the database might be down. We have a fallback for this case so we
863
      // hide the error completely.
864
    }
865
    // Fallback to searching the filesystem if the database could not find the
866
    // file or the file returned by the database is not found.
867
    if (!isset($files[$type][$name])) {
868
      // We have a consistent directory naming: modules, themes...
869
      $dir = $type . 's';
870
      if ($type == 'theme_engine') {
871
        $dir = 'themes/engines';
872
        $extension = 'engine';
873
      }
874
      elseif ($type == 'theme') {
875
        $extension = 'info';
876
      }
877
      else {
878
        $extension = $type;
879
      }
880

    
881
      if (!isset($dirs[$dir][$extension])) {
882
        $dirs[$dir][$extension] = TRUE;
883
        if (!function_exists('drupal_system_listing')) {
884
          require_once DRUPAL_ROOT . '/includes/common.inc';
885
        }
886
        // Scan the appropriate directories for all files with the requested
887
        // extension, not just the file we are currently looking for. This
888
        // prevents unnecessary scans from being repeated when this function is
889
        // called more than once in the same page request.
890
        $matches = drupal_system_listing("/^" . DRUPAL_PHP_FUNCTION_PATTERN . "\.$extension$/", $dir, 'name', 0);
891
        foreach ($matches as $matched_name => $file) {
892
          $files[$type][$matched_name] = $file->uri;
893
        }
894
      }
895
    }
896
  }
897

    
898
  if (isset($files[$type][$name])) {
899
    return $files[$type][$name];
900
  }
901
}
902

    
903
/**
904
 * Loads the persistent variable table.
905
 *
906
 * The variable table is composed of values that have been saved in the table
907
 * with variable_set() as well as those explicitly specified in the
908
 * configuration file.
909
 */
910
function variable_initialize($conf = array()) {
911
  // NOTE: caching the variables improves performance by 20% when serving
912
  // cached pages.
913
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
914
    $variables = $cached->data;
915
  }
916
  else {
917
    // Cache miss. Avoid a stampede.
918
    $name = 'variable_init';
919
    if (!lock_acquire($name, 1)) {
920
      // Another request is building the variable cache.
921
      // Wait, then re-run this function.
922
      lock_wait($name);
923
      return variable_initialize($conf);
924
    }
925
    else {
926
      // Proceed with variable rebuild.
927
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
928
      cache_set('variables', $variables, 'cache_bootstrap');
929
      lock_release($name);
930
    }
931
  }
932

    
933
  foreach ($conf as $name => $value) {
934
    $variables[$name] = $value;
935
  }
936

    
937
  return $variables;
938
}
939

    
940
/**
941
 * Returns a persistent variable.
942
 *
943
 * Case-sensitivity of the variable_* functions depends on the database
944
 * collation used. To avoid problems, always use lower case for persistent
945
 * variable names.
946
 *
947
 * @param $name
948
 *   The name of the variable to return.
949
 * @param $default
950
 *   The default value to use if this variable has never been set.
951
 *
952
 * @return
953
 *   The value of the variable. Unserialization is taken care of as necessary.
954
 *
955
 * @see variable_del()
956
 * @see variable_set()
957
 */
958
function variable_get($name, $default = NULL) {
959
  global $conf;
960

    
961
  return isset($conf[$name]) ? $conf[$name] : $default;
962
}
963

    
964
/**
965
 * Sets a persistent variable.
966
 *
967
 * Case-sensitivity of the variable_* functions depends on the database
968
 * collation used. To avoid problems, always use lower case for persistent
969
 * variable names.
970
 *
971
 * @param $name
972
 *   The name of the variable to set.
973
 * @param $value
974
 *   The value to set. This can be any PHP data type; these functions take care
975
 *   of serialization as necessary.
976
 *
977
 * @see variable_del()
978
 * @see variable_get()
979
 */
980
function variable_set($name, $value) {
981
  global $conf;
982

    
983
  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();
984

    
985
  cache_clear_all('variables', 'cache_bootstrap');
986

    
987
  $conf[$name] = $value;
988
}
989

    
990
/**
991
 * Unsets a persistent variable.
992
 *
993
 * Case-sensitivity of the variable_* functions depends on the database
994
 * collation used. To avoid problems, always use lower case for persistent
995
 * variable names.
996
 *
997
 * @param $name
998
 *   The name of the variable to undefine.
999
 *
1000
 * @see variable_get()
1001
 * @see variable_set()
1002
 */
1003
function variable_del($name) {
1004
  global $conf;
1005

    
1006
  db_delete('variable')
1007
    ->condition('name', $name)
1008
    ->execute();
1009
  cache_clear_all('variables', 'cache_bootstrap');
1010

    
1011
  unset($conf[$name]);
1012
}
1013

    
1014
/**
1015
 * Retrieves the current page from the cache.
1016
 *
1017
 * Note: we do not serve cached pages to authenticated users, or to anonymous
1018
 * users when $_SESSION is non-empty. $_SESSION may contain status messages
1019
 * from a form submission, the contents of a shopping cart, or other user-
1020
 * specific content that should not be cached and displayed to other users.
1021
 *
1022
 * @param $check_only
1023
 *   (optional) Set to TRUE to only return whether a previous call found a
1024
 *   cache entry.
1025
 *
1026
 * @return
1027
 *   The cache object, if the page was found in the cache, NULL otherwise.
1028
 */
1029
function drupal_page_get_cache($check_only = FALSE) {
1030
  global $base_root;
1031
  static $cache_hit = FALSE;
1032

    
1033
  if ($check_only) {
1034
    return $cache_hit;
1035
  }
1036

    
1037
  if (drupal_page_is_cacheable()) {
1038
    $cache = cache_get($base_root . request_uri(), 'cache_page');
1039
    if ($cache !== FALSE) {
1040
      $cache_hit = TRUE;
1041
    }
1042
    return $cache;
1043
  }
1044
}
1045

    
1046
/**
1047
 * Determines the cacheability of the current page.
1048
 *
1049
 * @param $allow_caching
1050
 *   Set to FALSE if you want to prevent this page to get cached.
1051
 *
1052
 * @return
1053
 *   TRUE if the current page can be cached, FALSE otherwise.
1054
 */
1055
function drupal_page_is_cacheable($allow_caching = NULL) {
1056
  $allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
1057
  if (isset($allow_caching)) {
1058
    $allow_caching_static = $allow_caching;
1059
  }
1060

    
1061
  return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
1062
    && !drupal_is_cli();
1063
}
1064

    
1065
/**
1066
 * Invokes a bootstrap hook in all bootstrap modules that implement it.
1067
 *
1068
 * @param $hook
1069
 *   The name of the bootstrap hook to invoke.
1070
 *
1071
 * @see bootstrap_hooks()
1072
 */
1073
function bootstrap_invoke_all($hook) {
1074
  // Bootstrap modules should have been loaded when this function is called, so
1075
  // we don't need to tell module_list() to reset its internal list (and we
1076
  // therefore leave the first parameter at its default value of FALSE). We
1077
  // still pass in TRUE for the second parameter, though; in case this is the
1078
  // first time during the bootstrap that module_list() is called, we want to
1079
  // make sure that its internal cache is primed with the bootstrap modules
1080
  // only.
1081
  foreach (module_list(FALSE, TRUE) as $module) {
1082
    drupal_load('module', $module);
1083
    module_invoke($module, $hook);
1084
  }
1085
}
1086

    
1087
/**
1088
 * Includes a file with the provided type and name.
1089
 *
1090
 * This prevents including a theme, engine, module, etc., more than once.
1091
 *
1092
 * @param $type
1093
 *   The type of item to load (i.e. theme, theme_engine, module).
1094
 * @param $name
1095
 *   The name of the item to load.
1096
 *
1097
 * @return
1098
 *   TRUE if the item is loaded or has already been loaded.
1099
 */
1100
function drupal_load($type, $name) {
1101
  // Once a file is included this can't be reversed during a request so do not
1102
  // use drupal_static() here.
1103
  static $files = array();
1104

    
1105
  if (isset($files[$type][$name])) {
1106
    return TRUE;
1107
  }
1108

    
1109
  $filename = drupal_get_filename($type, $name);
1110

    
1111
  if ($filename) {
1112
    include_once DRUPAL_ROOT . '/' . $filename;
1113
    $files[$type][$name] = TRUE;
1114

    
1115
    return TRUE;
1116
  }
1117

    
1118
  return FALSE;
1119
}
1120

    
1121
/**
1122
 * Sets an HTTP response header for the current page.
1123
 *
1124
 * Note: When sending a Content-Type header, always include a 'charset' type,
1125
 * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
1126
 *
1127
 * @param $name
1128
 *   The HTTP header name, or the special 'Status' header name.
1129
 * @param $value
1130
 *   The HTTP header value; if equal to FALSE, the specified header is unset.
1131
 *   If $name is 'Status', this is expected to be a status code followed by a
1132
 *   reason phrase, e.g. "404 Not Found".
1133
 * @param $append
1134
 *   Whether to append the value to an existing header or to replace it.
1135
 */
1136
function drupal_add_http_header($name, $value, $append = FALSE) {
1137
  // The headers as name/value pairs.
1138
  $headers = &drupal_static('drupal_http_headers', array());
1139

    
1140
  $name_lower = strtolower($name);
1141
  _drupal_set_preferred_header_name($name);
1142

    
1143
  if ($value === FALSE) {
1144
    $headers[$name_lower] = FALSE;
1145
  }
1146
  elseif (isset($headers[$name_lower]) && $append) {
1147
    // Multiple headers with identical names may be combined using comma (RFC
1148
    // 2616, section 4.2).
1149
    $headers[$name_lower] .= ',' . $value;
1150
  }
1151
  else {
1152
    $headers[$name_lower] = $value;
1153
  }
1154
  drupal_send_headers(array($name => $headers[$name_lower]), TRUE);
1155
}
1156

    
1157
/**
1158
 * Gets the HTTP response headers for the current page.
1159
 *
1160
 * @param $name
1161
 *   An HTTP header name. If omitted, all headers are returned as name/value
1162
 *   pairs. If an array value is FALSE, the header has been unset.
1163
 *
1164
 * @return
1165
 *   A string containing the header value, or FALSE if the header has been set,
1166
 *   or NULL if the header has not been set.
1167
 */
1168
function drupal_get_http_header($name = NULL) {
1169
  $headers = &drupal_static('drupal_http_headers', array());
1170
  if (isset($name)) {
1171
    $name = strtolower($name);
1172
    return isset($headers[$name]) ? $headers[$name] : NULL;
1173
  }
1174
  else {
1175
    return $headers;
1176
  }
1177
}
1178

    
1179
/**
1180
 * Sets the preferred name for the HTTP header.
1181
 *
1182
 * Header names are case-insensitive, but for maximum compatibility they should
1183
 * follow "common form" (see RFC 2617, section 4.2).
1184
 */
1185
function _drupal_set_preferred_header_name($name = NULL) {
1186
  static $header_names = array();
1187

    
1188
  if (!isset($name)) {
1189
    return $header_names;
1190
  }
1191
  $header_names[strtolower($name)] = $name;
1192
}
1193

    
1194
/**
1195
 * Sends the HTTP response headers that were previously set, adding defaults.
1196
 *
1197
 * Headers are set in drupal_add_http_header(). Default headers are not set
1198
 * if they have been replaced or unset using drupal_add_http_header().
1199
 *
1200
 * @param array $default_headers
1201
 *   (optional) An array of headers as name/value pairs.
1202
 * @param bool $only_default
1203
 *   (optional) If TRUE and headers have already been sent, send only the
1204
 *   specified headers.
1205
 */
1206
function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
1207
  $headers_sent = &drupal_static(__FUNCTION__, FALSE);
1208
  $headers = drupal_get_http_header();
1209
  if ($only_default && $headers_sent) {
1210
    $headers = array();
1211
  }
1212
  $headers_sent = TRUE;
1213

    
1214
  $header_names = _drupal_set_preferred_header_name();
1215
  foreach ($default_headers as $name => $value) {
1216
    $name_lower = strtolower($name);
1217
    if (!isset($headers[$name_lower])) {
1218
      $headers[$name_lower] = $value;
1219
      $header_names[$name_lower] = $name;
1220
    }
1221
  }
1222
  foreach ($headers as $name_lower => $value) {
1223
    if ($name_lower == 'status') {
1224
      header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
1225
    }
1226
    // Skip headers that have been unset.
1227
    elseif ($value !== FALSE) {
1228
      header($header_names[$name_lower] . ': ' . $value);
1229
    }
1230
  }
1231
}
1232

    
1233
/**
1234
 * Sets HTTP headers in preparation for a page response.
1235
 *
1236
 * Authenticated users are always given a 'no-cache' header, and will fetch a
1237
 * fresh page on every request. This prevents authenticated users from seeing
1238
 * locally cached pages.
1239
 *
1240
 * Also give each page a unique ETag. This will force clients to include both
1241
 * an If-Modified-Since header and an If-None-Match header when doing
1242
 * conditional requests for the page (required by RFC 2616, section 13.3.4),
1243
 * making the validation more robust. This is a workaround for a bug in Mozilla
1244
 * Firefox that is triggered when Drupal's caching is enabled and the user
1245
 * accesses Drupal via an HTTP proxy (see
1246
 * https://bugzilla.mozilla.org/show_bug.cgi?id=269303): When an authenticated
1247
 * user requests a page, and then logs out and requests the same page again,
1248
 * Firefox may send a conditional request based on the page that was cached
1249
 * locally when the user was logged in. If this page did not have an ETag
1250
 * header, the request only contains an If-Modified-Since header. The date will
1251
 * be recent, because with authenticated users the Last-Modified header always
1252
 * refers to the time of the request. If the user accesses Drupal via a proxy
1253
 * server, and the proxy already has a cached copy of the anonymous page with an
1254
 * older Last-Modified date, the proxy may respond with 304 Not Modified, making
1255
 * the client think that the anonymous and authenticated pageviews are
1256
 * identical.
1257
 *
1258
 * @see drupal_page_set_cache()
1259
 */
1260
function drupal_page_header() {
1261
  $headers_sent = &drupal_static(__FUNCTION__, FALSE);
1262
  if ($headers_sent) {
1263
    return TRUE;
1264
  }
1265
  $headers_sent = TRUE;
1266

    
1267
  $default_headers = array(
1268
    'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
1269
    'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),
1270
    'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0',
1271
    'ETag' => '"' . REQUEST_TIME . '"',
1272
  );
1273
  drupal_send_headers($default_headers);
1274
}
1275

    
1276
/**
1277
 * Sets HTTP headers in preparation for a cached page response.
1278
 *
1279
 * The headers allow as much as possible in proxies and browsers without any
1280
 * particular knowledge about the pages. Modules can override these headers
1281
 * using drupal_add_http_header().
1282
 *
1283
 * If the request is conditional (using If-Modified-Since and If-None-Match),
1284
 * and the conditions match those currently in the cache, a 304 Not Modified
1285
 * response is sent.
1286
 */
1287
function drupal_serve_page_from_cache(stdClass $cache) {
1288
  // Negotiate whether to use compression.
1289
  $page_compression = !empty($cache->data['page_compressed']);
1290
  $return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;
1291

    
1292
  // Get headers set in hook_boot(). Keys are lower-case.
1293
  $hook_boot_headers = drupal_get_http_header();
1294

    
1295
  // Headers generated in this function, that may be replaced or unset using
1296
  // drupal_add_http_headers(). Keys are mixed-case.
1297
  $default_headers = array();
1298

    
1299
  foreach ($cache->data['headers'] as $name => $value) {
1300
    // In the case of a 304 response, certain headers must be sent, and the
1301
    // remaining may not (see RFC 2616, section 10.3.5). Do not override
1302
    // headers set in hook_boot().
1303
    $name_lower = strtolower($name);
1304
    if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($hook_boot_headers[$name_lower])) {
1305
      drupal_add_http_header($name, $value);
1306
      unset($cache->data['headers'][$name]);
1307
    }
1308
  }
1309

    
1310
  // If the client sent a session cookie, a cached copy will only be served
1311
  // to that one particular client due to Vary: Cookie. Thus, do not set
1312
  // max-age > 0, allowing the page to be cached by external proxies, when a
1313
  // session cookie is present unless the Vary header has been replaced or
1314
  // unset in hook_boot().
1315
  $max_age = !isset($_COOKIE[session_name()]) || isset($hook_boot_headers['vary']) ? variable_get('page_cache_maximum_age', 0) : 0;
1316
  $default_headers['Cache-Control'] = 'public, max-age=' . $max_age;
1317

    
1318
  // Entity tag should change if the output changes.
1319
  $etag = '"' . $cache->created . '-' . intval($return_compressed) . '"';
1320
  header('Etag: ' . $etag);
1321

    
1322
  // See if the client has provided the required HTTP headers.
1323
  $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
1324
  $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
1325

    
1326
  if ($if_modified_since && $if_none_match
1327
      && $if_none_match == $etag // etag must match
1328
      && $if_modified_since == $cache->created) {  // if-modified-since must match
1329
    header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
1330
    drupal_send_headers($default_headers);
1331
    return;
1332
  }
1333

    
1334
  // Send the remaining headers.
1335
  foreach ($cache->data['headers'] as $name => $value) {
1336
    drupal_add_http_header($name, $value);
1337
  }
1338

    
1339
  $default_headers['Last-Modified'] = gmdate(DATE_RFC1123, $cache->created);
1340

    
1341
  // HTTP/1.0 proxies does not support the Vary header, so prevent any caching
1342
  // by sending an Expires date in the past. HTTP/1.1 clients ignores the
1343
  // Expires header if a Cache-Control: max-age= directive is specified (see RFC
1344
  // 2616, section 14.9.3).
1345
  $default_headers['Expires'] = 'Sun, 19 Nov 1978 05:00:00 GMT';
1346

    
1347
  drupal_send_headers($default_headers);
1348

    
1349
  // Allow HTTP proxies to cache pages for anonymous users without a session
1350
  // cookie. The Vary header is used to indicates the set of request-header
1351
  // fields that fully determines whether a cache is permitted to use the
1352
  // response to reply to a subsequent request for a given URL without
1353
  // revalidation. If a Vary header has been set in hook_boot(), it is assumed
1354
  // that the module knows how to cache the page.
1355
  if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie')) {
1356
    header('Vary: Cookie');
1357
  }
1358

    
1359
  if ($page_compression) {
1360
    header('Vary: Accept-Encoding', FALSE);
1361
    // If page_compression is enabled, the cache contains gzipped data.
1362
    if ($return_compressed) {
1363
      // $cache->data['body'] is already gzip'ed, so make sure
1364
      // zlib.output_compression does not compress it once more.
1365
      ini_set('zlib.output_compression', '0');
1366
      header('Content-Encoding: gzip');
1367
    }
1368
    else {
1369
      // The client does not support compression, so unzip the data in the
1370
      // cache. Strip the gzip header and run uncompress.
1371
      $cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
1372
    }
1373
  }
1374

    
1375
  // Print the page.
1376
  print $cache->data['body'];
1377
}
1378

    
1379
/**
1380
 * Defines the critical hooks that force modules to always be loaded.
1381
 */
1382
function bootstrap_hooks() {
1383
  return array('boot', 'exit', 'watchdog', 'language_init');
1384
}
1385

    
1386
/**
1387
 * Unserializes and appends elements from a serialized string.
1388
 *
1389
 * @param $obj
1390
 *   The object to which the elements are appended.
1391
 * @param $field
1392
 *   The attribute of $obj whose value should be unserialized.
1393
 */
1394
function drupal_unpack($obj, $field = 'data') {
1395
  if ($obj->$field && $data = unserialize($obj->$field)) {
1396
    foreach ($data as $key => $value) {
1397
      if (!empty($key) && !isset($obj->$key)) {
1398
        $obj->$key = $value;
1399
      }
1400
    }
1401
  }
1402
  return $obj;
1403
}
1404

    
1405
/**
1406
 * Translates a string to the current language or to a given language.
1407
 *
1408
 * The t() function serves two purposes. First, at run-time it translates
1409
 * user-visible text into the appropriate language. Second, various mechanisms
1410
 * that figure out what text needs to be translated work off t() -- the text
1411
 * inside t() calls is added to the database of strings to be translated.
1412
 * These strings are expected to be in English, so the first argument should
1413
 * always be in English. To enable a fully-translatable site, it is important
1414
 * that all human-readable text that will be displayed on the site or sent to
1415
 * a user is passed through the t() function, or a related function. See the
1416
 * @link http://drupal.org/node/322729 Localization API @endlink pages for
1417
 * more information, including recommendations on how to break up or not
1418
 * break up strings for translation.
1419
 *
1420
 * @section sec_translating_vars Translating Variables
1421
 * You should never use t() to translate variables, such as calling
1422
 * @code t($text); @endcode, unless the text that the variable holds has been
1423
 * passed through t() elsewhere (e.g., $text is one of several translated
1424
 * literal strings in an array). It is especially important never to call
1425
 * @code t($user_text); @endcode, where $user_text is some text that a user
1426
 * entered - doing that can lead to cross-site scripting and other security
1427
 * problems. However, you can use variable substitution in your string, to put
1428
 * variable text such as user names or link URLs into translated text. Variable
1429
 * substitution looks like this:
1430
 * @code
1431
 * $text = t("@name's blog", array('@name' => format_username($account)));
1432
 * @endcode
1433
 * Basically, you can put variables like @name into your string, and t() will
1434
 * substitute their sanitized values at translation time. (See the
1435
 * Localization API pages referenced above and the documentation of
1436
 * format_string() for details about how to define variables in your string.)
1437
 * Translators can then rearrange the string as necessary for the language
1438
 * (e.g., in Spanish, it might be "blog de @name").
1439
 *
1440
 * @section sec_alt_funcs_install Use During Installation Phase
1441
 * During the Drupal installation phase, some resources used by t() wil not be
1442
 * available to code that needs localization. See st() and get_t() for
1443
 * alternatives.
1444
 *
1445
 * @param $string
1446
 *   A string containing the English string to translate.
1447
 * @param $args
1448
 *   An associative array of replacements to make after translation. Based
1449
 *   on the first character of the key, the value is escaped and/or themed.
1450
 *   See format_string() for details.
1451
 * @param $options
1452
 *   An associative array of additional options, with the following elements:
1453
 *   - 'langcode' (defaults to the current language): The language code to
1454
 *     translate to a language other than what is used to display the page.
1455
 *   - 'context' (defaults to the empty context): The context the source string
1456
 *     belongs to.
1457
 *
1458
 * @return
1459
 *   The translated string.
1460
 *
1461
 * @see st()
1462
 * @see get_t()
1463
 * @see format_string()
1464
 * @ingroup sanitization
1465
 */
1466
function t($string, array $args = array(), array $options = array()) {
1467
  global $language;
1468
  static $custom_strings;
1469

    
1470
  // Merge in default.
1471
  if (empty($options['langcode'])) {
1472
    $options['langcode'] = isset($language->language) ? $language->language : 'en';
1473
  }
1474
  if (empty($options['context'])) {
1475
    $options['context'] = '';
1476
  }
1477

    
1478
  // First, check for an array of customized strings. If present, use the array
1479
  // *instead of* database lookups. This is a high performance way to provide a
1480
  // handful of string replacements. See settings.php for examples.
1481
  // Cache the $custom_strings variable to improve performance.
1482
  if (!isset($custom_strings[$options['langcode']])) {
1483
    $custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
1484
  }
1485
  // Custom strings work for English too, even if locale module is disabled.
1486
  if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
1487
    $string = $custom_strings[$options['langcode']][$options['context']][$string];
1488
  }
1489
  // Translate with locale module if enabled.
1490
  elseif ($options['langcode'] != 'en' && function_exists('locale')) {
1491
    $string = locale($string, $options['context'], $options['langcode']);
1492
  }
1493
  if (empty($args)) {
1494
    return $string;
1495
  }
1496
  else {
1497
    return format_string($string, $args);
1498
  }
1499
}
1500

    
1501
/**
1502
 * Formats a string for HTML display by replacing variable placeholders.
1503
 *
1504
 * This function replaces variable placeholders in a string with the requested
1505
 * values and escapes the values so they can be safely displayed as HTML. It
1506
 * should be used on any unknown text that is intended to be printed to an HTML
1507
 * page (especially text that may have come from untrusted users, since in that
1508
 * case it prevents cross-site scripting and other security problems).
1509
 *
1510
 * In most cases, you should use t() rather than calling this function
1511
 * directly, since it will translate the text (on non-English-only sites) in
1512
 * addition to formatting it.
1513
 *
1514
 * @param $string
1515
 *   A string containing placeholders.
1516
 * @param $args
1517
 *   An associative array of replacements to make. Occurrences in $string of
1518
 *   any key in $args are replaced with the corresponding value, after optional
1519
 *   sanitization and formatting. The type of sanitization and formatting
1520
 *   depends on the first character of the key:
1521
 *   - @variable: Escaped to HTML using check_plain(). Use this as the default
1522
 *     choice for anything displayed on a page on the site.
1523
 *   - %variable: Escaped to HTML and formatted using drupal_placeholder(),
1524
 *     which makes it display as <em>emphasized</em> text.
1525
 *   - !variable: Inserted as is, with no sanitization or formatting. Only use
1526
 *     this for text that has already been prepared for HTML display (for
1527
 *     example, user-supplied text that has already been run through
1528
 *     check_plain() previously, or is expected to contain some limited HTML
1529
 *     tags and has already been run through filter_xss() previously).
1530
 *
1531
 * @see t()
1532
 * @ingroup sanitization
1533
 */
1534
function format_string($string, array $args = array()) {
1535
  // Transform arguments before inserting them.
1536
  foreach ($args as $key => $value) {
1537
    switch ($key[0]) {
1538
      case '@':
1539
        // Escaped only.
1540
        $args[$key] = check_plain($value);
1541
        break;
1542

    
1543
      case '%':
1544
      default:
1545
        // Escaped and placeholder.
1546
        $args[$key] = drupal_placeholder($value);
1547
        break;
1548

    
1549
      case '!':
1550
        // Pass-through.
1551
    }
1552
  }
1553
  return strtr($string, $args);
1554
}
1555

    
1556
/**
1557
 * Encodes special characters in a plain-text string for display as HTML.
1558
 *
1559
 * Also validates strings as UTF-8 to prevent cross site scripting attacks on
1560
 * Internet Explorer 6.
1561
 *
1562
 * @param $text
1563
 *   The text to be checked or processed.
1564
 *
1565
 * @return
1566
 *   An HTML safe version of $text, or an empty string if $text is not
1567
 *   valid UTF-8.
1568
 *
1569
 * @see drupal_validate_utf8()
1570
 * @ingroup sanitization
1571
 */
1572
function check_plain($text) {
1573
  return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
1574
}
1575

    
1576
/**
1577
 * Checks whether a string is valid UTF-8.
1578
 *
1579
 * All functions designed to filter input should use drupal_validate_utf8
1580
 * to ensure they operate on valid UTF-8 strings to prevent bypass of the
1581
 * filter.
1582
 *
1583
 * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
1584
 * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
1585
 * bytes. When these subsequent bytes are HTML control characters such as
1586
 * quotes or angle brackets, parts of the text that were deemed safe by filters
1587
 * end up in locations that are potentially unsafe; An onerror attribute that
1588
 * is outside of a tag, and thus deemed safe by a filter, can be interpreted
1589
 * by the browser as if it were inside the tag.
1590
 *
1591
 * The function does not return FALSE for strings containing character codes
1592
 * above U+10FFFF, even though these are prohibited by RFC 3629.
1593
 *
1594
 * @param $text
1595
 *   The text to check.
1596
 *
1597
 * @return
1598
 *   TRUE if the text is valid UTF-8, FALSE if not.
1599
 */
1600
function drupal_validate_utf8($text) {
1601
  if (strlen($text) == 0) {
1602
    return TRUE;
1603
  }
1604
  // With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
1605
  // containing invalid UTF-8 byte sequences. It does not reject character
1606
  // codes above U+10FFFF (represented by 4 or more octets), though.
1607
  return (preg_match('/^./us', $text) == 1);
1608
}
1609

    
1610
/**
1611
 * Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
1612
 *
1613
 * Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
1614
 * equivalent using other environment variables.
1615
 */
1616
function request_uri() {
1617
  if (isset($_SERVER['REQUEST_URI'])) {
1618
    $uri = $_SERVER['REQUEST_URI'];
1619
  }
1620
  else {
1621
    if (isset($_SERVER['argv'])) {
1622
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
1623
    }
1624
    elseif (isset($_SERVER['QUERY_STRING'])) {
1625
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
1626
    }
1627
    else {
1628
      $uri = $_SERVER['SCRIPT_NAME'];
1629
    }
1630
  }
1631
  // Prevent multiple slashes to avoid cross site requests via the Form API.
1632
  $uri = '/' . ltrim($uri, '/');
1633

    
1634
  return $uri;
1635
}
1636

    
1637
/**
1638
 * Logs an exception.
1639
 *
1640
 * This is a wrapper function for watchdog() which automatically decodes an
1641
 * exception.
1642
 *
1643
 * @param $type
1644
 *   The category to which this message belongs.
1645
 * @param $exception
1646
 *   The exception that is going to be logged.
1647
 * @param $message
1648
 *   The message to store in the log. If empty, a text that contains all useful
1649
 *   information about the passed-in exception is used.
1650
 * @param $variables
1651
 *   Array of variables to replace in the message on display. Defaults to the
1652
 *   return value of drupal_decode_exception().
1653
 * @param $severity
1654
 *   The severity of the message, as per RFC 3164.
1655
 * @param $link
1656
 *   A link to associate with the message.
1657
 *
1658
 * @see watchdog()
1659
 * @see drupal_decode_exception()
1660
 */
1661
function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {
1662

    
1663
   // Use a default value if $message is not set.
1664
   if (empty($message)) {
1665
     // The exception message is run through check_plain() by _drupal_decode_exception().
1666
     $message = '%type: !message in %function (line %line of %file).';
1667
   }
1668
   // $variables must be an array so that we can add the exception information.
1669
   if (!is_array($variables)) {
1670
     $variables = array();
1671
   }
1672

    
1673
   require_once DRUPAL_ROOT . '/includes/errors.inc';
1674
   $variables += _drupal_decode_exception($exception);
1675
   watchdog($type, $message, $variables, $severity, $link);
1676
}
1677

    
1678
/**
1679
 * Logs a system message.
1680
 *
1681
 * @param $type
1682
 *   The category to which this message belongs. Can be any string, but the
1683
 *   general practice is to use the name of the module calling watchdog().
1684
 * @param $message
1685
 *   The message to store in the log. Keep $message translatable
1686
 *   by not concatenating dynamic values into it! Variables in the
1687
 *   message should be added by using placeholder strings alongside
1688
 *   the variables argument to declare the value of the placeholders.
1689
 *   See t() for documentation on how $message and $variables interact.
1690
 * @param $variables
1691
 *   Array of variables to replace in the message on display or
1692
 *   NULL if message is already translated or not possible to
1693
 *   translate.
1694
 * @param $severity
1695
 *   The severity of the message; one of the following values as defined in
1696
 *   @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
1697
 *   - WATCHDOG_EMERGENCY: Emergency, system is unusable.
1698
 *   - WATCHDOG_ALERT: Alert, action must be taken immediately.
1699
 *   - WATCHDOG_CRITICAL: Critical conditions.
1700
 *   - WATCHDOG_ERROR: Error conditions.
1701
 *   - WATCHDOG_WARNING: Warning conditions.
1702
 *   - WATCHDOG_NOTICE: (default) Normal but significant conditions.
1703
 *   - WATCHDOG_INFO: Informational messages.
1704
 *   - WATCHDOG_DEBUG: Debug-level messages.
1705
 * @param $link
1706
 *   A link to associate with the message.
1707
 *
1708
 * @see watchdog_severity_levels()
1709
 * @see hook_watchdog()
1710
 */
1711
function watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
1712
  global $user, $base_root;
1713

    
1714
  static $in_error_state = FALSE;
1715

    
1716
  // It is possible that the error handling will itself trigger an error. In that case, we could
1717
  // end up in an infinite loop. To avoid that, we implement a simple static semaphore.
1718
  if (!$in_error_state && function_exists('module_implements')) {
1719
    $in_error_state = TRUE;
1720

    
1721
    // The user object may not exist in all conditions, so 0 is substituted if needed.
1722
    $user_uid = isset($user->uid) ? $user->uid : 0;
1723

    
1724
    // Prepare the fields to be logged
1725
    $log_entry = array(
1726
      'type'        => $type,
1727
      'message'     => $message,
1728
      'variables'   => $variables,
1729
      'severity'    => $severity,
1730
      'link'        => $link,
1731
      'user'        => $user,
1732
      'uid'         => $user_uid,
1733
      'request_uri' => $base_root . request_uri(),
1734
      'referer'     => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
1735
      'ip'          => ip_address(),
1736
      // Request time isn't accurate for long processes, use time() instead.
1737
      'timestamp'   => time(),
1738
    );
1739

    
1740
    // Call the logging hooks to log/process the message
1741
    foreach (module_implements('watchdog') as $module) {
1742
      module_invoke($module, 'watchdog', $log_entry);
1743
    }
1744

    
1745
    // It is critical that the semaphore is only cleared here, in the parent
1746
    // watchdog() call (not outside the loop), to prevent recursive execution.
1747
    $in_error_state = FALSE;
1748
  }
1749
}
1750

    
1751
/**
1752
 * Sets a message to display to the user.
1753
 *
1754
 * Messages are stored in a session variable and displayed in page.tpl.php via
1755
 * the $messages theme variable.
1756
 *
1757
 * Example usage:
1758
 * @code
1759
 * drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
1760
 * @endcode
1761
 *
1762
 * @param string $message
1763
 *   (optional) The translated message to be displayed to the user. For
1764
 *   consistency with other messages, it should begin with a capital letter and
1765
 *   end with a period.
1766
 * @param string $type
1767
 *   (optional) The message's type. Defaults to 'status'. These values are
1768
 *   supported:
1769
 *   - 'status'
1770
 *   - 'warning'
1771
 *   - 'error'
1772
 * @param bool $repeat
1773
 *   (optional) If this is FALSE and the message is already set, then the
1774
 *   message won't be repeated. Defaults to TRUE.
1775
 *
1776
 * @return array|null
1777
 *   A multidimensional array with keys corresponding to the set message types.
1778
 *   The indexed array values of each contain the set messages for that type.
1779
 *   Or, if there are no messages set, the function returns NULL.
1780
 *
1781
 * @see drupal_get_messages()
1782
 * @see theme_status_messages()
1783
 */
1784
function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
1785
  if ($message) {
1786
    if (!isset($_SESSION['messages'][$type])) {
1787
      $_SESSION['messages'][$type] = array();
1788
    }
1789

    
1790
    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
1791
      $_SESSION['messages'][$type][] = $message;
1792
    }
1793

    
1794
    // Mark this page as being uncacheable.
1795
    drupal_page_is_cacheable(FALSE);
1796
  }
1797

    
1798
  // Messages not set when DB connection fails.
1799
  return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
1800
}
1801

    
1802
/**
1803
 * Returns all messages that have been set with drupal_set_message().
1804
 *
1805
 * @param string $type
1806
 *   (optional) Limit the messages returned by type. Defaults to NULL, meaning
1807
 *   all types. These values are supported:
1808
 *   - NULL
1809
 *   - 'status'
1810
 *   - 'warning'
1811
 *   - 'error'
1812
 * @param bool $clear_queue
1813
 *   (optional) If this is TRUE, the queue will be cleared of messages of the
1814
 *   type specified in the $type parameter. Otherwise the queue will be left
1815
 *   intact. Defaults to TRUE.
1816
 *
1817
 * @return array
1818
 *   A multidimensional array with keys corresponding to the set message types.
1819
 *   The indexed array values of each contain the set messages for that type.
1820
 *   The messages returned are limited to the type specified in the $type
1821
 *   parameter. If there are no messages of the specified type, an empty array
1822
 *   is returned.
1823
 *
1824
 * @see drupal_set_message()
1825
 * @see theme_status_messages()
1826
 */
1827
function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
1828
  if ($messages = drupal_set_message()) {
1829
    if ($type) {
1830
      if ($clear_queue) {
1831
        unset($_SESSION['messages'][$type]);
1832
      }
1833
      if (isset($messages[$type])) {
1834
        return array($type => $messages[$type]);
1835
      }
1836
    }
1837
    else {
1838
      if ($clear_queue) {
1839
        unset($_SESSION['messages']);
1840
      }
1841
      return $messages;
1842
    }
1843
  }
1844
  return array();
1845
}
1846

    
1847
/**
1848
 * Gets the title of the current page.
1849
 *
1850
 * The title is displayed on the page and in the title bar.
1851
 *
1852
 * @return
1853
 *   The current page's title.
1854
 */
1855
function drupal_get_title() {
1856
  $title = drupal_set_title();
1857

    
1858
  // During a bootstrap, menu.inc is not included and thus we cannot provide a title.
1859
  if (!isset($title) && function_exists('menu_get_active_title')) {
1860
    $title = check_plain(menu_get_active_title());
1861
  }
1862

    
1863
  return $title;
1864
}
1865

    
1866
/**
1867
 * Sets the title of the current page.
1868
 *
1869
 * The title is displayed on the page and in the title bar.
1870
 *
1871
 * @param $title
1872
 *   Optional string value to assign to the page title; or if set to NULL
1873
 *   (default), leaves the current title unchanged.
1874
 * @param $output
1875
 *   Optional flag - normally should be left as CHECK_PLAIN. Only set to
1876
 *   PASS_THROUGH if you have already removed any possibly dangerous code
1877
 *   from $title using a function like check_plain() or filter_xss(). With this
1878
 *   flag the string will be passed through unchanged.
1879
 *
1880
 * @return
1881
 *   The updated title of the current page.
1882
 */
1883
function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
1884
  $stored_title = &drupal_static(__FUNCTION__);
1885

    
1886
  if (isset($title)) {
1887
    $stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
1888
  }
1889

    
1890
  return $stored_title;
1891
}
1892

    
1893
/**
1894
 * Checks to see if an IP address has been blocked.
1895
 *
1896
 * Blocked IP addresses are stored in the database by default. However for
1897
 * performance reasons we allow an override in settings.php. This allows us
1898
 * to avoid querying the database at this critical stage of the bootstrap if
1899
 * an administrative interface for IP address blocking is not required.
1900
 *
1901
 * @param $ip
1902
 *   IP address to check.
1903
 *
1904
 * @return bool
1905
 *   TRUE if access is denied, FALSE if access is allowed.
1906
 */
1907
function drupal_is_denied($ip) {
1908
  // Because this function is called on every page request, we first check
1909
  // for an array of IP addresses in settings.php before querying the
1910
  // database.
1911
  $blocked_ips = variable_get('blocked_ips');
1912
  $denied = FALSE;
1913
  if (isset($blocked_ips) && is_array($blocked_ips)) {
1914
    $denied = in_array($ip, $blocked_ips);
1915
  }
1916
  // Only check if database.inc is loaded already. If
1917
  // $conf['page_cache_without_database'] = TRUE; is set in settings.php,
1918
  // then the database won't be loaded here so the IPs in the database
1919
  // won't be denied. However the user asked explicitly not to use the
1920
  // database and also in this case it's quite likely that the user relies
1921
  // on higher performance solutions like a firewall.
1922
  elseif (class_exists('Database', FALSE)) {
1923
    $denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();
1924
  }
1925
  return $denied;
1926
}
1927

    
1928
/**
1929
 * Handles denied users.
1930
 *
1931
 * @param $ip
1932
 *   IP address to check. Prints a message and exits if access is denied.
1933
 */
1934
function drupal_block_denied($ip) {
1935
  // Deny access to blocked IP addresses - t() is not yet available.
1936
  if (drupal_is_denied($ip)) {
1937
    header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
1938
    print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.';
1939
    exit();
1940
  }
1941
}
1942

    
1943
/**
1944
 * Returns a URL-safe, base64 encoded string of highly randomized bytes (over the full 8-bit range).
1945
 *
1946
 * @param $byte_count
1947
 *   The number of random bytes to fetch and base64 encode.
1948
 *
1949
 * @return string
1950
 *   The base64 encoded result will have a length of up to 4 * $byte_count.
1951
 */
1952
function drupal_random_key($byte_count = 32) {
1953
  return drupal_base64_encode(drupal_random_bytes($byte_count));
1954
}
1955

    
1956
/**
1957
 * Returns a URL-safe, base64 encoded version of the supplied string.
1958
 *
1959
 * @param $string
1960
 *   The string to convert to base64.
1961
 *
1962
 * @return string
1963
 */
1964
function drupal_base64_encode($string) {
1965
  $data = base64_encode($string);
1966
  // Modify the output so it's safe to use in URLs.
1967
  return strtr($data, array('+' => '-', '/' => '_', '=' => ''));
1968
}
1969

    
1970
/**
1971
 * Returns a string of highly randomized bytes (over the full 8-bit range).
1972
 *
1973
 * This function is better than simply calling mt_rand() or any other built-in
1974
 * PHP function because it can return a long string of bytes (compared to < 4
1975
 * bytes normally from mt_rand()) and uses the best available pseudo-random
1976
 * source.
1977
 *
1978
 * @param $count
1979
 *   The number of characters (bytes) to return in the string.
1980
 */
1981
function drupal_random_bytes($count)  {
1982
  // $random_state does not use drupal_static as it stores random bytes.
1983
  static $random_state, $bytes, $has_openssl;
1984

    
1985
  $missing_bytes = $count - strlen($bytes);
1986

    
1987
  if ($missing_bytes > 0) {
1988
    // PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
1989
    // locking on Windows and rendered it unusable.
1990
    if (!isset($has_openssl)) {
1991
      $has_openssl = version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes');
1992
    }
1993

    
1994
    // openssl_random_pseudo_bytes() will find entropy in a system-dependent
1995
    // way.
1996
    if ($has_openssl) {
1997
      $bytes .= openssl_random_pseudo_bytes($missing_bytes);
1998
    }
1999

    
2000
    // Else, read directly from /dev/urandom, which is available on many *nix
2001
    // systems and is considered cryptographically secure.
2002
    elseif ($fh = @fopen('/dev/urandom', 'rb')) {
2003
      // PHP only performs buffered reads, so in reality it will always read
2004
      // at least 4096 bytes. Thus, it costs nothing extra to read and store
2005
      // that much so as to speed any additional invocations.
2006
      $bytes .= fread($fh, max(4096, $missing_bytes));
2007
      fclose($fh);
2008
    }
2009

    
2010
    // If we couldn't get enough entropy, this simple hash-based PRNG will
2011
    // generate a good set of pseudo-random bytes on any system.
2012
    // Note that it may be important that our $random_state is passed
2013
    // through hash() prior to being rolled into $output, that the two hash()
2014
    // invocations are different, and that the extra input into the first one -
2015
    // the microtime() - is prepended rather than appended. This is to avoid
2016
    // directly leaking $random_state via the $output stream, which could
2017
    // allow for trivial prediction of further "random" numbers.
2018
    if (strlen($bytes) < $count) {
2019
      // Initialize on the first call. The contents of $_SERVER includes a mix of
2020
      // user-specific and system information that varies a little with each page.
2021
      if (!isset($random_state)) {
2022
        $random_state = print_r($_SERVER, TRUE);
2023
        if (function_exists('getmypid')) {
2024
          // Further initialize with the somewhat random PHP process ID.
2025
          $random_state .= getmypid();
2026
        }
2027
        $bytes = '';
2028
      }
2029

    
2030
      do {
2031
        $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
2032
        $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
2033
      }
2034
      while (strlen($bytes) < $count);
2035
    }
2036
  }
2037
  $output = substr($bytes, 0, $count);
2038
  $bytes = substr($bytes, $count);
2039
  return $output;
2040
}
2041

    
2042
/**
2043
 * Calculates a base-64 encoded, URL-safe sha-256 hmac.
2044
 *
2045
 * @param string $data
2046
 *   String to be validated with the hmac.
2047
 * @param string $key
2048
 *   A secret string key.
2049
 *
2050
 * @return string
2051
 *   A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
2052
 *   any = padding characters removed.
2053
 */
2054
function drupal_hmac_base64($data, $key) {
2055
  // Casting $data and $key to strings here is necessary to avoid empty string
2056
  // results of the hash function if they are not scalar values. As this
2057
  // function is used in security-critical contexts like token validation it is
2058
  // important that it never returns an empty string.
2059
  $hmac = base64_encode(hash_hmac('sha256', (string) $data, (string) $key, TRUE));
2060
  // Modify the hmac so it's safe to use in URLs.
2061
  return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
2062
}
2063

    
2064
/**
2065
 * Calculates a base-64 encoded, URL-safe sha-256 hash.
2066
 *
2067
 * @param $data
2068
 *   String to be hashed.
2069
 *
2070
 * @return
2071
 *   A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
2072
 *   any = padding characters removed.
2073
 */
2074
function drupal_hash_base64($data) {
2075
  $hash = base64_encode(hash('sha256', $data, TRUE));
2076
  // Modify the hash so it's safe to use in URLs.
2077
  return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
2078
}
2079

    
2080
/**
2081
 * Merges multiple arrays, recursively, and returns the merged array.
2082
 *
2083
 * This function is similar to PHP's array_merge_recursive() function, but it
2084
 * handles non-array values differently. When merging values that are not both
2085
 * arrays, the latter value replaces the former rather than merging with it.
2086
 *
2087
 * Example:
2088
 * @code
2089
 * $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
2090
 * $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
2091
 *
2092
 * // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
2093
 * $incorrect = array_merge_recursive($link_options_1, $link_options_2);
2094
 *
2095
 * // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
2096
 * $correct = drupal_array_merge_deep($link_options_1, $link_options_2);
2097
 * @endcode
2098
 *
2099
 * @param ...
2100
 *   Arrays to merge.
2101
 *
2102
 * @return
2103
 *   The merged array.
2104
 *
2105
 * @see drupal_array_merge_deep_array()
2106
 */
2107
function drupal_array_merge_deep() {
2108
  $args = func_get_args();
2109
  return drupal_array_merge_deep_array($args);
2110
}
2111

    
2112
/**
2113
 * Merges multiple arrays, recursively, and returns the merged array.
2114
 *
2115
 * This function is equivalent to drupal_array_merge_deep(), except the
2116
 * input arrays are passed as a single array parameter rather than a variable
2117
 * parameter list.
2118
 *
2119
 * The following are equivalent:
2120
 * - drupal_array_merge_deep($a, $b);
2121
 * - drupal_array_merge_deep_array(array($a, $b));
2122
 *
2123
 * The following are also equivalent:
2124
 * - call_user_func_array('drupal_array_merge_deep', $arrays_to_merge);
2125
 * - drupal_array_merge_deep_array($arrays_to_merge);
2126
 *
2127
 * @see drupal_array_merge_deep()
2128
 */
2129
function drupal_array_merge_deep_array($arrays) {
2130
  $result = array();
2131

    
2132
  foreach ($arrays as $array) {
2133
    foreach ($array as $key => $value) {
2134
      // Renumber integer keys as array_merge_recursive() does. Note that PHP
2135
      // automatically converts array keys that are integer strings (e.g., '1')
2136
      // to integers.
2137
      if (is_integer($key)) {
2138
        $result[] = $value;
2139
      }
2140
      // Recurse when both values are arrays.
2141
      elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
2142
        $result[$key] = drupal_array_merge_deep_array(array($result[$key], $value));
2143
      }
2144
      // Otherwise, use the latter value, overriding any previous value.
2145
      else {
2146
        $result[$key] = $value;
2147
      }
2148
    }
2149
  }
2150

    
2151
  return $result;
2152
}
2153

    
2154
/**
2155
 * Generates a default anonymous $user object.
2156
 *
2157
 * @return Object - the user object.
2158
 */
2159
function drupal_anonymous_user() {
2160
  $user = variable_get('drupal_anonymous_user_object', new stdClass);
2161
  $user->uid = 0;
2162
  $user->hostname = ip_address();
2163
  $user->roles = array();
2164
  $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
2165
  $user->cache = 0;
2166
  return $user;
2167
}
2168

    
2169
/**
2170
 * Ensures Drupal is bootstrapped to the specified phase.
2171
 *
2172
 * In order to bootstrap Drupal from another PHP script, you can use this code:
2173
 * @code
2174
 *   define('DRUPAL_ROOT', '/path/to/drupal');
2175
 *   require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
2176
 *   drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
2177
 * @endcode
2178
 *
2179
 * @param $phase
2180
 *   A constant telling which phase to bootstrap to. When you bootstrap to a
2181
 *   particular phase, all earlier phases are run automatically. Possible
2182
 *   values:
2183
 *   - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
2184
 *   - DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
2185
 *   - DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
2186
 *   - DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
2187
 *   - DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
2188
 *   - DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
2189
 *   - DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
2190
 *   - DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input
2191
 *     data.
2192
 * @param $new_phase
2193
 *   A boolean, set to FALSE if calling drupal_bootstrap from inside a
2194
 *   function called from drupal_bootstrap (recursion).
2195
 *
2196
 * @return
2197
 *   The most recently completed phase.
2198
 */
2199
function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
2200
  // Not drupal_static(), because does not depend on any run-time information.
2201
  static $phases = array(
2202
    DRUPAL_BOOTSTRAP_CONFIGURATION,
2203
    DRUPAL_BOOTSTRAP_PAGE_CACHE,
2204
    DRUPAL_BOOTSTRAP_DATABASE,
2205
    DRUPAL_BOOTSTRAP_VARIABLES,
2206
    DRUPAL_BOOTSTRAP_SESSION,
2207
    DRUPAL_BOOTSTRAP_PAGE_HEADER,
2208
    DRUPAL_BOOTSTRAP_LANGUAGE,
2209
    DRUPAL_BOOTSTRAP_FULL,
2210
  );
2211
  // Not drupal_static(), because the only legitimate API to control this is to
2212
  // call drupal_bootstrap() with a new phase parameter.
2213
  static $final_phase;
2214
  // Not drupal_static(), because it's impossible to roll back to an earlier
2215
  // bootstrap state.
2216
  static $stored_phase = -1;
2217

    
2218
  // When not recursing, store the phase name so it's not forgotten while
2219
  // recursing.
2220
  if ($new_phase) {
2221
    $final_phase = $phase;
2222
  }
2223
  if (isset($phase)) {
2224
    // Call a phase if it has not been called before and is below the requested
2225
    // phase.
2226
    while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
2227
      $current_phase = array_shift($phases);
2228

    
2229
      // This function is re-entrant. Only update the completed phase when the
2230
      // current call actually resulted in a progress in the bootstrap process.
2231
      if ($current_phase > $stored_phase) {
2232
        $stored_phase = $current_phase;
2233
      }
2234

    
2235
      switch ($current_phase) {
2236
        case DRUPAL_BOOTSTRAP_CONFIGURATION:
2237
          _drupal_bootstrap_configuration();
2238
          break;
2239

    
2240
        case DRUPAL_BOOTSTRAP_PAGE_CACHE:
2241
          _drupal_bootstrap_page_cache();
2242
          break;
2243

    
2244
        case DRUPAL_BOOTSTRAP_DATABASE:
2245
          _drupal_bootstrap_database();
2246
          break;
2247

    
2248
        case DRUPAL_BOOTSTRAP_VARIABLES:
2249
          _drupal_bootstrap_variables();
2250
          break;
2251

    
2252
        case DRUPAL_BOOTSTRAP_SESSION:
2253
          require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
2254
          drupal_session_initialize();
2255
          break;
2256

    
2257
        case DRUPAL_BOOTSTRAP_PAGE_HEADER:
2258
          _drupal_bootstrap_page_header();
2259
          break;
2260

    
2261
        case DRUPAL_BOOTSTRAP_LANGUAGE:
2262
          drupal_language_initialize();
2263
          break;
2264

    
2265
        case DRUPAL_BOOTSTRAP_FULL:
2266
          require_once DRUPAL_ROOT . '/includes/common.inc';
2267
          _drupal_bootstrap_full();
2268
          break;
2269
      }
2270
    }
2271
  }
2272
  return $stored_phase;
2273
}
2274

    
2275
/**
2276
 * Returns the time zone of the current user.
2277
 */
2278
function drupal_get_user_timezone() {
2279
  global $user;
2280
  if (variable_get('configurable_timezones', 1) && $user->uid && $user->timezone) {
2281
    return $user->timezone;
2282
  }
2283
  else {
2284
    // Ignore PHP strict notice if time zone has not yet been set in the php.ini
2285
    // configuration.
2286
    return variable_get('date_default_timezone', @date_default_timezone_get());
2287
  }
2288
}
2289

    
2290
/**
2291
 * Gets a salt useful for hardening against SQL injection.
2292
 *
2293
 * @return
2294
 *   A salt based on information in settings.php, not in the database.
2295
 */
2296
function drupal_get_hash_salt() {
2297
  global $drupal_hash_salt, $databases;
2298
  // If the $drupal_hash_salt variable is empty, a hash of the serialized
2299
  // database credentials is used as a fallback salt.
2300
  return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
2301
}
2302

    
2303
/**
2304
 * Provides custom PHP error handling.
2305
 *
2306
 * @param $error_level
2307
 *   The level of the error raised.
2308
 * @param $message
2309
 *   The error message.
2310
 * @param $filename
2311
 *   The filename that the error was raised in.
2312
 * @param $line
2313
 *   The line number the error was raised at.
2314
 * @param $context
2315
 *   An array that points to the active symbol table at the point the error
2316
 *   occurred.
2317
 */
2318
function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
2319
  require_once DRUPAL_ROOT . '/includes/errors.inc';
2320
  _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
2321
}
2322

    
2323
/**
2324
 * Provides custom PHP exception handling.
2325
 *
2326
 * Uncaught exceptions are those not enclosed in a try/catch block. They are
2327
 * always fatal: the execution of the script will stop as soon as the exception
2328
 * handler exits.
2329
 *
2330
 * @param $exception
2331
 *   The exception object that was thrown.
2332
 */
2333
function _drupal_exception_handler($exception) {
2334
  require_once DRUPAL_ROOT . '/includes/errors.inc';
2335

    
2336
  try {
2337
    // Log the message to the watchdog and return an error page to the user.
2338
    _drupal_log_error(_drupal_decode_exception($exception), TRUE);
2339
  }
2340
  catch (Exception $exception2) {
2341
    // Another uncaught exception was thrown while handling the first one.
2342
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
2343
    if (error_displayable()) {
2344
      print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
2345
      print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
2346
      print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
2347
    }
2348
  }
2349
}
2350

    
2351
/**
2352
 * Sets up the script environment and loads settings.php.
2353
 */
2354
function _drupal_bootstrap_configuration() {
2355
  // Set the Drupal custom error handler.
2356
  set_error_handler('_drupal_error_handler');
2357
  set_exception_handler('_drupal_exception_handler');
2358

    
2359
  drupal_environment_initialize();
2360
  // Start a page timer:
2361
  timer_start('page');
2362
  // Initialize the configuration, including variables from settings.php.
2363
  drupal_settings_initialize();
2364
}
2365

    
2366
/**
2367
 * Attempts to serve a page from the cache.
2368
 */
2369
function _drupal_bootstrap_page_cache() {
2370
  global $user;
2371

    
2372
  // Allow specifying special cache handlers in settings.php, like
2373
  // using memcached or files for storing cache information.
2374
  require_once DRUPAL_ROOT . '/includes/cache.inc';
2375
  foreach (variable_get('cache_backends', array()) as $include) {
2376
    require_once DRUPAL_ROOT . '/' . $include;
2377
  }
2378
  // Check for a cache mode force from settings.php.
2379
  if (variable_get('page_cache_without_database')) {
2380
    $cache_enabled = TRUE;
2381
  }
2382
  else {
2383
    drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
2384
    $cache_enabled = variable_get('cache');
2385
  }
2386
  drupal_block_denied(ip_address());
2387
  // If there is no session cookie and cache is enabled (or forced), try
2388
  // to serve a cached page.
2389
  if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
2390
    // Make sure there is a user object because its timestamp will be
2391
    // checked, hook_boot might check for anonymous user etc.
2392
    $user = drupal_anonymous_user();
2393
    // Get the page from the cache.
2394
    $cache = drupal_page_get_cache();
2395
    // If there is a cached page, display it.
2396
    if (is_object($cache)) {
2397
      header('X-Drupal-Cache: HIT');
2398
      // Restore the metadata cached with the page.
2399
      $_GET['q'] = $cache->data['path'];
2400
      drupal_set_title($cache->data['title'], PASS_THROUGH);
2401
      date_default_timezone_set(drupal_get_user_timezone());
2402
      // If the skipping of the bootstrap hooks is not enforced, call
2403
      // hook_boot.
2404
      if (variable_get('page_cache_invoke_hooks', TRUE)) {
2405
        bootstrap_invoke_all('boot');
2406
      }
2407
      drupal_serve_page_from_cache($cache);
2408
      // If the skipping of the bootstrap hooks is not enforced, call
2409
      // hook_exit.
2410
      if (variable_get('page_cache_invoke_hooks', TRUE)) {
2411
        bootstrap_invoke_all('exit');
2412
      }
2413
      // We are done.
2414
      exit;
2415
    }
2416
    else {
2417
      header('X-Drupal-Cache: MISS');
2418
    }
2419
  }
2420
}
2421

    
2422
/**
2423
 * Initializes the database system and registers autoload functions.
2424
 */
2425
function _drupal_bootstrap_database() {
2426
  // Redirect the user to the installation script if Drupal has not been
2427
  // installed yet (i.e., if no $databases array has been defined in the
2428
  // settings.php file) and we are not already installing.
2429
  if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
2430
    include_once DRUPAL_ROOT . '/includes/install.inc';
2431
    install_goto('install.php');
2432
  }
2433

    
2434
  // The user agent header is used to pass a database prefix in the request when
2435
  // running tests. However, for security reasons, it is imperative that we
2436
  // validate we ourselves made the request.
2437
  if ($test_prefix = drupal_valid_test_ua()) {
2438
    // Set the test run id for use in other parts of Drupal.
2439
    $test_info = &$GLOBALS['drupal_test_info'];
2440
    $test_info['test_run_id'] = $test_prefix;
2441
    $test_info['in_child_site'] = TRUE;
2442

    
2443
    foreach ($GLOBALS['databases']['default'] as &$value) {
2444
      // Extract the current default database prefix.
2445
      if (!isset($value['prefix'])) {
2446
        $current_prefix = '';
2447
      }
2448
      elseif (is_array($value['prefix'])) {
2449
        $current_prefix = $value['prefix']['default'];
2450
      }
2451
      else {
2452
        $current_prefix = $value['prefix'];
2453
      }
2454

    
2455
      // Remove the current database prefix and replace it by our own.
2456
      $value['prefix'] = array(
2457
        'default' => $current_prefix . $test_prefix,
2458
      );
2459
    }
2460
  }
2461

    
2462
  // Initialize the database system. Note that the connection
2463
  // won't be initialized until it is actually requested.
2464
  require_once DRUPAL_ROOT . '/includes/database/database.inc';
2465

    
2466
  // Register autoload functions so that we can access classes and interfaces.
2467
  // The database autoload routine comes first so that we can load the database
2468
  // system without hitting the database. That is especially important during
2469
  // the install or upgrade process.
2470
  spl_autoload_register('drupal_autoload_class');
2471
  spl_autoload_register('drupal_autoload_interface');
2472
}
2473

    
2474
/**
2475
 * Loads system variables and all enabled bootstrap modules.
2476
 */
2477
function _drupal_bootstrap_variables() {
2478
  global $conf;
2479

    
2480
  // Initialize the lock system.
2481
  require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
2482
  lock_initialize();
2483

    
2484
  // Load variables from the database, but do not overwrite variables set in settings.php.
2485
  $conf = variable_initialize(isset($conf) ? $conf : array());
2486
  // Load bootstrap modules.
2487
  require_once DRUPAL_ROOT . '/includes/module.inc';
2488
  module_load_all(TRUE);
2489
}
2490

    
2491
/**
2492
 * Invokes hook_boot(), initializes locking system, and sends HTTP headers.
2493
 */
2494
function _drupal_bootstrap_page_header() {
2495
  bootstrap_invoke_all('boot');
2496

    
2497
  if (!drupal_is_cli()) {
2498
    ob_start();
2499
    drupal_page_header();
2500
  }
2501
}
2502

    
2503
/**
2504
 * Returns the current bootstrap phase for this Drupal process.
2505
 *
2506
 * The current phase is the one most recently completed by drupal_bootstrap().
2507
 *
2508
 * @see drupal_bootstrap()
2509
 */
2510
function drupal_get_bootstrap_phase() {
2511
  return drupal_bootstrap();
2512
}
2513

    
2514
/**
2515
 * Returns the test prefix if this is an internal request from SimpleTest.
2516
 *
2517
 * @return
2518
 *   Either the simpletest prefix (the string "simpletest" followed by any
2519
 *   number of digits) or FALSE if the user agent does not contain a valid
2520
 *   HMAC and timestamp.
2521
 */
2522
function drupal_valid_test_ua() {
2523
  // No reason to reset this.
2524
  static $test_prefix;
2525

    
2526
  if (isset($test_prefix)) {
2527
    return $test_prefix;
2528
  }
2529

    
2530
  if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
2531
    list(, $prefix, $time, $salt, $hmac) = $matches;
2532
    $check_string =  $prefix . ';' . $time . ';' . $salt;
2533
    // We use the salt from settings.php to make the HMAC key, since
2534
    // the database is not yet initialized and we can't access any Drupal variables.
2535
    // The file properties add more entropy not easily accessible to others.
2536
    $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
2537
    $time_diff = REQUEST_TIME - $time;
2538
    // Since we are making a local request a 5 second time window is allowed,
2539
    // and the HMAC must match.
2540
    if ($time_diff >= 0 && $time_diff <= 5 && $hmac == drupal_hmac_base64($check_string, $key)) {
2541
      $test_prefix = $prefix;
2542
      return $test_prefix;
2543
    }
2544
  }
2545

    
2546
  $test_prefix = FALSE;
2547
  return $test_prefix;
2548
}
2549

    
2550
/**
2551
 * Generates a user agent string with a HMAC and timestamp for simpletest.
2552
 */
2553
function drupal_generate_test_ua($prefix) {
2554
  static $key;
2555

    
2556
  if (!isset($key)) {
2557
    // We use the salt from settings.php to make the HMAC key, since
2558
    // the database is not yet initialized and we can't access any Drupal variables.
2559
    // The file properties add more entropy not easily accessible to others.
2560
    $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
2561
  }
2562
  // Generate a moderately secure HMAC based on the database credentials.
2563
  $salt = uniqid('', TRUE);
2564
  $check_string = $prefix . ';' . time() . ';' . $salt;
2565
  return $check_string . ';' . drupal_hmac_base64($check_string, $key);
2566
}
2567

    
2568
/**
2569
 * Enables use of the theme system without requiring database access.
2570
 *
2571
 * Loads and initializes the theme system for site installs, updates and when
2572
 * the site is in maintenance mode. This also applies when the database fails.
2573
 *
2574
 * @see _drupal_maintenance_theme()
2575
 */
2576
function drupal_maintenance_theme() {
2577
  require_once DRUPAL_ROOT . '/includes/theme.maintenance.inc';
2578
  _drupal_maintenance_theme();
2579
}
2580

    
2581
/**
2582
 * Returns a simple 404 Not Found page.
2583
 *
2584
 * If fast 404 pages are enabled, and this is a matching page then print a
2585
 * simple 404 page and exit.
2586
 *
2587
 * This function is called from drupal_deliver_html_page() at the time when a
2588
 * a normal 404 page is generated, but it can also optionally be called directly
2589
 * from settings.php to prevent a Drupal bootstrap on these pages. See
2590
 * documentation in settings.php for the benefits and drawbacks of using this.
2591
 *
2592
 * Paths to dynamically-generated content, such as image styles, should also be
2593
 * accounted for in this function.
2594
 */
2595
function drupal_fast_404() {
2596
  $exclude_paths = variable_get('404_fast_paths_exclude', FALSE);
2597
  if ($exclude_paths && !preg_match($exclude_paths, $_GET['q'])) {
2598
    $fast_paths = variable_get('404_fast_paths', FALSE);
2599
    if ($fast_paths && preg_match($fast_paths, $_GET['q'])) {
2600
      drupal_add_http_header('Status', '404 Not Found');
2601
      $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>');
2602
      // Replace @path in the variable with the page path.
2603
      print strtr($fast_404_html, array('@path' => check_plain(request_uri())));
2604
      exit;
2605
    }
2606
  }
2607
}
2608

    
2609
/**
2610
 * Returns TRUE if a Drupal installation is currently being attempted.
2611
 */
2612
function drupal_installation_attempted() {
2613
  return defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install';
2614
}
2615

    
2616
/**
2617
 * Returns the name of the proper localization function.
2618
 *
2619
 * get_t() exists to support localization for code that might run during
2620
 * the installation phase, when some elements of the system might not have
2621
 * loaded.
2622
 *
2623
 * This would include implementations of hook_install(), which could run
2624
 * during the Drupal installation phase, and might also be run during
2625
 * non-installation time, such as while installing the module from the the
2626
 * module administration page.
2627
 *
2628
 * Example usage:
2629
 * @code
2630
 *   $t = get_t();
2631
 *   $translated = $t('translate this');
2632
 * @endcode
2633
 *
2634
 * Use t() if your code will never run during the Drupal installation phase.
2635
 * Use st() if your code will only run during installation and never any other
2636
 * time. Use get_t() if your code could run in either circumstance.
2637
 *
2638
 * @see t()
2639
 * @see st()
2640
 * @ingroup sanitization
2641
 */
2642
function get_t() {
2643
  static $t;
2644
  // This is not converted to drupal_static because there is no point in
2645
  // resetting this as it can not change in the course of a request.
2646
  if (!isset($t)) {
2647
    $t = drupal_installation_attempted() ? 'st' : 't';
2648
  }
2649
  return $t;
2650
}
2651

    
2652
/**
2653
 * Initializes all the defined language types.
2654
 */
2655
function drupal_language_initialize() {
2656
  $types = language_types();
2657

    
2658
  // Ensure the language is correctly returned, even without multilanguage
2659
  // support. Also make sure we have a $language fallback, in case a language
2660
  // negotiation callback needs to do a full bootstrap.
2661
  // Useful for eg. XML/HTML 'lang' attributes.
2662
  $default = language_default();
2663
  foreach ($types as $type) {
2664
    $GLOBALS[$type] = $default;
2665
  }
2666
  if (drupal_multilingual()) {
2667
    include_once DRUPAL_ROOT . '/includes/language.inc';
2668
    foreach ($types as $type) {
2669
      $GLOBALS[$type] = language_initialize($type);
2670
    }
2671
    // Allow modules to react on language system initialization in multilingual
2672
    // environments.
2673
    bootstrap_invoke_all('language_init');
2674
  }
2675
}
2676

    
2677
/**
2678
 * Returns a list of the built-in language types.
2679
 *
2680
 * @return
2681
 *   An array of key-values pairs where the key is the language type and the
2682
 *   value is its configurability.
2683
 */
2684
function drupal_language_types() {
2685
  return array(
2686
    LANGUAGE_TYPE_INTERFACE => TRUE,
2687
    LANGUAGE_TYPE_CONTENT => FALSE,
2688
    LANGUAGE_TYPE_URL => FALSE,
2689
  );
2690
}
2691

    
2692
/**
2693
 * Returns TRUE if there is more than one language enabled.
2694
 *
2695
 * @return
2696
 *   TRUE if more than one language is enabled.
2697
 */
2698
function drupal_multilingual() {
2699
  // The "language_count" variable stores the number of enabled languages to
2700
  // avoid unnecessarily querying the database when building the list of
2701
  // enabled languages on monolingual sites.
2702
  return variable_get('language_count', 1) > 1;
2703
}
2704

    
2705
/**
2706
 * Returns an array of the available language types.
2707
 *
2708
 * @return
2709
 *   An array of all language types where the keys of each are the language type
2710
 *   name and its value is its configurability (TRUE/FALSE).
2711
 */
2712
function language_types() {
2713
  return array_keys(variable_get('language_types', drupal_language_types()));
2714
}
2715

    
2716
/**
2717
 * Returns a list of installed languages, indexed by the specified key.
2718
 *
2719
 * @param $field
2720
 *   (optional) The field to index the list with.
2721
 *
2722
 * @return
2723
 *   An associative array, keyed on the values of $field.
2724
 *   - If $field is 'weight' or 'enabled', the array is nested, with the outer
2725
 *     array's values each being associative arrays with language codes as
2726
 *     keys and language objects as values.
2727
 *   - For all other values of $field, the array is only one level deep, and
2728
 *     the array's values are language objects.
2729
 */
2730
function language_list($field = 'language') {
2731
  $languages = &drupal_static(__FUNCTION__);
2732
  // Init language list
2733
  if (!isset($languages)) {
2734
    if (drupal_multilingual() || module_exists('locale')) {
2735
      $languages['language'] = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC')->fetchAllAssoc('language');
2736
      // Users cannot uninstall the native English language. However, we allow
2737
      // it to be hidden from the installed languages. Therefore, at least one
2738
      // other language must be enabled then.
2739
      if (!$languages['language']['en']->enabled && !variable_get('language_native_enabled', TRUE)) {
2740
        unset($languages['language']['en']);
2741
      }
2742
    }
2743
    else {
2744
      // No locale module, so use the default language only.
2745
      $default = language_default();
2746
      $languages['language'][$default->language] = $default;
2747
    }
2748
  }
2749

    
2750
  // Return the array indexed by the right field
2751
  if (!isset($languages[$field])) {
2752
    $languages[$field] = array();
2753
    foreach ($languages['language'] as $lang) {
2754
      // Some values should be collected into an array
2755
      if (in_array($field, array('enabled', 'weight'))) {
2756
        $languages[$field][$lang->$field][$lang->language] = $lang;
2757
      }
2758
      else {
2759
        $languages[$field][$lang->$field] = $lang;
2760
      }
2761
    }
2762
  }
2763
  return $languages[$field];
2764
}
2765

    
2766
/**
2767
 * Returns the default language used on the site
2768
 *
2769
 * @param $property
2770
 *   Optional property of the language object to return
2771
 */
2772
function language_default($property = NULL) {
2773
  $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' => ''));
2774
  return $property ? $language->$property : $language;
2775
}
2776

    
2777
/**
2778
 * Returns the requested URL path of the page being viewed.
2779
 *
2780
 * Examples:
2781
 * - http://example.com/node/306 returns "node/306".
2782
 * - http://example.com/drupalfolder/node/306 returns "node/306" while
2783
 *   base_path() returns "/drupalfolder/".
2784
 * - http://example.com/path/alias (which is a path alias for node/306) returns
2785
 *   "path/alias" as opposed to the internal path.
2786
 * - http://example.com/index.php returns an empty string (meaning: front page).
2787
 * - http://example.com/index.php?page=1 returns an empty string.
2788
 *
2789
 * @return
2790
 *   The requested Drupal URL path.
2791
 *
2792
 * @see current_path()
2793
 */
2794
function request_path() {
2795
  static $path;
2796

    
2797
  if (isset($path)) {
2798
    return $path;
2799
  }
2800

    
2801
  if (isset($_GET['q']) && is_string($_GET['q'])) {
2802
    // This is a request with a ?q=foo/bar query string. $_GET['q'] is
2803
    // overwritten in drupal_path_initialize(), but request_path() is called
2804
    // very early in the bootstrap process, so the original value is saved in
2805
    // $path and returned in later calls.
2806
    $path = $_GET['q'];
2807
  }
2808
  elseif (isset($_SERVER['REQUEST_URI'])) {
2809
    // This request is either a clean URL, or 'index.php', or nonsense.
2810
    // Extract the path from REQUEST_URI.
2811
    $request_path = strtok($_SERVER['REQUEST_URI'], '?');
2812
    $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
2813
    // Unescape and strip $base_path prefix, leaving q without a leading slash.
2814
    $path = substr(urldecode($request_path), $base_path_len + 1);
2815
    // If the path equals the script filename, either because 'index.php' was
2816
    // explicitly provided in the URL, or because the server added it to
2817
    // $_SERVER['REQUEST_URI'] even when it wasn't provided in the URL (some
2818
    // versions of Microsoft IIS do this), the front page should be served.
2819
    if ($path == basename($_SERVER['PHP_SELF'])) {
2820
      $path = '';
2821
    }
2822
  }
2823
  else {
2824
    // This is the front page.
2825
    $path = '';
2826
  }
2827

    
2828
  // Under certain conditions Apache's RewriteRule directive prepends the value
2829
  // assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
2830
  // slash in place, hence we need to normalize $_GET['q'].
2831
  $path = trim($path, '/');
2832

    
2833
  return $path;
2834
}
2835

    
2836
/**
2837
 * Returns a component of the current Drupal path.
2838
 *
2839
 * When viewing a page at the path "admin/structure/types", for example, arg(0)
2840
 * returns "admin", arg(1) returns "structure", and arg(2) returns "types".
2841
 *
2842
 * Avoid use of this function where possible, as resulting code is hard to
2843
 * read. In menu callback functions, attempt to use named arguments. See the
2844
 * explanation in menu.inc for how to construct callbacks that take arguments.
2845
 * When attempting to use this function to load an element from the current
2846
 * path, e.g. loading the node on a node page, use menu_get_object() instead.
2847
 *
2848
 * @param $index
2849
 *   The index of the component, where each component is separated by a '/'
2850
 *   (forward-slash), and where the first component has an index of 0 (zero).
2851
 * @param $path
2852
 *   A path to break into components. Defaults to the path of the current page.
2853
 *
2854
 * @return
2855
 *   The component specified by $index, or NULL if the specified component was
2856
 *   not found. If called without arguments, it returns an array containing all
2857
 *   the components of the current path.
2858
 */
2859
function arg($index = NULL, $path = NULL) {
2860
  // Even though $arguments doesn't need to be resettable for any functional
2861
  // reasons (the result of explode() does not depend on any run-time
2862
  // information), it should be resettable anyway in case a module needs to
2863
  // free up the memory used by it.
2864
  // Use the advanced drupal_static() pattern, since this is called very often.
2865
  static $drupal_static_fast;
2866
  if (!isset($drupal_static_fast)) {
2867
    $drupal_static_fast['arguments'] = &drupal_static(__FUNCTION__);
2868
  }
2869
  $arguments = &$drupal_static_fast['arguments'];
2870

    
2871
  if (!isset($path)) {
2872
    $path = $_GET['q'];
2873
  }
2874
  if (!isset($arguments[$path])) {
2875
    $arguments[$path] = explode('/', $path);
2876
  }
2877
  if (!isset($index)) {
2878
    return $arguments[$path];
2879
  }
2880
  if (isset($arguments[$path][$index])) {
2881
    return $arguments[$path][$index];
2882
  }
2883
}
2884

    
2885
/**
2886
 * Returns the IP address of the client machine.
2887
 *
2888
 * If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
2889
 * instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of
2890
 * the proxy server, and not the client's. The actual header name can be
2891
 * configured by the reverse_proxy_header variable.
2892
 *
2893
 * @return
2894
 *   IP address of client machine, adjusted for reverse proxy and/or cluster
2895
 *   environments.
2896
 */
2897
function ip_address() {
2898
  $ip_address = &drupal_static(__FUNCTION__);
2899

    
2900
  if (!isset($ip_address)) {
2901
    $ip_address = $_SERVER['REMOTE_ADDR'];
2902

    
2903
    if (variable_get('reverse_proxy', 0)) {
2904
      $reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
2905
      if (!empty($_SERVER[$reverse_proxy_header])) {
2906
        // If an array of known reverse proxy IPs is provided, then trust
2907
        // the XFF header if request really comes from one of them.
2908
        $reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
2909

    
2910
        // Turn XFF header into an array.
2911
        $forwarded = explode(',', $_SERVER[$reverse_proxy_header]);
2912

    
2913
        // Trim the forwarded IPs; they may have been delimited by commas and spaces.
2914
        $forwarded = array_map('trim', $forwarded);
2915

    
2916
        // Tack direct client IP onto end of forwarded array.
2917
        $forwarded[] = $ip_address;
2918

    
2919
        // Eliminate all trusted IPs.
2920
        $untrusted = array_diff($forwarded, $reverse_proxy_addresses);
2921

    
2922
        // The right-most IP is the most specific we can trust.
2923
        $ip_address = array_pop($untrusted);
2924
      }
2925
    }
2926
  }
2927

    
2928
  return $ip_address;
2929
}
2930

    
2931
/**
2932
 * @addtogroup schemaapi
2933
 * @{
2934
 */
2935

    
2936
/**
2937
 * Gets the schema definition of a table, or the whole database schema.
2938
 *
2939
 * The returned schema will include any modifications made by any
2940
 * module that implements hook_schema_alter().
2941
 *
2942
 * @param $table
2943
 *   The name of the table. If not given, the schema of all tables is returned.
2944
 * @param $rebuild
2945
 *   If true, the schema will be rebuilt instead of retrieved from the cache.
2946
 */
2947
function drupal_get_schema($table = NULL, $rebuild = FALSE) {
2948
  static $schema;
2949

    
2950
  if ($rebuild || !isset($table)) {
2951
    $schema = drupal_get_complete_schema($rebuild);
2952
  }
2953
  elseif (!isset($schema)) {
2954
    $schema = new SchemaCache();
2955
  }
2956

    
2957
  if (!isset($table)) {
2958
    return $schema;
2959
  }
2960
  if (isset($schema[$table])) {
2961
    return $schema[$table];
2962
  }
2963
  else {
2964
    return FALSE;
2965
  }
2966
}
2967

    
2968
/**
2969
 * Extends DrupalCacheArray to allow for dynamic building of the schema cache.
2970
 */
2971
class SchemaCache extends DrupalCacheArray {
2972

    
2973
  /**
2974
   * Constructs a SchemaCache object.
2975
   */
2976
  public function __construct() {
2977
    // Cache by request method.
2978
    parent::__construct('schema:runtime:' . ($_SERVER['REQUEST_METHOD'] == 'GET'), 'cache');
2979
  }
2980

    
2981
  /**
2982
   * Overrides DrupalCacheArray::resolveCacheMiss().
2983
   */
2984
  protected function resolveCacheMiss($offset) {
2985
    $complete_schema = drupal_get_complete_schema();
2986
    $value = isset($complete_schema[$offset]) ? $complete_schema[$offset] :  NULL;
2987
    $this->storage[$offset] = $value;
2988
    $this->persist($offset);
2989
    return $value;
2990
  }
2991
}
2992

    
2993
/**
2994
 * Gets the whole database schema.
2995
 *
2996
 * The returned schema will include any modifications made by any
2997
 * module that implements hook_schema_alter().
2998
 *
2999
 * @param $rebuild
3000
 *   If true, the schema will be rebuilt instead of retrieved from the cache.
3001
 */
3002
function drupal_get_complete_schema($rebuild = FALSE) {
3003
  static $schema = array();
3004

    
3005
  if (empty($schema) || $rebuild) {
3006
    // Try to load the schema from cache.
3007
    if (!$rebuild && $cached = cache_get('schema')) {
3008
      $schema = $cached->data;
3009
    }
3010
    // Otherwise, rebuild the schema cache.
3011
    else {
3012
      $schema = array();
3013
      // Load the .install files to get hook_schema.
3014
      // On some databases this function may be called before bootstrap has
3015
      // been completed, so we force the functions we need to load just in case.
3016
      if (function_exists('module_load_all_includes')) {
3017
        // This function can be called very early in the bootstrap process, so
3018
        // we force the module_list() cache to be refreshed to ensure that it
3019
        // contains the complete list of modules before we go on to call
3020
        // module_load_all_includes().
3021
        module_list(TRUE);
3022
        module_load_all_includes('install');
3023
      }
3024

    
3025
      require_once DRUPAL_ROOT . '/includes/common.inc';
3026
      // Invoke hook_schema for all modules.
3027
      foreach (module_implements('schema') as $module) {
3028
        // Cast the result of hook_schema() to an array, as a NULL return value
3029
        // would cause array_merge() to set the $schema variable to NULL as well.
3030
        // That would break modules which use $schema further down the line.
3031
        $current = (array) module_invoke($module, 'schema');
3032
        // Set 'module' and 'name' keys for each table, and remove descriptions,
3033
        // as they needlessly slow down cache_get() for every single request.
3034
        _drupal_schema_initialize($current, $module);
3035
        $schema = array_merge($schema, $current);
3036
      }
3037

    
3038
      drupal_alter('schema', $schema);
3039
      // If the schema is empty, avoid saving it: some database engines require
3040
      // the schema to perform queries, and this could lead to infinite loops.
3041
      if (!empty($schema) && (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL)) {
3042
        cache_set('schema', $schema);
3043
      }
3044
      if ($rebuild) {
3045
        cache_clear_all('schema:', 'cache', TRUE);
3046
      }
3047
    }
3048
  }
3049

    
3050
  return $schema;
3051
}
3052

    
3053
/**
3054
 * @} End of "addtogroup schemaapi".
3055
 */
3056

    
3057

    
3058
/**
3059
 * @addtogroup registry
3060
 * @{
3061
 */
3062

    
3063
/**
3064
 * Confirms that an interface is available.
3065
 *
3066
 * This function is rarely called directly. Instead, it is registered as an
3067
 * spl_autoload()  handler, and PHP calls it for us when necessary.
3068
 *
3069
 * @param $interface
3070
 *   The name of the interface to check or load.
3071
 *
3072
 * @return
3073
 *   TRUE if the interface is currently available, FALSE otherwise.
3074
 */
3075
function drupal_autoload_interface($interface) {
3076
  return _registry_check_code('interface', $interface);
3077
}
3078

    
3079
/**
3080
 * Confirms that a class is available.
3081
 *
3082
 * This function is rarely called directly. Instead, it is registered as an
3083
 * spl_autoload()  handler, and PHP calls it for us when necessary.
3084
 *
3085
 * @param $class
3086
 *   The name of the class to check or load.
3087
 *
3088
 * @return
3089
 *   TRUE if the class is currently available, FALSE otherwise.
3090
 */
3091
function drupal_autoload_class($class) {
3092
  return _registry_check_code('class', $class);
3093
}
3094

    
3095
/**
3096
 * Checks for a resource in the registry.
3097
 *
3098
 * @param $type
3099
 *   The type of resource we are looking up, or one of the constants
3100
 *   REGISTRY_RESET_LOOKUP_CACHE or REGISTRY_WRITE_LOOKUP_CACHE, which
3101
 *   signal that we should reset or write the cache, respectively.
3102
 * @param $name
3103
 *   The name of the resource, or NULL if either of the REGISTRY_* constants
3104
 *   is passed in.
3105
 *
3106
 * @return
3107
 *   TRUE if the resource was found, FALSE if not.
3108
 *   NULL if either of the REGISTRY_* constants is passed in as $type.
3109
 */
3110
function _registry_check_code($type, $name = NULL) {
3111
  static $lookup_cache, $cache_update_needed;
3112

    
3113
  if ($type == 'class' && class_exists($name) || $type == 'interface' && interface_exists($name)) {
3114
    return TRUE;
3115
  }
3116

    
3117
  if (!isset($lookup_cache)) {
3118
    $lookup_cache = array();
3119
    if ($cache = cache_get('lookup_cache', 'cache_bootstrap')) {
3120
      $lookup_cache = $cache->data;
3121
    }
3122
  }
3123

    
3124
  // When we rebuild the registry, we need to reset this cache so
3125
  // we don't keep lookups for resources that changed during the rebuild.
3126
  if ($type == REGISTRY_RESET_LOOKUP_CACHE) {
3127
    $cache_update_needed = TRUE;
3128
    $lookup_cache = NULL;
3129
    return;
3130
  }
3131

    
3132
  // Called from drupal_page_footer, we write to permanent storage if there
3133
  // changes to the lookup cache for this request.
3134
  if ($type == REGISTRY_WRITE_LOOKUP_CACHE) {
3135
    if ($cache_update_needed) {
3136
      cache_set('lookup_cache', $lookup_cache, 'cache_bootstrap');
3137
    }
3138
    return;
3139
  }
3140

    
3141
  // $type is either 'interface' or 'class', so we only need the first letter to
3142
  // keep the cache key unique.
3143
  $cache_key = $type[0] . $name;
3144
  if (isset($lookup_cache[$cache_key])) {
3145
    if ($lookup_cache[$cache_key]) {
3146
      require_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
3147
    }
3148
    return (bool) $lookup_cache[$cache_key];
3149
  }
3150

    
3151
  // This function may get called when the default database is not active, but
3152
  // there is no reason we'd ever want to not use the default database for
3153
  // this query.
3154
  $file = Database::getConnection('default', 'default')->query("SELECT filename FROM {registry} WHERE name = :name AND type = :type", array(
3155
      ':name' => $name,
3156
      ':type' => $type,
3157
    ))
3158
    ->fetchField();
3159

    
3160
  // Flag that we've run a lookup query and need to update the cache.
3161
  $cache_update_needed = TRUE;
3162

    
3163
  // Misses are valuable information worth caching, so cache even if
3164
  // $file is FALSE.
3165
  $lookup_cache[$cache_key] = $file;
3166

    
3167
  if ($file) {
3168
    require_once DRUPAL_ROOT . '/' . $file;
3169
    return TRUE;
3170
  }
3171
  else {
3172
    return FALSE;
3173
  }
3174
}
3175

    
3176
/**
3177
 * Rescans all enabled modules and rebuilds the registry.
3178
 *
3179
 * Rescans all code in modules or includes directories, storing the location of
3180
 * each interface or class in the database.
3181
 */
3182
function registry_rebuild() {
3183
  system_rebuild_module_data();
3184
  registry_update();
3185
}
3186

    
3187
/**
3188
 * Updates the registry based on the latest files listed in the database.
3189
 *
3190
 * This function should be used when system_rebuild_module_data() does not need
3191
 * to be called, because it is already known that the list of files in the
3192
 * {system} table matches those in the file system.
3193
 *
3194
 * @return
3195
 *   TRUE if the registry was rebuilt, FALSE if another thread was rebuilding
3196
 *   in parallel and the current thread just waited for completion.
3197
 *
3198
 * @see registry_rebuild()
3199
 */
3200
function registry_update() {
3201
  // install_system_module() calls module_enable() which calls into this
3202
  // function during initial system installation, so the lock system is neither
3203
  // loaded nor does its storage exist yet.
3204
  $in_installer = drupal_installation_attempted();
3205
  if (!$in_installer && !lock_acquire(__FUNCTION__)) {
3206
    // Another request got the lock, wait for it to finish.
3207
    lock_wait(__FUNCTION__);
3208
    return FALSE;
3209
  }
3210

    
3211
  require_once DRUPAL_ROOT . '/includes/registry.inc';
3212
  _registry_update();
3213

    
3214
  if (!$in_installer) {
3215
    lock_release(__FUNCTION__);
3216
  }
3217
  return TRUE;
3218
}
3219

    
3220
/**
3221
 * @} End of "addtogroup registry".
3222
 */
3223

    
3224
/**
3225
 * Provides central static variable storage.
3226
 *
3227
 * All functions requiring a static variable to persist or cache data within
3228
 * a single page request are encouraged to use this function unless it is
3229
 * absolutely certain that the static variable will not need to be reset during
3230
 * the page request. By centralizing static variable storage through this
3231
 * function, other functions can rely on a consistent API for resetting any
3232
 * other function's static variables.
3233
 *
3234
 * Example:
3235
 * @code
3236
 * function language_list($field = 'language') {
3237
 *   $languages = &drupal_static(__FUNCTION__);
3238
 *   if (!isset($languages)) {
3239
 *     // If this function is being called for the first time after a reset,
3240
 *     // query the database and execute any other code needed to retrieve
3241
 *     // information about the supported languages.
3242
 *     ...
3243
 *   }
3244
 *   if (!isset($languages[$field])) {
3245
 *     // If this function is being called for the first time for a particular
3246
 *     // index field, then execute code needed to index the information already
3247
 *     // available in $languages by the desired field.
3248
 *     ...
3249
 *   }
3250
 *   // Subsequent invocations of this function for a particular index field
3251
 *   // skip the above two code blocks and quickly return the already indexed
3252
 *   // information.
3253
 *   return $languages[$field];
3254
 * }
3255
 * function locale_translate_overview_screen() {
3256
 *   // When building the content for the translations overview page, make
3257
 *   // sure to get completely fresh information about the supported languages.
3258
 *   drupal_static_reset('language_list');
3259
 *   ...
3260
 * }
3261
 * @endcode
3262
 *
3263
 * In a few cases, a function can have certainty that there is no legitimate
3264
 * use-case for resetting that function's static variable. This is rare,
3265
 * because when writing a function, it's hard to forecast all the situations in
3266
 * which it will be used. A guideline is that if a function's static variable
3267
 * does not depend on any information outside of the function that might change
3268
 * during a single page request, then it's ok to use the "static" keyword
3269
 * instead of the drupal_static() function.
3270
 *
3271
 * Example:
3272
 * @code
3273
 * function actions_do(...) {
3274
 *   // $stack tracks the number of recursive calls.
3275
 *   static $stack;
3276
 *   $stack++;
3277
 *   if ($stack > variable_get('actions_max_stack', 35)) {
3278
 *     ...
3279
 *     return;
3280
 *   }
3281
 *   ...
3282
 *   $stack--;
3283
 * }
3284
 * @endcode
3285
 *
3286
 * In a few cases, a function needs a resettable static variable, but the
3287
 * function is called many times (100+) during a single page request, so
3288
 * every microsecond of execution time that can be removed from the function
3289
 * counts. These functions can use a more cumbersome, but faster variant of
3290
 * calling drupal_static(). It works by storing the reference returned by
3291
 * drupal_static() in the calling function's own static variable, thereby
3292
 * removing the need to call drupal_static() for each iteration of the function.
3293
 * Conceptually, it replaces:
3294
 * @code
3295
 * $foo = &drupal_static(__FUNCTION__);
3296
 * @endcode
3297
 * with:
3298
 * @code
3299
 * // Unfortunately, this does not work.
3300
 * static $foo = &drupal_static(__FUNCTION__);
3301
 * @endcode
3302
 * However, the above line of code does not work, because PHP only allows static
3303
 * variables to be initializied by literal values, and does not allow static
3304
 * variables to be assigned to references.
3305
 * - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
3306
 * - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
3307
 * The example below shows the syntax needed to work around both limitations.
3308
 * For benchmarks and more information, see http://drupal.org/node/619666.
3309
 *
3310
 * Example:
3311
 * @code
3312
 * function user_access($string, $account = NULL) {
3313
 *   // Use the advanced drupal_static() pattern, since this is called very often.
3314
 *   static $drupal_static_fast;
3315
 *   if (!isset($drupal_static_fast)) {
3316
 *     $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
3317
 *   }
3318
 *   $perm = &$drupal_static_fast['perm'];
3319
 *   ...
3320
 * }
3321
 * @endcode
3322
 *
3323
 * @param $name
3324
 *   Globally unique name for the variable. For a function with only one static,
3325
 *   variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
3326
 *   is recommended. For a function with multiple static variables add a
3327
 *   distinguishing suffix to the function name for each one.
3328
 * @param $default_value
3329
 *   Optional default value.
3330
 * @param $reset
3331
 *   TRUE to reset a specific named variable, or all variables if $name is NULL.
3332
 *   Resetting every variable should only be used, for example, for running
3333
 *   unit tests with a clean environment. Should be used only though via
3334
 *   function drupal_static_reset() and the return value should not be used in
3335
 *   this case.
3336
 *
3337
 * @return
3338
 *   Returns a variable by reference.
3339
 *
3340
 * @see drupal_static_reset()
3341
 */
3342
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
3343
  static $data = array(), $default = array();
3344
  // First check if dealing with a previously defined static variable.
3345
  if (isset($data[$name]) || array_key_exists($name, $data)) {
3346
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
3347
    if ($reset) {
3348
      // Reset pre-existing static variable to its default value.
3349
      $data[$name] = $default[$name];
3350
    }
3351
    return $data[$name];
3352
  }
3353
  // Neither $data[$name] nor $default[$name] static variables exist.
3354
  if (isset($name)) {
3355
    if ($reset) {
3356
      // Reset was called before a default is set and yet a variable must be
3357
      // returned.
3358
      return $data;
3359
    }
3360
    // First call with new non-NULL $name. Initialize a new static variable.
3361
    $default[$name] = $data[$name] = $default_value;
3362
    return $data[$name];
3363
  }
3364
  // Reset all: ($name == NULL). This needs to be done one at a time so that
3365
  // references returned by earlier invocations of drupal_static() also get
3366
  // reset.
3367
  foreach ($default as $name => $value) {
3368
    $data[$name] = $value;
3369
  }
3370
  // As the function returns a reference, the return should always be a
3371
  // variable.
3372
  return $data;
3373
}
3374

    
3375
/**
3376
 * Resets one or all centrally stored static variable(s).
3377
 *
3378
 * @param $name
3379
 *   Name of the static variable to reset. Omit to reset all variables.
3380
 */
3381
function drupal_static_reset($name = NULL) {
3382
  drupal_static($name, NULL, TRUE);
3383
}
3384

    
3385
/**
3386
 * Detects whether the current script is running in a command-line environment.
3387
 */
3388
function drupal_is_cli() {
3389
  return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
3390
}
3391

    
3392
/**
3393
 * Formats text for emphasized display in a placeholder inside a sentence.
3394
 *
3395
 * Used automatically by format_string().
3396
 *
3397
 * @param $text
3398
 *   The text to format (plain-text).
3399
 *
3400
 * @return
3401
 *   The formatted text (html).
3402
 */
3403
function drupal_placeholder($text) {
3404
  return '<em class="placeholder">' . check_plain($text) . '</em>';
3405
}
3406

    
3407
/**
3408
 * Registers a function for execution on shutdown.
3409
 *
3410
 * Wrapper for register_shutdown_function() that catches thrown exceptions to
3411
 * avoid "Exception thrown without a stack frame in Unknown".
3412
 *
3413
 * @param $callback
3414
 *   The shutdown function to register.
3415
 * @param ...
3416
 *   Additional arguments to pass to the shutdown function.
3417
 *
3418
 * @return
3419
 *   Array of shutdown functions to be executed.
3420
 *
3421
 * @see register_shutdown_function()
3422
 * @ingroup php_wrappers
3423
 */
3424
function &drupal_register_shutdown_function($callback = NULL) {
3425
  // We cannot use drupal_static() here because the static cache is reset during
3426
  // batch processing, which breaks batch handling.
3427
  static $callbacks = array();
3428

    
3429
  if (isset($callback)) {
3430
    // Only register the internal shutdown function once.
3431
    if (empty($callbacks)) {
3432
      register_shutdown_function('_drupal_shutdown_function');
3433
    }
3434
    $args = func_get_args();
3435
    array_shift($args);
3436
    // Save callback and arguments
3437
    $callbacks[] = array('callback' => $callback, 'arguments' => $args);
3438
  }
3439
  return $callbacks;
3440
}
3441

    
3442
/**
3443
 * Executes registered shutdown functions.
3444
 */
3445
function _drupal_shutdown_function() {
3446
  $callbacks = &drupal_register_shutdown_function();
3447

    
3448
  // Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
3449
  // was in the normal context of execution.
3450
  chdir(DRUPAL_ROOT);
3451

    
3452
  try {
3453
    while (list($key, $callback) = each($callbacks)) {
3454
      call_user_func_array($callback['callback'], $callback['arguments']);
3455
    }
3456
  }
3457
  catch (Exception $exception) {
3458
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
3459
   require_once DRUPAL_ROOT . '/includes/errors.inc';
3460
   if (error_displayable()) {
3461
      print '<h1>Uncaught exception thrown in shutdown function.</h1>';
3462
      print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
3463
    }
3464
  }
3465
}
3466

    
3467
/**
3468
 * Compares the memory required for an operation to the available memory.
3469
 *
3470
 * @param $required
3471
 *   The memory required for the operation, expressed as a number of bytes with
3472
 *   optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
3473
 *   9mbytes).
3474
 * @param $memory_limit
3475
 *   (optional) The memory limit for the operation, expressed as a number of
3476
 *   bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
3477
 *   6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
3478
 *   memory_limit will be used. Defaults to NULL.
3479
 *
3480
 * @return
3481
 *   TRUE if there is sufficient memory to allow the operation, or FALSE
3482
 *   otherwise.
3483
 */
3484
function drupal_check_memory_limit($required, $memory_limit = NULL) {
3485
  if (!isset($memory_limit)) {
3486
    $memory_limit = ini_get('memory_limit');
3487
  }
3488

    
3489
  // There is sufficient memory if:
3490
  // - No memory limit is set.
3491
  // - The memory limit is set to unlimited (-1).
3492
  // - The memory limit is greater than the memory required for the operation.
3493
  return ((!$memory_limit) || ($memory_limit == -1) || (parse_size($memory_limit) >= parse_size($required)));
3494
}