Projet

Général

Profil

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

root / drupal7 / includes / bootstrap.inc @ 63832e56

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.54');
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
 * A RFC7231 Compliant date.
253
 *
254
 * http://tools.ietf.org/html/rfc7231#section-7.1.1.1
255
 *
256
 * Example: Sun, 06 Nov 1994 08:49:37 GMT
257
 */
258
define('DATE_RFC7231', 'D, d M Y H:i:s \G\M\T');
259

    
260
/**
261
 * Provides a caching wrapper to be used in place of large array structures.
262
 *
263
 * This class should be extended by systems that need to cache large amounts
264
 * of data and have it represented as an array to calling functions. These
265
 * arrays can become very large, so ArrayAccess is used to allow different
266
 * strategies to be used for caching internally (lazy loading, building caches
267
 * over time etc.). This can dramatically reduce the amount of data that needs
268
 * to be loaded from cache backends on each request, and memory usage from
269
 * static caches of that same data.
270
 *
271
 * Note that array_* functions do not work with ArrayAccess. Systems using
272
 * DrupalCacheArray should use this only internally. If providing API functions
273
 * that return the full array, this can be cached separately or returned
274
 * directly. However since DrupalCacheArray holds partial content by design, it
275
 * should be a normal PHP array or otherwise contain the full structure.
276
 *
277
 * Note also that due to limitations in PHP prior to 5.3.4, it is impossible to
278
 * write directly to the contents of nested arrays contained in this object.
279
 * Only writes to the top-level array elements are possible. So if you
280
 * previously had set $object['foo'] = array(1, 2, 'bar' => 'baz'), but later
281
 * want to change the value of 'bar' from 'baz' to 'foobar', you cannot do so
282
 * a targeted write like $object['foo']['bar'] = 'foobar'. Instead, you must
283
 * overwrite the entire top-level 'foo' array with the entire set of new
284
 * values: $object['foo'] = array(1, 2, 'bar' => 'foobar'). Due to this same
285
 * limitation, attempts to create references to any contained data, nested or
286
 * otherwise, will fail silently. So $var = &$object['foo'] will not throw an
287
 * error, and $var will be populated with the contents of $object['foo'], but
288
 * that data will be passed by value, not reference. For more information on
289
 * the PHP limitation, see the note in the official PHP documentation at·
290
 * http://php.net/manual/arrayaccess.offsetget.php on
291
 * ArrayAccess::offsetGet().
292
 *
293
 * By default, the class accounts for caches where calling functions might
294
 * request keys in the array that won't exist even after a cache rebuild. This
295
 * prevents situations where a cache rebuild would be triggered over and over
296
 * due to a 'missing' item. These cases are stored internally as a value of
297
 * NULL. This means that the offsetGet() and offsetExists() methods
298
 * must be overridden if caching an array where the top level values can
299
 * legitimately be NULL, and where $object->offsetExists() needs to correctly
300
 * return (equivalent to array_key_exists() vs. isset()). This should not
301
 * be necessary in the majority of cases.
302
 *
303
 * Classes extending this class must override at least the
304
 * resolveCacheMiss() method to have a working implementation.
305
 *
306
 * offsetSet() is not overridden by this class by default. In practice this
307
 * means that assigning an offset via arrayAccess will only apply while the
308
 * object is in scope and will not be written back to the persistent cache.
309
 * This follows a similar pattern to static vs. persistent caching in
310
 * procedural code. Extending classes may wish to alter this behavior, for
311
 * example by overriding offsetSet() and adding an automatic call to persist().
312
 *
313
 * @see SchemaCache
314
 */
315
abstract class DrupalCacheArray implements ArrayAccess {
316

    
317
  /**
318
   * A cid to pass to cache_set() and cache_get().
319
   */
320
  protected $cid;
321

    
322
  /**
323
   * A bin to pass to cache_set() and cache_get().
324
   */
325
  protected $bin;
326

    
327
  /**
328
   * An array of keys to add to the cache at the end of the request.
329
   */
330
  protected $keysToPersist = array();
331

    
332
  /**
333
   * Storage for the data itself.
334
   */
335
  protected $storage = array();
336

    
337
  /**
338
   * Constructs a DrupalCacheArray object.
339
   *
340
   * @param $cid
341
   *   The cid for the array being cached.
342
   * @param $bin
343
   *   The bin to cache the array.
344
   */
345
  public function __construct($cid, $bin) {
346
    $this->cid = $cid;
347
    $this->bin = $bin;
348

    
349
    if ($cached = cache_get($this->cid, $this->bin)) {
350
     $this->storage = $cached->data;
351
    }
352
  }
353

    
354
  /**
355
   * Implements ArrayAccess::offsetExists().
356
   */
357
  public function offsetExists($offset) {
358
    return $this->offsetGet($offset) !== NULL;
359
  }
360

    
361
  /**
362
   * Implements ArrayAccess::offsetGet().
363
   */
364
  public function offsetGet($offset) {
365
    if (isset($this->storage[$offset]) || array_key_exists($offset, $this->storage)) {
366
      return $this->storage[$offset];
367
    }
368
    else {
369
      return $this->resolveCacheMiss($offset);
370
    }
371
  }
372

    
373
  /**
374
   * Implements ArrayAccess::offsetSet().
375
   */
376
  public function offsetSet($offset, $value) {
377
    $this->storage[$offset] = $value;
378
  }
379

    
380
  /**
381
   * Implements ArrayAccess::offsetUnset().
382
   */
383
  public function offsetUnset($offset) {
384
    unset($this->storage[$offset]);
385
  }
386

    
387
  /**
388
   * Flags an offset value to be written to the persistent cache.
389
   *
390
   * If a value is assigned to a cache object with offsetSet(), by default it
391
   * will not be written to the persistent cache unless it is flagged with this
392
   * method. This allows items to be cached for the duration of a request,
393
   * without necessarily writing back to the persistent cache at the end.
394
   *
395
   * @param $offset
396
   *   The array offset that was requested.
397
   * @param $persist
398
   *   Optional boolean to specify whether the offset should be persisted or
399
   *   not, defaults to TRUE. When called with $persist = FALSE the offset will
400
   *   be unflagged so that it will not be written at the end of the request.
401
   */
402
  protected function persist($offset, $persist = TRUE) {
403
    $this->keysToPersist[$offset] = $persist;
404
  }
405

    
406
  /**
407
   * Resolves a cache miss.
408
   *
409
   * When an offset is not found in the object, this is treated as a cache
410
   * miss. This method allows classes implementing the interface to look up
411
   * the actual value and allow it to be cached.
412
   *
413
   * @param $offset
414
   *   The offset that was requested.
415
   *
416
   * @return
417
   *   The value of the offset, or NULL if no value was found.
418
   */
419
  abstract protected function resolveCacheMiss($offset);
420

    
421
  /**
422
   * Writes a value to the persistent cache immediately.
423
   *
424
   * @param $data
425
   *   The data to write to the persistent cache.
426
   * @param $lock
427
   *   Whether to acquire a lock before writing to cache.
428
   */
429
  protected function set($data, $lock = TRUE) {
430
    // Lock cache writes to help avoid stampedes.
431
    // To implement locking for cache misses, override __construct().
432
    $lock_name = $this->cid . ':' . $this->bin;
433
    if (!$lock || lock_acquire($lock_name)) {
434
      if ($cached = cache_get($this->cid, $this->bin)) {
435
        $data = $cached->data + $data;
436
      }
437
      cache_set($this->cid, $data, $this->bin);
438
      if ($lock) {
439
        lock_release($lock_name);
440
      }
441
    }
442
  }
443

    
444
  /**
445
   * Destructs the DrupalCacheArray object.
446
   */
447
  public function __destruct() {
448
    $data = array();
449
    foreach ($this->keysToPersist as $offset => $persist) {
450
      if ($persist) {
451
        $data[$offset] = $this->storage[$offset];
452
      }
453
    }
454
    if (!empty($data)) {
455
      $this->set($data);
456
    }
457
  }
458
}
459

    
460
/**
461
 * Starts the timer with the specified name.
462
 *
463
 * If you start and stop the same timer multiple times, the measured intervals
464
 * will be accumulated.
465
 *
466
 * @param $name
467
 *   The name of the timer.
468
 */
469
function timer_start($name) {
470
  global $timers;
471

    
472
  $timers[$name]['start'] = microtime(TRUE);
473
  $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
474
}
475

    
476
/**
477
 * Reads the current timer value without stopping the timer.
478
 *
479
 * @param $name
480
 *   The name of the timer.
481
 *
482
 * @return
483
 *   The current timer value in ms.
484
 */
485
function timer_read($name) {
486
  global $timers;
487

    
488
  if (isset($timers[$name]['start'])) {
489
    $stop = microtime(TRUE);
490
    $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
491

    
492
    if (isset($timers[$name]['time'])) {
493
      $diff += $timers[$name]['time'];
494
    }
495
    return $diff;
496
  }
497
  return $timers[$name]['time'];
498
}
499

    
500
/**
501
 * Stops the timer with the specified name.
502
 *
503
 * @param $name
504
 *   The name of the timer.
505
 *
506
 * @return
507
 *   A timer array. The array contains the number of times the timer has been
508
 *   started and stopped (count) and the accumulated timer value in ms (time).
509
 */
510
function timer_stop($name) {
511
  global $timers;
512

    
513
  if (isset($timers[$name]['start'])) {
514
    $stop = microtime(TRUE);
515
    $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
516
    if (isset($timers[$name]['time'])) {
517
      $timers[$name]['time'] += $diff;
518
    }
519
    else {
520
      $timers[$name]['time'] = $diff;
521
    }
522
    unset($timers[$name]['start']);
523
  }
524

    
525
  return $timers[$name];
526
}
527

    
528
/**
529
 * Returns the appropriate configuration directory.
530
 *
531
 * Returns the configuration path based on the site's hostname, port, and
532
 * pathname. See default.settings.php for examples on how the URL is converted
533
 * to a directory.
534
 *
535
 * @param bool $require_settings
536
 *   Only configuration directories with an existing settings.php file
537
 *   will be recognized. Defaults to TRUE. During initial installation,
538
 *   this is set to FALSE so that Drupal can detect a matching directory,
539
 *   then create a new settings.php file in it.
540
 * @param bool $reset
541
 *   Force a full search for matching directories even if one had been
542
 *   found previously. Defaults to FALSE.
543
 *
544
 * @return
545
 *   The path of the matching directory.
546
 *
547
 * @see default.settings.php
548
 */
549
function conf_path($require_settings = TRUE, $reset = FALSE) {
550
  $conf = &drupal_static(__FUNCTION__, '');
551

    
552
  if ($conf && !$reset) {
553
    return $conf;
554
  }
555

    
556
  $confdir = 'sites';
557

    
558
  $sites = array();
559
  if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/sites.php')) {
560
    // This will overwrite $sites with the desired mappings.
561
    include(DRUPAL_ROOT . '/' . $confdir . '/sites.php');
562
  }
563

    
564
  $uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
565
  $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
566
  for ($i = count($uri) - 1; $i > 0; $i--) {
567
    for ($j = count($server); $j > 0; $j--) {
568
      $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
569
      if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $sites[$dir])) {
570
        $dir = $sites[$dir];
571
      }
572
      if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir))) {
573
        $conf = "$confdir/$dir";
574
        return $conf;
575
      }
576
    }
577
  }
578
  $conf = "$confdir/default";
579
  return $conf;
580
}
581

    
582
/**
583
 * Sets appropriate server variables needed for command line scripts to work.
584
 *
585
 * This function can be called by command line scripts before bootstrapping
586
 * Drupal, to ensure that the page loads with the desired server parameters.
587
 * This is because many parts of Drupal assume that they are running in a web
588
 * browser and therefore use information from the global PHP $_SERVER variable
589
 * that does not get set when Drupal is run from the command line.
590
 *
591
 * In many cases, the default way in which this function populates the $_SERVER
592
 * variable is sufficient, and it can therefore be called without passing in
593
 * any input. However, command line scripts running on a multisite installation
594
 * (or on any installation that has settings.php stored somewhere other than
595
 * the sites/default folder) need to pass in the URL of the site to allow
596
 * Drupal to detect the correct location of the settings.php file. Passing in
597
 * the 'url' parameter is also required for functions like request_uri() to
598
 * return the expected values.
599
 *
600
 * Most other parameters do not need to be passed in, but may be necessary in
601
 * some cases; for example, if Drupal's ip_address() function needs to return
602
 * anything but the standard localhost value ('127.0.0.1'), the command line
603
 * script should pass in the desired value via the 'REMOTE_ADDR' key.
604
 *
605
 * @param $variables
606
 *   (optional) An associative array of variables within $_SERVER that should
607
 *   be replaced. If the special element 'url' is provided in this array, it
608
 *   will be used to populate some of the server defaults; it should be set to
609
 *   the URL of the current page request, excluding any $_GET request but
610
 *   including the script name (e.g., http://www.example.com/mysite/index.php).
611
 *
612
 * @see conf_path()
613
 * @see request_uri()
614
 * @see ip_address()
615
 */
616
function drupal_override_server_variables($variables = array()) {
617
  // Allow the provided URL to override any existing values in $_SERVER.
618
  if (isset($variables['url'])) {
619
    $url = parse_url($variables['url']);
620
    if (isset($url['host'])) {
621
      $_SERVER['HTTP_HOST'] = $url['host'];
622
    }
623
    if (isset($url['path'])) {
624
      $_SERVER['SCRIPT_NAME'] = $url['path'];
625
    }
626
    unset($variables['url']);
627
  }
628
  // Define default values for $_SERVER keys. These will be used if $_SERVER
629
  // does not already define them and no other values are passed in to this
630
  // function.
631
  $defaults = array(
632
    'HTTP_HOST' => 'localhost',
633
    'SCRIPT_NAME' => NULL,
634
    'REMOTE_ADDR' => '127.0.0.1',
635
    'REQUEST_METHOD' => 'GET',
636
    'SERVER_NAME' => NULL,
637
    'SERVER_SOFTWARE' => NULL,
638
    'HTTP_USER_AGENT' => NULL,
639
  );
640
  // Replace elements of the $_SERVER array, as appropriate.
641
  $_SERVER = $variables + $_SERVER + $defaults;
642
}
643

    
644
/**
645
 * Initializes the PHP environment.
646
 */
647
function drupal_environment_initialize() {
648
  if (!isset($_SERVER['HTTP_REFERER'])) {
649
    $_SERVER['HTTP_REFERER'] = '';
650
  }
651
  if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
652
    $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
653
  }
654

    
655
  if (isset($_SERVER['HTTP_HOST'])) {
656
    // As HTTP_HOST is user input, ensure it only contains characters allowed
657
    // in hostnames. See RFC 952 (and RFC 2181).
658
    // $_SERVER['HTTP_HOST'] is lowercased here per specifications.
659
    $_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
660
    if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
661
      // HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
662
      header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
663
      exit;
664
    }
665
  }
666
  else {
667
    // Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
668
    // defined for E_ALL compliance.
669
    $_SERVER['HTTP_HOST'] = '';
670
  }
671

    
672
  // When clean URLs are enabled, emulate ?q=foo/bar using REQUEST_URI. It is
673
  // not possible to append the query string using mod_rewrite without the B
674
  // flag (this was added in Apache 2.2.8), because mod_rewrite unescapes the
675
  // path before passing it on to PHP. This is a problem when the path contains
676
  // e.g. "&" or "%" that have special meanings in URLs and must be encoded.
677
  $_GET['q'] = request_path();
678

    
679
  // Enforce E_ALL, but allow users to set levels not part of E_ALL.
680
  error_reporting(E_ALL | error_reporting());
681

    
682
  // Override PHP settings required for Drupal to work properly.
683
  // sites/default/default.settings.php contains more runtime settings.
684
  // The .htaccess file contains settings that cannot be changed at runtime.
685

    
686
  // Don't escape quotes when reading files from the database, disk, etc.
687
  ini_set('magic_quotes_runtime', '0');
688
  // Use session cookies, not transparent sessions that puts the session id in
689
  // the query string.
690
  ini_set('session.use_cookies', '1');
691
  ini_set('session.use_only_cookies', '1');
692
  ini_set('session.use_trans_sid', '0');
693
  // Don't send HTTP headers using PHP's session handler.
694
  // An empty string is used here to disable the cache limiter.
695
  ini_set('session.cache_limiter', '');
696
  // Use httponly session cookies.
697
  ini_set('session.cookie_httponly', '1');
698

    
699
  // Set sane locale settings, to ensure consistent string, dates, times and
700
  // numbers handling.
701
  setlocale(LC_ALL, 'C');
702
}
703

    
704
/**
705
 * Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
706
 *
707
 * @return
708
 *  TRUE if only containing valid characters, or FALSE otherwise.
709
 */
710
function drupal_valid_http_host($host) {
711
  // Limit the length of the host name to 1000 bytes to prevent DoS attacks with
712
  // long host names.
713
  return strlen($host) <= 1000
714
    // Limit the number of subdomains and port separators to prevent DoS attacks
715
    // in conf_path().
716
    && substr_count($host, '.') <= 100
717
    && substr_count($host, ':') <= 100
718
    && preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host);
719
}
720

    
721
/**
722
 * Checks whether an HTTPS request is being served.
723
 *
724
 * @return bool
725
 *   TRUE if the request is HTTPS, FALSE otherwise.
726
 */
727
function drupal_is_https() {
728
  return isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
729
}
730

    
731
/**
732
 * Sets the base URL, cookie domain, and session name from configuration.
733
 */
734
function drupal_settings_initialize() {
735
  global $base_url, $base_path, $base_root;
736

    
737
  // Export these settings.php variables to the global namespace.
738
  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;
739
  $conf = array();
740

    
741
  if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.php')) {
742
    include_once DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
743
  }
744
  $is_https = drupal_is_https();
745

    
746
  if (isset($base_url)) {
747
    // Parse fixed base URL from settings.php.
748
    $parts = parse_url($base_url);
749
    if (!isset($parts['path'])) {
750
      $parts['path'] = '';
751
    }
752
    $base_path = $parts['path'] . '/';
753
    // Build $base_root (everything until first slash after "scheme://").
754
    $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
755
  }
756
  else {
757
    // Create base URL.
758
    $http_protocol = $is_https ? 'https' : 'http';
759
    $base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];
760

    
761
    $base_url = $base_root;
762

    
763
    // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
764
    // be modified by a visitor.
765
    if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
766
      $base_path = $dir;
767
      $base_url .= $base_path;
768
      $base_path .= '/';
769
    }
770
    else {
771
      $base_path = '/';
772
    }
773
  }
774
  $base_secure_url = str_replace('http://', 'https://', $base_url);
775
  $base_insecure_url = str_replace('https://', 'http://', $base_url);
776

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

    
816
/**
817
 * Returns and optionally sets the filename for a system resource.
818
 *
819
 * The filename, whether provided, cached, or retrieved from the database, is
820
 * only returned if the file exists.
821
 *
822
 * This function plays a key role in allowing Drupal's resources (modules
823
 * and themes) to be located in different places depending on a site's
824
 * configuration. For example, a module 'foo' may legally be located
825
 * in any of these three places:
826
 *
827
 * modules/foo/foo.module
828
 * sites/all/modules/foo/foo.module
829
 * sites/example.com/modules/foo/foo.module
830
 *
831
 * Calling drupal_get_filename('module', 'foo') will give you one of
832
 * the above, depending on where the module is located.
833
 *
834
 * @param $type
835
 *   The type of the item (theme, theme_engine, module, profile).
836
 * @param $name
837
 *   The name of the item for which the filename is requested.
838
 * @param $filename
839
 *   The filename of the item if it is to be set explicitly rather
840
 *   than by consulting the database.
841
 * @param bool $trigger_error
842
 *   Whether to trigger an error when a file is missing or has unexpectedly
843
 *   moved. This defaults to TRUE, but can be set to FALSE by calling code that
844
 *   merely wants to check whether an item exists in the filesystem.
845
 *
846
 * @return
847
 *   The filename of the requested item or NULL if the item is not found.
848
 */
849
function drupal_get_filename($type, $name, $filename = NULL, $trigger_error = TRUE) {
850
  // The $files static variable will hold the locations of all requested files.
851
  // We can be sure that any file listed in this static variable actually
852
  // exists as all additions have gone through a file_exists() check.
853
  // The location of files will not change during the request, so do not use
854
  // drupal_static().
855
  static $files = array();
856

    
857
  // Profiles are a special case: they have a fixed location and naming.
858
  if ($type == 'profile') {
859
    $profile_filename = "profiles/$name/$name.profile";
860
    $files[$type][$name] = file_exists($profile_filename) ? $profile_filename : FALSE;
861
  }
862
  if (!isset($files[$type])) {
863
    $files[$type] = array();
864
  }
865

    
866
  if (!empty($filename) && file_exists($filename)) {
867
    // Prime the static cache with the provided filename.
868
    $files[$type][$name] = $filename;
869
  }
870
  elseif (isset($files[$type][$name])) {
871
    // This item had already been found earlier in the request, either through
872
    // priming of the static cache (for example, in system_list()), through a
873
    // lookup in the {system} table, or through a file scan (cached or not). Do
874
    // nothing.
875
  }
876
  else {
877
    // Look for the filename listed in the {system} table. Verify that we have
878
    // an active database connection before doing so, since this function is
879
    // called both before we have a database connection (i.e. during
880
    // installation) and when a database connection fails.
881
    $database_unavailable = TRUE;
882
    try {
883
      if (function_exists('db_query')) {
884
        $file = db_query("SELECT filename FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
885
        if ($file !== FALSE && file_exists(DRUPAL_ROOT . '/' . $file)) {
886
          $files[$type][$name] = $file;
887
        }
888
        $database_unavailable = FALSE;
889
      }
890
    }
891
    catch (Exception $e) {
892
      // The database table may not exist because Drupal is not yet installed,
893
      // the database might be down, or we may have done a non-database cache
894
      // flush while $conf['page_cache_without_database'] = TRUE and
895
      // $conf['page_cache_invoke_hooks'] = TRUE. We have a fallback for these
896
      // cases so we hide the error completely.
897
    }
898
    // Fall back to searching the filesystem if the database could not find the
899
    // file or the file does not exist at the path returned by the database.
900
    if (!isset($files[$type][$name])) {
901
      $files[$type][$name] = _drupal_get_filename_fallback($type, $name, $trigger_error, $database_unavailable);
902
    }
903
  }
904

    
905
  if (isset($files[$type][$name])) {
906
    return $files[$type][$name];
907
  }
908
}
909

    
910
/**
911
 * Performs a cached file system scan as a fallback when searching for a file.
912
 *
913
 * This function looks for the requested file by triggering a file scan,
914
 * caching the new location if the file has moved and caching the miss
915
 * if the file is missing. If a file had been marked as missing in a previous
916
 * file scan, or if it has been marked as moved and is still in the last known
917
 * location, no new file scan will be performed.
918
 *
919
 * @param string $type
920
 *   The type of the item (theme, theme_engine, module, profile).
921
 * @param string $name
922
 *   The name of the item for which the filename is requested.
923
 * @param bool $trigger_error
924
 *   Whether to trigger an error when a file is missing or has unexpectedly
925
 *   moved.
926
 * @param bool $database_unavailable
927
 *   Whether this function is being called because the Drupal database could
928
 *   not be queried for the file's location.
929
 *
930
 * @return
931
 *   The filename of the requested item or NULL if the item is not found.
932
 *
933
 * @see drupal_get_filename()
934
 */
935
function _drupal_get_filename_fallback($type, $name, $trigger_error, $database_unavailable) {
936
  $file_scans = &_drupal_file_scan_cache();
937
  $filename = NULL;
938

    
939
  // If the cache indicates that the item is missing, or we can verify that the
940
  // item exists in the location the cache says it exists in, use that.
941
  if (isset($file_scans[$type][$name]) && ($file_scans[$type][$name] === FALSE || file_exists($file_scans[$type][$name]))) {
942
    $filename = $file_scans[$type][$name];
943
  }
944
  // Otherwise, perform a new file scan to find the item.
945
  else {
946
    $filename = _drupal_get_filename_perform_file_scan($type, $name);
947
    // Update the static cache, and mark the persistent cache for updating at
948
    // the end of the page request. See drupal_file_scan_write_cache().
949
    $file_scans[$type][$name] = $filename;
950
    $file_scans['#write_cache'] = TRUE;
951
  }
952

    
953
  // If requested, trigger a user-level warning about the missing or
954
  // unexpectedly moved file. If the database was unavailable, do not trigger a
955
  // warning in the latter case, though, since if the {system} table could not
956
  // be queried there is no way to know if the location found here was
957
  // "unexpected" or not.
958
  if ($trigger_error) {
959
    $error_type = $filename === FALSE ? 'missing' : 'moved';
960
    if ($error_type == 'missing' || !$database_unavailable) {
961
      _drupal_get_filename_fallback_trigger_error($type, $name, $error_type);
962
    }
963
  }
964

    
965
  // The cache stores FALSE for files that aren't found (to be able to
966
  // distinguish them from files that have not yet been searched for), but
967
  // drupal_get_filename() expects NULL for these instead, so convert to NULL
968
  // before returning.
969
  if ($filename === FALSE) {
970
    $filename = NULL;
971
  }
972
  return $filename;
973
}
974

    
975
/**
976
 * Returns the current list of cached file system scan results.
977
 *
978
 * @return
979
 *   An associative array tracking the most recent file scan results for all
980
 *   files that have had scans performed. The keys are the type and name of the
981
 *   item that was searched for, and the values can be either:
982
 *   - Boolean FALSE if the item was not found in the file system.
983
 *   - A string pointing to the location where the item was found.
984
 */
985
function &_drupal_file_scan_cache() {
986
  $file_scans = &drupal_static(__FUNCTION__, array());
987

    
988
  // The file scan results are stored in a persistent cache (in addition to the
989
  // static cache) but because this function can be called before the
990
  // persistent cache is available, we must merge any items that were found
991
  // earlier in the page request into the results from the persistent cache.
992
  if (!isset($file_scans['#cache_merge_done'])) {
993
    try {
994
      if (function_exists('cache_get')) {
995
        $cache = cache_get('_drupal_file_scan_cache', 'cache_bootstrap');
996
        if (!empty($cache->data)) {
997
          // File scan results from the current request should take precedence
998
          // over the results from the persistent cache, since they are newer.
999
          $file_scans = drupal_array_merge_deep($cache->data, $file_scans);
1000
        }
1001
        // Set a flag to indicate that the persistent cache does not need to be
1002
        // merged again.
1003
        $file_scans['#cache_merge_done'] = TRUE;
1004
      }
1005
    }
1006
    catch (Exception $e) {
1007
      // Hide the error.
1008
    }
1009
  }
1010

    
1011
  return $file_scans;
1012
}
1013

    
1014
/**
1015
 * Performs a file system scan to search for a system resource.
1016
 *
1017
 * @param $type
1018
 *   The type of the item (theme, theme_engine, module, profile).
1019
 * @param $name
1020
 *   The name of the item for which the filename is requested.
1021
 *
1022
 * @return
1023
 *   The filename of the requested item or FALSE if the item is not found.
1024
 *
1025
 * @see drupal_get_filename()
1026
 * @see _drupal_get_filename_fallback()
1027
 */
1028
function _drupal_get_filename_perform_file_scan($type, $name) {
1029
  // The location of files will not change during the request, so do not use
1030
  // drupal_static().
1031
  static $dirs = array(), $files = array();
1032

    
1033
  // We have a consistent directory naming: modules, themes...
1034
  $dir = $type . 's';
1035
  if ($type == 'theme_engine') {
1036
    $dir = 'themes/engines';
1037
    $extension = 'engine';
1038
  }
1039
  elseif ($type == 'theme') {
1040
    $extension = 'info';
1041
  }
1042
  else {
1043
    $extension = $type;
1044
  }
1045

    
1046
  // Check if we had already scanned this directory/extension combination.
1047
  if (!isset($dirs[$dir][$extension])) {
1048
    // Log that we have now scanned this directory/extension combination
1049
    // into a static variable so as to prevent unnecessary file scans.
1050
    $dirs[$dir][$extension] = TRUE;
1051
    if (!function_exists('drupal_system_listing')) {
1052
      require_once DRUPAL_ROOT . '/includes/common.inc';
1053
    }
1054
    // Scan the appropriate directories for all files with the requested
1055
    // extension, not just the file we are currently looking for. This
1056
    // prevents unnecessary scans from being repeated when this function is
1057
    // called more than once in the same page request.
1058
    $matches = drupal_system_listing("/^" . DRUPAL_PHP_FUNCTION_PATTERN . "\.$extension$/", $dir, 'name', 0);
1059
    foreach ($matches as $matched_name => $file) {
1060
      // Log the locations found in the file scan into a static variable.
1061
      $files[$type][$matched_name] = $file->uri;
1062
    }
1063
  }
1064

    
1065
  // Return the results of the file system scan, or FALSE to indicate the file
1066
  // was not found.
1067
  return isset($files[$type][$name]) ? $files[$type][$name] : FALSE;
1068
}
1069

    
1070
/**
1071
 * Triggers a user-level warning for missing or unexpectedly moved files.
1072
 *
1073
 * @param $type
1074
 *   The type of the item (theme, theme_engine, module, profile).
1075
 * @param $name
1076
 *   The name of the item for which the filename is requested.
1077
 * @param $error_type
1078
 *   The type of the error ('missing' or 'moved').
1079
 *
1080
 * @see drupal_get_filename()
1081
 * @see _drupal_get_filename_fallback()
1082
 */
1083
function _drupal_get_filename_fallback_trigger_error($type, $name, $error_type) {
1084
  // Hide messages due to known bugs that will appear on a lot of sites.
1085
  // @todo Remove this in https://www.drupal.org/node/2383823
1086
  if (empty($name)) {
1087
    return;
1088
  }
1089

    
1090
  // Make sure we only show any missing or moved file errors only once per
1091
  // request.
1092
  static $errors_triggered = array();
1093
  if (empty($errors_triggered[$type][$name][$error_type])) {
1094
    // Use _drupal_trigger_error_with_delayed_logging() here since these are
1095
    // triggered during low-level operations that cannot necessarily be
1096
    // interrupted by a watchdog() call.
1097
    if ($error_type == 'missing') {
1098
      _drupal_trigger_error_with_delayed_logging(format_string('The following @type is missing from the file system: %name. For information about how to fix this, see <a href="@documentation">the documentation page</a>.', array('@type' => $type, '%name' => $name, '@documentation' => 'https://www.drupal.org/node/2487215')), E_USER_WARNING);
1099
    }
1100
    elseif ($error_type == 'moved') {
1101
      _drupal_trigger_error_with_delayed_logging(format_string('The following @type has moved within the file system: %name. In order to fix this, clear caches or put the @type back in its original location. For more information, see <a href="@documentation">the documentation page</a>.', array('@type' => $type, '%name' => $name, '@documentation' => 'https://www.drupal.org/node/2487215')), E_USER_WARNING);
1102
    }
1103
    $errors_triggered[$type][$name][$error_type] = TRUE;
1104
  }
1105
}
1106

    
1107
/**
1108
 * Invokes trigger_error() with logging delayed until the end of the request.
1109
 *
1110
 * This is an alternative to PHP's trigger_error() function which can be used
1111
 * during low-level Drupal core operations that need to avoid being interrupted
1112
 * by a watchdog() call.
1113
 *
1114
 * Normally, Drupal's error handler calls watchdog() in response to a
1115
 * trigger_error() call. However, this invokes hook_watchdog() which can run
1116
 * arbitrary code. If the trigger_error() happens in the middle of an
1117
 * operation such as a rebuild operation which should not be interrupted by
1118
 * arbitrary code, that could potentially break or trigger the rebuild again.
1119
 * This function protects against that by delaying the watchdog() call until
1120
 * the end of the current page request.
1121
 *
1122
 * This is an internal function which should only be called by low-level Drupal
1123
 * core functions. It may be removed in a future Drupal 7 release.
1124
 *
1125
 * @param string $error_msg
1126
 *   The error message to trigger. As with trigger_error() itself, this is
1127
 *   limited to 1024 bytes; additional characters beyond that will be removed.
1128
 * @param int $error_type
1129
 *   (optional) The type of error. This should be one of the E_USER family of
1130
 *   constants. As with trigger_error() itself, this defaults to E_USER_NOTICE
1131
 *   if not provided.
1132
 *
1133
 * @see _drupal_log_error()
1134
 */
1135
function _drupal_trigger_error_with_delayed_logging($error_msg, $error_type = E_USER_NOTICE) {
1136
  $delay_logging = &drupal_static(__FUNCTION__, FALSE);
1137
  $delay_logging = TRUE;
1138
  trigger_error($error_msg, $error_type);
1139
  $delay_logging = FALSE;
1140
}
1141

    
1142
/**
1143
 * Writes the file scan cache to the persistent cache.
1144
 *
1145
 * This cache stores all files marked as missing or moved after a file scan
1146
 * to prevent unnecessary file scans in subsequent requests. This cache is
1147
 * cleared in system_list_reset() (i.e. after a module/theme rebuild).
1148
 */
1149
function drupal_file_scan_write_cache() {
1150
  // Only write to the persistent cache if requested, and if we know that any
1151
  // data previously in the cache was successfully loaded and merged in by
1152
  // _drupal_file_scan_cache().
1153
  $file_scans = &_drupal_file_scan_cache();
1154
  if (isset($file_scans['#write_cache']) && isset($file_scans['#cache_merge_done'])) {
1155
    unset($file_scans['#write_cache']);
1156
    cache_set('_drupal_file_scan_cache', $file_scans, 'cache_bootstrap');
1157
  }
1158
}
1159

    
1160
/**
1161
 * Loads the persistent variable table.
1162
 *
1163
 * The variable table is composed of values that have been saved in the table
1164
 * with variable_set() as well as those explicitly specified in the
1165
 * configuration file.
1166
 */
1167
function variable_initialize($conf = array()) {
1168
  // NOTE: caching the variables improves performance by 20% when serving
1169
  // cached pages.
1170
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
1171
    $variables = $cached->data;
1172
  }
1173
  else {
1174
    // Cache miss. Avoid a stampede.
1175
    $name = 'variable_init';
1176
    if (!lock_acquire($name, 1)) {
1177
      // Another request is building the variable cache.
1178
      // Wait, then re-run this function.
1179
      lock_wait($name);
1180
      return variable_initialize($conf);
1181
    }
1182
    else {
1183
      // Proceed with variable rebuild.
1184
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
1185
      cache_set('variables', $variables, 'cache_bootstrap');
1186
      lock_release($name);
1187
    }
1188
  }
1189

    
1190
  foreach ($conf as $name => $value) {
1191
    $variables[$name] = $value;
1192
  }
1193

    
1194
  return $variables;
1195
}
1196

    
1197
/**
1198
 * Returns a persistent variable.
1199
 *
1200
 * Case-sensitivity of the variable_* functions depends on the database
1201
 * collation used. To avoid problems, always use lower case for persistent
1202
 * variable names.
1203
 *
1204
 * @param $name
1205
 *   The name of the variable to return.
1206
 * @param $default
1207
 *   The default value to use if this variable has never been set.
1208
 *
1209
 * @return
1210
 *   The value of the variable. Unserialization is taken care of as necessary.
1211
 *
1212
 * @see variable_del()
1213
 * @see variable_set()
1214
 */
1215
function variable_get($name, $default = NULL) {
1216
  global $conf;
1217

    
1218
  return isset($conf[$name]) ? $conf[$name] : $default;
1219
}
1220

    
1221
/**
1222
 * Sets a persistent variable.
1223
 *
1224
 * Case-sensitivity of the variable_* functions depends on the database
1225
 * collation used. To avoid problems, always use lower case for persistent
1226
 * variable names.
1227
 *
1228
 * @param $name
1229
 *   The name of the variable to set.
1230
 * @param $value
1231
 *   The value to set. This can be any PHP data type; these functions take care
1232
 *   of serialization as necessary.
1233
 *
1234
 * @see variable_del()
1235
 * @see variable_get()
1236
 */
1237
function variable_set($name, $value) {
1238
  global $conf;
1239

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

    
1242
  cache_clear_all('variables', 'cache_bootstrap');
1243

    
1244
  $conf[$name] = $value;
1245
}
1246

    
1247
/**
1248
 * Unsets a persistent variable.
1249
 *
1250
 * Case-sensitivity of the variable_* functions depends on the database
1251
 * collation used. To avoid problems, always use lower case for persistent
1252
 * variable names.
1253
 *
1254
 * @param $name
1255
 *   The name of the variable to undefine.
1256
 *
1257
 * @see variable_get()
1258
 * @see variable_set()
1259
 */
1260
function variable_del($name) {
1261
  global $conf;
1262

    
1263
  db_delete('variable')
1264
    ->condition('name', $name)
1265
    ->execute();
1266
  cache_clear_all('variables', 'cache_bootstrap');
1267

    
1268
  unset($conf[$name]);
1269
}
1270

    
1271
/**
1272
 * Retrieves the current page from the cache.
1273
 *
1274
 * Note: we do not serve cached pages to authenticated users, or to anonymous
1275
 * users when $_SESSION is non-empty. $_SESSION may contain status messages
1276
 * from a form submission, the contents of a shopping cart, or other user-
1277
 * specific content that should not be cached and displayed to other users.
1278
 *
1279
 * @param $check_only
1280
 *   (optional) Set to TRUE to only return whether a previous call found a
1281
 *   cache entry.
1282
 *
1283
 * @return
1284
 *   The cache object, if the page was found in the cache, NULL otherwise.
1285
 */
1286
function drupal_page_get_cache($check_only = FALSE) {
1287
  global $base_root;
1288
  static $cache_hit = FALSE;
1289

    
1290
  if ($check_only) {
1291
    return $cache_hit;
1292
  }
1293

    
1294
  if (drupal_page_is_cacheable()) {
1295
    $cache = cache_get($base_root . request_uri(), 'cache_page');
1296
    if ($cache !== FALSE) {
1297
      $cache_hit = TRUE;
1298
    }
1299
    return $cache;
1300
  }
1301
}
1302

    
1303
/**
1304
 * Determines the cacheability of the current page.
1305
 *
1306
 * @param $allow_caching
1307
 *   Set to FALSE if you want to prevent this page from being cached.
1308
 *
1309
 * @return
1310
 *   TRUE if the current page can be cached, FALSE otherwise.
1311
 */
1312
function drupal_page_is_cacheable($allow_caching = NULL) {
1313
  $allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
1314
  if (isset($allow_caching)) {
1315
    $allow_caching_static = $allow_caching;
1316
  }
1317

    
1318
  return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
1319
    && !drupal_is_cli();
1320
}
1321

    
1322
/**
1323
 * Invokes a bootstrap hook in all bootstrap modules that implement it.
1324
 *
1325
 * @param $hook
1326
 *   The name of the bootstrap hook to invoke.
1327
 *
1328
 * @see bootstrap_hooks()
1329
 */
1330
function bootstrap_invoke_all($hook) {
1331
  // Bootstrap modules should have been loaded when this function is called, so
1332
  // we don't need to tell module_list() to reset its internal list (and we
1333
  // therefore leave the first parameter at its default value of FALSE). We
1334
  // still pass in TRUE for the second parameter, though; in case this is the
1335
  // first time during the bootstrap that module_list() is called, we want to
1336
  // make sure that its internal cache is primed with the bootstrap modules
1337
  // only.
1338
  foreach (module_list(FALSE, TRUE) as $module) {
1339
    drupal_load('module', $module);
1340
    module_invoke($module, $hook);
1341
  }
1342
}
1343

    
1344
/**
1345
 * Includes a file with the provided type and name.
1346
 *
1347
 * This prevents including a theme, engine, module, etc., more than once.
1348
 *
1349
 * @param $type
1350
 *   The type of item to load (i.e. theme, theme_engine, module).
1351
 * @param $name
1352
 *   The name of the item to load.
1353
 *
1354
 * @return
1355
 *   TRUE if the item is loaded or has already been loaded.
1356
 */
1357
function drupal_load($type, $name) {
1358
  // Once a file is included this can't be reversed during a request so do not
1359
  // use drupal_static() here.
1360
  static $files = array();
1361

    
1362
  if (isset($files[$type][$name])) {
1363
    return TRUE;
1364
  }
1365

    
1366
  $filename = drupal_get_filename($type, $name);
1367

    
1368
  if ($filename) {
1369
    include_once DRUPAL_ROOT . '/' . $filename;
1370
    $files[$type][$name] = TRUE;
1371

    
1372
    return TRUE;
1373
  }
1374

    
1375
  return FALSE;
1376
}
1377

    
1378
/**
1379
 * Sets an HTTP response header for the current page.
1380
 *
1381
 * Note: When sending a Content-Type header, always include a 'charset' type,
1382
 * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
1383
 *
1384
 * @param $name
1385
 *   The HTTP header name, or the special 'Status' header name.
1386
 * @param $value
1387
 *   The HTTP header value; if equal to FALSE, the specified header is unset.
1388
 *   If $name is 'Status', this is expected to be a status code followed by a
1389
 *   reason phrase, e.g. "404 Not Found".
1390
 * @param $append
1391
 *   Whether to append the value to an existing header or to replace it.
1392
 */
1393
function drupal_add_http_header($name, $value, $append = FALSE) {
1394
  // The headers as name/value pairs.
1395
  $headers = &drupal_static('drupal_http_headers', array());
1396

    
1397
  $name_lower = strtolower($name);
1398
  _drupal_set_preferred_header_name($name);
1399

    
1400
  if ($value === FALSE) {
1401
    $headers[$name_lower] = FALSE;
1402
  }
1403
  elseif (isset($headers[$name_lower]) && $append) {
1404
    // Multiple headers with identical names may be combined using comma (RFC
1405
    // 2616, section 4.2).
1406
    $headers[$name_lower] .= ',' . $value;
1407
  }
1408
  else {
1409
    $headers[$name_lower] = $value;
1410
  }
1411
  drupal_send_headers(array($name => $headers[$name_lower]), TRUE);
1412
}
1413

    
1414
/**
1415
 * Gets the HTTP response headers for the current page.
1416
 *
1417
 * @param $name
1418
 *   An HTTP header name. If omitted, all headers are returned as name/value
1419
 *   pairs. If an array value is FALSE, the header has been unset.
1420
 *
1421
 * @return
1422
 *   A string containing the header value, or FALSE if the header has been set,
1423
 *   or NULL if the header has not been set.
1424
 */
1425
function drupal_get_http_header($name = NULL) {
1426
  $headers = &drupal_static('drupal_http_headers', array());
1427
  if (isset($name)) {
1428
    $name = strtolower($name);
1429
    return isset($headers[$name]) ? $headers[$name] : NULL;
1430
  }
1431
  else {
1432
    return $headers;
1433
  }
1434
}
1435

    
1436
/**
1437
 * Sets the preferred name for the HTTP header.
1438
 *
1439
 * Header names are case-insensitive, but for maximum compatibility they should
1440
 * follow "common form" (see RFC 2617, section 4.2).
1441
 */
1442
function _drupal_set_preferred_header_name($name = NULL) {
1443
  static $header_names = array();
1444

    
1445
  if (!isset($name)) {
1446
    return $header_names;
1447
  }
1448
  $header_names[strtolower($name)] = $name;
1449
}
1450

    
1451
/**
1452
 * Sends the HTTP response headers that were previously set, adding defaults.
1453
 *
1454
 * Headers are set in drupal_add_http_header(). Default headers are not set
1455
 * if they have been replaced or unset using drupal_add_http_header().
1456
 *
1457
 * @param array $default_headers
1458
 *   (optional) An array of headers as name/value pairs.
1459
 * @param bool $only_default
1460
 *   (optional) If TRUE and headers have already been sent, send only the
1461
 *   specified headers.
1462
 */
1463
function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
1464
  $headers_sent = &drupal_static(__FUNCTION__, FALSE);
1465
  $headers = drupal_get_http_header();
1466
  if ($only_default && $headers_sent) {
1467
    $headers = array();
1468
  }
1469
  $headers_sent = TRUE;
1470

    
1471
  $header_names = _drupal_set_preferred_header_name();
1472
  foreach ($default_headers as $name => $value) {
1473
    $name_lower = strtolower($name);
1474
    if (!isset($headers[$name_lower])) {
1475
      $headers[$name_lower] = $value;
1476
      $header_names[$name_lower] = $name;
1477
    }
1478
  }
1479
  foreach ($headers as $name_lower => $value) {
1480
    if ($name_lower == 'status') {
1481
      header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
1482
    }
1483
    // Skip headers that have been unset.
1484
    elseif ($value !== FALSE) {
1485
      header($header_names[$name_lower] . ': ' . $value);
1486
    }
1487
  }
1488
}
1489

    
1490
/**
1491
 * Sets HTTP headers in preparation for a page response.
1492
 *
1493
 * Authenticated users are always given a 'no-cache' header, and will fetch a
1494
 * fresh page on every request. This prevents authenticated users from seeing
1495
 * locally cached pages.
1496
 *
1497
 * ETag and Last-Modified headers are not set per default for authenticated
1498
 * users so that browsers do not send If-Modified-Since headers from
1499
 * authenticated user pages. drupal_serve_page_from_cache() will set appropriate
1500
 * ETag and Last-Modified headers for cached pages.
1501
 *
1502
 * @see drupal_page_set_cache()
1503
 */
1504
function drupal_page_header() {
1505
  $headers_sent = &drupal_static(__FUNCTION__, FALSE);
1506
  if ($headers_sent) {
1507
    return TRUE;
1508
  }
1509
  $headers_sent = TRUE;
1510

    
1511
  $default_headers = array(
1512
    'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
1513
    'Cache-Control' => 'no-cache, must-revalidate',
1514
    // Prevent browsers from sniffing a response and picking a MIME type
1515
    // different from the declared content-type, since that can lead to
1516
    // XSS and other vulnerabilities.
1517
    'X-Content-Type-Options' => 'nosniff',
1518
  );
1519
  drupal_send_headers($default_headers);
1520
}
1521

    
1522
/**
1523
 * Sets HTTP headers in preparation for a cached page response.
1524
 *
1525
 * The headers allow as much as possible in proxies and browsers without any
1526
 * particular knowledge about the pages. Modules can override these headers
1527
 * using drupal_add_http_header().
1528
 *
1529
 * If the request is conditional (using If-Modified-Since and If-None-Match),
1530
 * and the conditions match those currently in the cache, a 304 Not Modified
1531
 * response is sent.
1532
 */
1533
function drupal_serve_page_from_cache(stdClass $cache) {
1534
  // Negotiate whether to use compression.
1535
  $page_compression = !empty($cache->data['page_compressed']);
1536
  $return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;
1537

    
1538
  // Get headers set in hook_boot(). Keys are lower-case.
1539
  $hook_boot_headers = drupal_get_http_header();
1540

    
1541
  // Headers generated in this function, that may be replaced or unset using
1542
  // drupal_add_http_headers(). Keys are mixed-case.
1543
  $default_headers = array();
1544

    
1545
  foreach ($cache->data['headers'] as $name => $value) {
1546
    // In the case of a 304 response, certain headers must be sent, and the
1547
    // remaining may not (see RFC 2616, section 10.3.5). Do not override
1548
    // headers set in hook_boot().
1549
    $name_lower = strtolower($name);
1550
    if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($hook_boot_headers[$name_lower])) {
1551
      drupal_add_http_header($name, $value);
1552
      unset($cache->data['headers'][$name]);
1553
    }
1554
  }
1555

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

    
1564
  // Entity tag should change if the output changes.
1565
  $etag = '"' . $cache->created . '-' . intval($return_compressed) . '"';
1566
  header('Etag: ' . $etag);
1567

    
1568
  // See if the client has provided the required HTTP headers.
1569
  $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
1570
  $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
1571

    
1572
  if ($if_modified_since && $if_none_match
1573
      && $if_none_match == $etag // etag must match
1574
      && $if_modified_since == $cache->created) {  // if-modified-since must match
1575
    header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
1576
    drupal_send_headers($default_headers);
1577
    return;
1578
  }
1579

    
1580
  // Send the remaining headers.
1581
  foreach ($cache->data['headers'] as $name => $value) {
1582
    drupal_add_http_header($name, $value);
1583
  }
1584

    
1585
  $default_headers['Last-Modified'] = gmdate(DATE_RFC7231, $cache->created);
1586

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

    
1593
  drupal_send_headers($default_headers);
1594

    
1595
  // Allow HTTP proxies to cache pages for anonymous users without a session
1596
  // cookie. The Vary header is used to indicates the set of request-header
1597
  // fields that fully determines whether a cache is permitted to use the
1598
  // response to reply to a subsequent request for a given URL without
1599
  // revalidation. If a Vary header has been set in hook_boot(), it is assumed
1600
  // that the module knows how to cache the page.
1601
  if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie')) {
1602
    header('Vary: Cookie');
1603
  }
1604

    
1605
  if ($page_compression) {
1606
    header('Vary: Accept-Encoding', FALSE);
1607
    // If page_compression is enabled, the cache contains gzipped data.
1608
    if ($return_compressed) {
1609
      // $cache->data['body'] is already gzip'ed, so make sure
1610
      // zlib.output_compression does not compress it once more.
1611
      ini_set('zlib.output_compression', '0');
1612
      header('Content-Encoding: gzip');
1613
    }
1614
    else {
1615
      // The client does not support compression, so unzip the data in the
1616
      // cache. Strip the gzip header and run uncompress.
1617
      $cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
1618
    }
1619
  }
1620

    
1621
  // Print the page.
1622
  print $cache->data['body'];
1623
}
1624

    
1625
/**
1626
 * Defines the critical hooks that force modules to always be loaded.
1627
 */
1628
function bootstrap_hooks() {
1629
  return array('boot', 'exit', 'watchdog', 'language_init');
1630
}
1631

    
1632
/**
1633
 * Unserializes and appends elements from a serialized string.
1634
 *
1635
 * @param $obj
1636
 *   The object to which the elements are appended.
1637
 * @param $field
1638
 *   The attribute of $obj whose value should be unserialized.
1639
 */
1640
function drupal_unpack($obj, $field = 'data') {
1641
  if ($obj->$field && $data = unserialize($obj->$field)) {
1642
    foreach ($data as $key => $value) {
1643
      if (!empty($key) && !isset($obj->$key)) {
1644
        $obj->$key = $value;
1645
      }
1646
    }
1647
  }
1648
  return $obj;
1649
}
1650

    
1651
/**
1652
 * Translates a string to the current language or to a given language.
1653
 *
1654
 * The t() function serves two purposes. First, at run-time it translates
1655
 * user-visible text into the appropriate language. Second, various mechanisms
1656
 * that figure out what text needs to be translated work off t() -- the text
1657
 * inside t() calls is added to the database of strings to be translated.
1658
 * These strings are expected to be in English, so the first argument should
1659
 * always be in English. To enable a fully-translatable site, it is important
1660
 * that all human-readable text that will be displayed on the site or sent to
1661
 * a user is passed through the t() function, or a related function. See the
1662
 * @link http://drupal.org/node/322729 Localization API @endlink pages for
1663
 * more information, including recommendations on how to break up or not
1664
 * break up strings for translation.
1665
 *
1666
 * @section sec_translating_vars Translating Variables
1667
 * You should never use t() to translate variables, such as calling
1668
 * @code t($text); @endcode, unless the text that the variable holds has been
1669
 * passed through t() elsewhere (e.g., $text is one of several translated
1670
 * literal strings in an array). It is especially important never to call
1671
 * @code t($user_text); @endcode, where $user_text is some text that a user
1672
 * entered - doing that can lead to cross-site scripting and other security
1673
 * problems. However, you can use variable substitution in your string, to put
1674
 * variable text such as user names or link URLs into translated text. Variable
1675
 * substitution looks like this:
1676
 * @code
1677
 * $text = t("@name's blog", array('@name' => format_username($account)));
1678
 * @endcode
1679
 * Basically, you can put variables like @name into your string, and t() will
1680
 * substitute their sanitized values at translation time. (See the
1681
 * Localization API pages referenced above and the documentation of
1682
 * format_string() for details about how to define variables in your string.)
1683
 * Translators can then rearrange the string as necessary for the language
1684
 * (e.g., in Spanish, it might be "blog de @name").
1685
 *
1686
 * @section sec_alt_funcs_install Use During Installation Phase
1687
 * During the Drupal installation phase, some resources used by t() wil not be
1688
 * available to code that needs localization. See st() and get_t() for
1689
 * alternatives.
1690
 *
1691
 * @section sec_context String context
1692
 * Matching source strings are normally only translated once, and the same
1693
 * translation is used everywhere that has a matching string. However, in some
1694
 * cases, a certain English source string needs to have multiple translations.
1695
 * One example of this is the string "May", which could be used as either a
1696
 * full month name or a 3-letter abbreviated month. In other languages where
1697
 * the month name for May has more than 3 letters, you would need to provide
1698
 * two different translations (one for the full name and one abbreviated), and
1699
 * the correct form would need to be chosen, depending on how "May" is being
1700
 * used. To facilitate this, the "May" string should be provided with two
1701
 * different contexts in the $options parameter when calling t(). For example:
1702
 * @code
1703
 * t('May', array(), array('context' => 'Long month name')
1704
 * t('May', array(), array('context' => 'Abbreviated month name')
1705
 * @endcode
1706
 * See https://localize.drupal.org/node/2109 for more information.
1707
 *
1708
 * @param $string
1709
 *   A string containing the English string to translate.
1710
 * @param $args
1711
 *   An associative array of replacements to make after translation. Based
1712
 *   on the first character of the key, the value is escaped and/or themed.
1713
 *   See format_string() for details.
1714
 * @param $options
1715
 *   An associative array of additional options, with the following elements:
1716
 *   - 'langcode' (defaults to the current language): The language code to
1717
 *     translate to a language other than what is used to display the page.
1718
 *   - 'context' (defaults to the empty context): A string giving the context
1719
 *     that the source string belongs to. See @ref sec_context above for more
1720
 *     information.
1721
 *
1722
 * @return
1723
 *   The translated string.
1724
 *
1725
 * @see st()
1726
 * @see get_t()
1727
 * @see format_string()
1728
 * @ingroup sanitization
1729
 */
1730
function t($string, array $args = array(), array $options = array()) {
1731
  global $language;
1732
  static $custom_strings;
1733

    
1734
  // Merge in default.
1735
  if (empty($options['langcode'])) {
1736
    $options['langcode'] = isset($language->language) ? $language->language : 'en';
1737
  }
1738
  if (empty($options['context'])) {
1739
    $options['context'] = '';
1740
  }
1741

    
1742
  // First, check for an array of customized strings. If present, use the array
1743
  // *instead of* database lookups. This is a high performance way to provide a
1744
  // handful of string replacements. See settings.php for examples.
1745
  // Cache the $custom_strings variable to improve performance.
1746
  if (!isset($custom_strings[$options['langcode']])) {
1747
    $custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
1748
  }
1749
  // Custom strings work for English too, even if locale module is disabled.
1750
  if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
1751
    $string = $custom_strings[$options['langcode']][$options['context']][$string];
1752
  }
1753
  // Translate with locale module if enabled.
1754
  elseif ($options['langcode'] != 'en' && function_exists('locale')) {
1755
    $string = locale($string, $options['context'], $options['langcode']);
1756
  }
1757
  if (empty($args)) {
1758
    return $string;
1759
  }
1760
  else {
1761
    return format_string($string, $args);
1762
  }
1763
}
1764

    
1765
/**
1766
 * Formats a string for HTML display by replacing variable placeholders.
1767
 *
1768
 * This function replaces variable placeholders in a string with the requested
1769
 * values and escapes the values so they can be safely displayed as HTML. It
1770
 * should be used on any unknown text that is intended to be printed to an HTML
1771
 * page (especially text that may have come from untrusted users, since in that
1772
 * case it prevents cross-site scripting and other security problems).
1773
 *
1774
 * In most cases, you should use t() rather than calling this function
1775
 * directly, since it will translate the text (on non-English-only sites) in
1776
 * addition to formatting it.
1777
 *
1778
 * @param $string
1779
 *   A string containing placeholders.
1780
 * @param $args
1781
 *   An associative array of replacements to make. Occurrences in $string of
1782
 *   any key in $args are replaced with the corresponding value, after optional
1783
 *   sanitization and formatting. The type of sanitization and formatting
1784
 *   depends on the first character of the key:
1785
 *   - @variable: Escaped to HTML using check_plain(). Use this as the default
1786
 *     choice for anything displayed on a page on the site.
1787
 *   - %variable: Escaped to HTML and formatted using drupal_placeholder(),
1788
 *     which makes it display as <em>emphasized</em> text.
1789
 *   - !variable: Inserted as is, with no sanitization or formatting. Only use
1790
 *     this for text that has already been prepared for HTML display (for
1791
 *     example, user-supplied text that has already been run through
1792
 *     check_plain() previously, or is expected to contain some limited HTML
1793
 *     tags and has already been run through filter_xss() previously).
1794
 *
1795
 * @see t()
1796
 * @ingroup sanitization
1797
 */
1798
function format_string($string, array $args = array()) {
1799
  // Transform arguments before inserting them.
1800
  foreach ($args as $key => $value) {
1801
    switch ($key[0]) {
1802
      case '@':
1803
        // Escaped only.
1804
        $args[$key] = check_plain($value);
1805
        break;
1806

    
1807
      case '%':
1808
      default:
1809
        // Escaped and placeholder.
1810
        $args[$key] = drupal_placeholder($value);
1811
        break;
1812

    
1813
      case '!':
1814
        // Pass-through.
1815
    }
1816
  }
1817
  return strtr($string, $args);
1818
}
1819

    
1820
/**
1821
 * Encodes special characters in a plain-text string for display as HTML.
1822
 *
1823
 * Also validates strings as UTF-8 to prevent cross site scripting attacks on
1824
 * Internet Explorer 6.
1825
 *
1826
 * @param string $text
1827
 *   The text to be checked or processed.
1828
 *
1829
 * @return string
1830
 *   An HTML safe version of $text. If $text is not valid UTF-8, an empty string
1831
 *   is returned and, on PHP < 5.4, a warning may be issued depending on server
1832
 *   configuration (see @link https://bugs.php.net/bug.php?id=47494 @endlink).
1833
 *
1834
 * @see drupal_validate_utf8()
1835
 * @ingroup sanitization
1836
 */
1837
function check_plain($text) {
1838
  return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
1839
}
1840

    
1841
/**
1842
 * Checks whether a string is valid UTF-8.
1843
 *
1844
 * All functions designed to filter input should use drupal_validate_utf8
1845
 * to ensure they operate on valid UTF-8 strings to prevent bypass of the
1846
 * filter.
1847
 *
1848
 * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
1849
 * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
1850
 * bytes. When these subsequent bytes are HTML control characters such as
1851
 * quotes or angle brackets, parts of the text that were deemed safe by filters
1852
 * end up in locations that are potentially unsafe; An onerror attribute that
1853
 * is outside of a tag, and thus deemed safe by a filter, can be interpreted
1854
 * by the browser as if it were inside the tag.
1855
 *
1856
 * The function does not return FALSE for strings containing character codes
1857
 * above U+10FFFF, even though these are prohibited by RFC 3629.
1858
 *
1859
 * @param $text
1860
 *   The text to check.
1861
 *
1862
 * @return
1863
 *   TRUE if the text is valid UTF-8, FALSE if not.
1864
 */
1865
function drupal_validate_utf8($text) {
1866
  if (strlen($text) == 0) {
1867
    return TRUE;
1868
  }
1869
  // With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
1870
  // containing invalid UTF-8 byte sequences. It does not reject character
1871
  // codes above U+10FFFF (represented by 4 or more octets), though.
1872
  return (preg_match('/^./us', $text) == 1);
1873
}
1874

    
1875
/**
1876
 * Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
1877
 *
1878
 * Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
1879
 * equivalent using other environment variables.
1880
 */
1881
function request_uri() {
1882
  if (isset($_SERVER['REQUEST_URI'])) {
1883
    $uri = $_SERVER['REQUEST_URI'];
1884
  }
1885
  else {
1886
    if (isset($_SERVER['argv'])) {
1887
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
1888
    }
1889
    elseif (isset($_SERVER['QUERY_STRING'])) {
1890
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
1891
    }
1892
    else {
1893
      $uri = $_SERVER['SCRIPT_NAME'];
1894
    }
1895
  }
1896
  // Prevent multiple slashes to avoid cross site requests via the Form API.
1897
  $uri = '/' . ltrim($uri, '/');
1898

    
1899
  return $uri;
1900
}
1901

    
1902
/**
1903
 * Logs an exception.
1904
 *
1905
 * This is a wrapper function for watchdog() which automatically decodes an
1906
 * exception.
1907
 *
1908
 * @param $type
1909
 *   The category to which this message belongs.
1910
 * @param $exception
1911
 *   The exception that is going to be logged.
1912
 * @param $message
1913
 *   The message to store in the log. If empty, a text that contains all useful
1914
 *   information about the passed-in exception is used.
1915
 * @param $variables
1916
 *   Array of variables to replace in the message on display. Defaults to the
1917
 *   return value of _drupal_decode_exception().
1918
 * @param $severity
1919
 *   The severity of the message, as per RFC 3164.
1920
 * @param $link
1921
 *   A link to associate with the message.
1922
 *
1923
 * @see watchdog()
1924
 * @see _drupal_decode_exception()
1925
 */
1926
function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {
1927

    
1928
   // Use a default value if $message is not set.
1929
   if (empty($message)) {
1930
     // The exception message is run through check_plain() by _drupal_decode_exception().
1931
     $message = '%type: !message in %function (line %line of %file).';
1932
   }
1933
   // $variables must be an array so that we can add the exception information.
1934
   if (!is_array($variables)) {
1935
     $variables = array();
1936
   }
1937

    
1938
   require_once DRUPAL_ROOT . '/includes/errors.inc';
1939
   $variables += _drupal_decode_exception($exception);
1940
   watchdog($type, $message, $variables, $severity, $link);
1941
}
1942

    
1943
/**
1944
 * Logs a system message.
1945
 *
1946
 * @param $type
1947
 *   The category to which this message belongs. Can be any string, but the
1948
 *   general practice is to use the name of the module calling watchdog().
1949
 * @param $message
1950
 *   The message to store in the log. Keep $message translatable
1951
 *   by not concatenating dynamic values into it! Variables in the
1952
 *   message should be added by using placeholder strings alongside
1953
 *   the variables argument to declare the value of the placeholders.
1954
 *   See t() for documentation on how $message and $variables interact.
1955
 * @param $variables
1956
 *   Array of variables to replace in the message on display or
1957
 *   NULL if message is already translated or not possible to
1958
 *   translate.
1959
 * @param $severity
1960
 *   The severity of the message; one of the following values as defined in
1961
 *   @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
1962
 *   - WATCHDOG_EMERGENCY: Emergency, system is unusable.
1963
 *   - WATCHDOG_ALERT: Alert, action must be taken immediately.
1964
 *   - WATCHDOG_CRITICAL: Critical conditions.
1965
 *   - WATCHDOG_ERROR: Error conditions.
1966
 *   - WATCHDOG_WARNING: Warning conditions.
1967
 *   - WATCHDOG_NOTICE: (default) Normal but significant conditions.
1968
 *   - WATCHDOG_INFO: Informational messages.
1969
 *   - WATCHDOG_DEBUG: Debug-level messages.
1970
 * @param $link
1971
 *   A link to associate with the message.
1972
 *
1973
 * @see watchdog_severity_levels()
1974
 * @see hook_watchdog()
1975
 */
1976
function watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
1977
  global $user, $base_root;
1978

    
1979
  static $in_error_state = FALSE;
1980

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

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

    
1989
    // Prepare the fields to be logged
1990
    $log_entry = array(
1991
      'type'        => $type,
1992
      'message'     => $message,
1993
      'variables'   => $variables,
1994
      'severity'    => $severity,
1995
      'link'        => $link,
1996
      'user'        => $user,
1997
      'uid'         => $user_uid,
1998
      'request_uri' => $base_root . request_uri(),
1999
      'referer'     => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
2000
      'ip'          => ip_address(),
2001
      // Request time isn't accurate for long processes, use time() instead.
2002
      'timestamp'   => time(),
2003
    );
2004

    
2005
    // Call the logging hooks to log/process the message
2006
    foreach (module_implements('watchdog') as $module) {
2007
      module_invoke($module, 'watchdog', $log_entry);
2008
    }
2009

    
2010
    // It is critical that the semaphore is only cleared here, in the parent
2011
    // watchdog() call (not outside the loop), to prevent recursive execution.
2012
    $in_error_state = FALSE;
2013
  }
2014
}
2015

    
2016
/**
2017
 * Sets a message to display to the user.
2018
 *
2019
 * Messages are stored in a session variable and displayed in page.tpl.php via
2020
 * the $messages theme variable.
2021
 *
2022
 * Example usage:
2023
 * @code
2024
 * drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
2025
 * @endcode
2026
 *
2027
 * @param string $message
2028
 *   (optional) The translated message to be displayed to the user. For
2029
 *   consistency with other messages, it should begin with a capital letter and
2030
 *   end with a period.
2031
 * @param string $type
2032
 *   (optional) The message's type. Defaults to 'status'. These values are
2033
 *   supported:
2034
 *   - 'status'
2035
 *   - 'warning'
2036
 *   - 'error'
2037
 * @param bool $repeat
2038
 *   (optional) If this is FALSE and the message is already set, then the
2039
 *   message won't be repeated. Defaults to TRUE.
2040
 *
2041
 * @return array|null
2042
 *   A multidimensional array with keys corresponding to the set message types.
2043
 *   The indexed array values of each contain the set messages for that type.
2044
 *   Or, if there are no messages set, the function returns NULL.
2045
 *
2046
 * @see drupal_get_messages()
2047
 * @see theme_status_messages()
2048
 */
2049
function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
2050
  if ($message || $message === '0' || $message === 0) {
2051
    if (!isset($_SESSION['messages'][$type])) {
2052
      $_SESSION['messages'][$type] = array();
2053
    }
2054

    
2055
    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
2056
      $_SESSION['messages'][$type][] = $message;
2057
    }
2058

    
2059
    // Mark this page as being uncacheable.
2060
    drupal_page_is_cacheable(FALSE);
2061
  }
2062

    
2063
  // Messages not set when DB connection fails.
2064
  return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
2065
}
2066

    
2067
/**
2068
 * Returns all messages that have been set with drupal_set_message().
2069
 *
2070
 * @param string $type
2071
 *   (optional) Limit the messages returned by type. Defaults to NULL, meaning
2072
 *   all types. These values are supported:
2073
 *   - NULL
2074
 *   - 'status'
2075
 *   - 'warning'
2076
 *   - 'error'
2077
 * @param bool $clear_queue
2078
 *   (optional) If this is TRUE, the queue will be cleared of messages of the
2079
 *   type specified in the $type parameter. Otherwise the queue will be left
2080
 *   intact. Defaults to TRUE.
2081
 *
2082
 * @return array
2083
 *   A multidimensional array with keys corresponding to the set message types.
2084
 *   The indexed array values of each contain the set messages for that type.
2085
 *   The messages returned are limited to the type specified in the $type
2086
 *   parameter. If there are no messages of the specified type, an empty array
2087
 *   is returned.
2088
 *
2089
 * @see drupal_set_message()
2090
 * @see theme_status_messages()
2091
 */
2092
function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
2093
  if ($messages = drupal_set_message()) {
2094
    if ($type) {
2095
      if ($clear_queue) {
2096
        unset($_SESSION['messages'][$type]);
2097
      }
2098
      if (isset($messages[$type])) {
2099
        return array($type => $messages[$type]);
2100
      }
2101
    }
2102
    else {
2103
      if ($clear_queue) {
2104
        unset($_SESSION['messages']);
2105
      }
2106
      return $messages;
2107
    }
2108
  }
2109
  return array();
2110
}
2111

    
2112
/**
2113
 * Gets the title of the current page.
2114
 *
2115
 * The title is displayed on the page and in the title bar.
2116
 *
2117
 * @return
2118
 *   The current page's title.
2119
 */
2120
function drupal_get_title() {
2121
  $title = drupal_set_title();
2122

    
2123
  // During a bootstrap, menu.inc is not included and thus we cannot provide a title.
2124
  if (!isset($title) && function_exists('menu_get_active_title')) {
2125
    $title = check_plain(menu_get_active_title());
2126
  }
2127

    
2128
  return $title;
2129
}
2130

    
2131
/**
2132
 * Sets the title of the current page.
2133
 *
2134
 * The title is displayed on the page and in the title bar.
2135
 *
2136
 * @param $title
2137
 *   Optional string value to assign to the page title; or if set to NULL
2138
 *   (default), leaves the current title unchanged.
2139
 * @param $output
2140
 *   Optional flag - normally should be left as CHECK_PLAIN. Only set to
2141
 *   PASS_THROUGH if you have already removed any possibly dangerous code
2142
 *   from $title using a function like check_plain() or filter_xss(). With this
2143
 *   flag the string will be passed through unchanged.
2144
 *
2145
 * @return
2146
 *   The updated title of the current page.
2147
 */
2148
function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
2149
  $stored_title = &drupal_static(__FUNCTION__);
2150

    
2151
  if (isset($title)) {
2152
    $stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
2153
  }
2154

    
2155
  return $stored_title;
2156
}
2157

    
2158
/**
2159
 * Checks to see if an IP address has been blocked.
2160
 *
2161
 * Blocked IP addresses are stored in the database by default. However for
2162
 * performance reasons we allow an override in settings.php. This allows us
2163
 * to avoid querying the database at this critical stage of the bootstrap if
2164
 * an administrative interface for IP address blocking is not required.
2165
 *
2166
 * @param $ip
2167
 *   IP address to check.
2168
 *
2169
 * @return bool
2170
 *   TRUE if access is denied, FALSE if access is allowed.
2171
 */
2172
function drupal_is_denied($ip) {
2173
  // Because this function is called on every page request, we first check
2174
  // for an array of IP addresses in settings.php before querying the
2175
  // database.
2176
  $blocked_ips = variable_get('blocked_ips');
2177
  $denied = FALSE;
2178
  if (isset($blocked_ips) && is_array($blocked_ips)) {
2179
    $denied = in_array($ip, $blocked_ips);
2180
  }
2181
  // Only check if database.inc is loaded already. If
2182
  // $conf['page_cache_without_database'] = TRUE; is set in settings.php,
2183
  // then the database won't be loaded here so the IPs in the database
2184
  // won't be denied. However the user asked explicitly not to use the
2185
  // database and also in this case it's quite likely that the user relies
2186
  // on higher performance solutions like a firewall.
2187
  elseif (class_exists('Database', FALSE)) {
2188
    $denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();
2189
  }
2190
  return $denied;
2191
}
2192

    
2193
/**
2194
 * Handles denied users.
2195
 *
2196
 * @param $ip
2197
 *   IP address to check. Prints a message and exits if access is denied.
2198
 */
2199
function drupal_block_denied($ip) {
2200
  // Deny access to blocked IP addresses - t() is not yet available.
2201
  if (drupal_is_denied($ip)) {
2202
    header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
2203
    print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.';
2204
    exit();
2205
  }
2206
}
2207

    
2208
/**
2209
 * Returns a URL-safe, base64 encoded string of highly randomized bytes (over the full 8-bit range).
2210
 *
2211
 * @param $byte_count
2212
 *   The number of random bytes to fetch and base64 encode.
2213
 *
2214
 * @return string
2215
 *   The base64 encoded result will have a length of up to 4 * $byte_count.
2216
 */
2217
function drupal_random_key($byte_count = 32) {
2218
  return drupal_base64_encode(drupal_random_bytes($byte_count));
2219
}
2220

    
2221
/**
2222
 * Returns a URL-safe, base64 encoded version of the supplied string.
2223
 *
2224
 * @param $string
2225
 *   The string to convert to base64.
2226
 *
2227
 * @return string
2228
 */
2229
function drupal_base64_encode($string) {
2230
  $data = base64_encode($string);
2231
  // Modify the output so it's safe to use in URLs.
2232
  return strtr($data, array('+' => '-', '/' => '_', '=' => ''));
2233
}
2234

    
2235
/**
2236
 * Returns a string of highly randomized bytes (over the full 8-bit range).
2237
 *
2238
 * This function is better than simply calling mt_rand() or any other built-in
2239
 * PHP function because it can return a long string of bytes (compared to < 4
2240
 * bytes normally from mt_rand()) and uses the best available pseudo-random
2241
 * source.
2242
 *
2243
 * @param $count
2244
 *   The number of characters (bytes) to return in the string.
2245
 */
2246
function drupal_random_bytes($count)  {
2247
  // $random_state does not use drupal_static as it stores random bytes.
2248
  static $random_state, $bytes, $has_openssl;
2249

    
2250
  $missing_bytes = $count - strlen($bytes);
2251

    
2252
  if ($missing_bytes > 0) {
2253
    // PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
2254
    // locking on Windows and rendered it unusable.
2255
    if (!isset($has_openssl)) {
2256
      $has_openssl = version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes');
2257
    }
2258

    
2259
    // openssl_random_pseudo_bytes() will find entropy in a system-dependent
2260
    // way.
2261
    if ($has_openssl) {
2262
      $bytes .= openssl_random_pseudo_bytes($missing_bytes);
2263
    }
2264

    
2265
    // Else, read directly from /dev/urandom, which is available on many *nix
2266
    // systems and is considered cryptographically secure.
2267
    elseif ($fh = @fopen('/dev/urandom', 'rb')) {
2268
      // PHP only performs buffered reads, so in reality it will always read
2269
      // at least 4096 bytes. Thus, it costs nothing extra to read and store
2270
      // that much so as to speed any additional invocations.
2271
      $bytes .= fread($fh, max(4096, $missing_bytes));
2272
      fclose($fh);
2273
    }
2274

    
2275
    // If we couldn't get enough entropy, this simple hash-based PRNG will
2276
    // generate a good set of pseudo-random bytes on any system.
2277
    // Note that it may be important that our $random_state is passed
2278
    // through hash() prior to being rolled into $output, that the two hash()
2279
    // invocations are different, and that the extra input into the first one -
2280
    // the microtime() - is prepended rather than appended. This is to avoid
2281
    // directly leaking $random_state via the $output stream, which could
2282
    // allow for trivial prediction of further "random" numbers.
2283
    if (strlen($bytes) < $count) {
2284
      // Initialize on the first call. The contents of $_SERVER includes a mix of
2285
      // user-specific and system information that varies a little with each page.
2286
      if (!isset($random_state)) {
2287
        $random_state = print_r($_SERVER, TRUE);
2288
        if (function_exists('getmypid')) {
2289
          // Further initialize with the somewhat random PHP process ID.
2290
          $random_state .= getmypid();
2291
        }
2292
        $bytes = '';
2293
      }
2294

    
2295
      do {
2296
        $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
2297
        $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
2298
      }
2299
      while (strlen($bytes) < $count);
2300
    }
2301
  }
2302
  $output = substr($bytes, 0, $count);
2303
  $bytes = substr($bytes, $count);
2304
  return $output;
2305
}
2306

    
2307
/**
2308
 * Calculates a base-64 encoded, URL-safe sha-256 hmac.
2309
 *
2310
 * @param string $data
2311
 *   String to be validated with the hmac.
2312
 * @param string $key
2313
 *   A secret string key.
2314
 *
2315
 * @return string
2316
 *   A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
2317
 *   any = padding characters removed.
2318
 */
2319
function drupal_hmac_base64($data, $key) {
2320
  // Casting $data and $key to strings here is necessary to avoid empty string
2321
  // results of the hash function if they are not scalar values. As this
2322
  // function is used in security-critical contexts like token validation it is
2323
  // important that it never returns an empty string.
2324
  $hmac = base64_encode(hash_hmac('sha256', (string) $data, (string) $key, TRUE));
2325
  // Modify the hmac so it's safe to use in URLs.
2326
  return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
2327
}
2328

    
2329
/**
2330
 * Calculates a base-64 encoded, URL-safe sha-256 hash.
2331
 *
2332
 * @param $data
2333
 *   String to be hashed.
2334
 *
2335
 * @return
2336
 *   A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
2337
 *   any = padding characters removed.
2338
 */
2339
function drupal_hash_base64($data) {
2340
  $hash = base64_encode(hash('sha256', $data, TRUE));
2341
  // Modify the hash so it's safe to use in URLs.
2342
  return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
2343
}
2344

    
2345
/**
2346
 * Merges multiple arrays, recursively, and returns the merged array.
2347
 *
2348
 * This function is similar to PHP's array_merge_recursive() function, but it
2349
 * handles non-array values differently. When merging values that are not both
2350
 * arrays, the latter value replaces the former rather than merging with it.
2351
 *
2352
 * Example:
2353
 * @code
2354
 * $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
2355
 * $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
2356
 *
2357
 * // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
2358
 * $incorrect = array_merge_recursive($link_options_1, $link_options_2);
2359
 *
2360
 * // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
2361
 * $correct = drupal_array_merge_deep($link_options_1, $link_options_2);
2362
 * @endcode
2363
 *
2364
 * @param ...
2365
 *   Arrays to merge.
2366
 *
2367
 * @return
2368
 *   The merged array.
2369
 *
2370
 * @see drupal_array_merge_deep_array()
2371
 */
2372
function drupal_array_merge_deep() {
2373
  $args = func_get_args();
2374
  return drupal_array_merge_deep_array($args);
2375
}
2376

    
2377
/**
2378
 * Merges multiple arrays, recursively, and returns the merged array.
2379
 *
2380
 * This function is equivalent to drupal_array_merge_deep(), except the
2381
 * input arrays are passed as a single array parameter rather than a variable
2382
 * parameter list.
2383
 *
2384
 * The following are equivalent:
2385
 * - drupal_array_merge_deep($a, $b);
2386
 * - drupal_array_merge_deep_array(array($a, $b));
2387
 *
2388
 * The following are also equivalent:
2389
 * - call_user_func_array('drupal_array_merge_deep', $arrays_to_merge);
2390
 * - drupal_array_merge_deep_array($arrays_to_merge);
2391
 *
2392
 * @see drupal_array_merge_deep()
2393
 */
2394
function drupal_array_merge_deep_array($arrays) {
2395
  $result = array();
2396

    
2397
  foreach ($arrays as $array) {
2398
    foreach ($array as $key => $value) {
2399
      // Renumber integer keys as array_merge_recursive() does. Note that PHP
2400
      // automatically converts array keys that are integer strings (e.g., '1')
2401
      // to integers.
2402
      if (is_integer($key)) {
2403
        $result[] = $value;
2404
      }
2405
      // Recurse when both values are arrays.
2406
      elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
2407
        $result[$key] = drupal_array_merge_deep_array(array($result[$key], $value));
2408
      }
2409
      // Otherwise, use the latter value, overriding any previous value.
2410
      else {
2411
        $result[$key] = $value;
2412
      }
2413
    }
2414
  }
2415

    
2416
  return $result;
2417
}
2418

    
2419
/**
2420
 * Generates a default anonymous $user object.
2421
 *
2422
 * @return Object - the user object.
2423
 */
2424
function drupal_anonymous_user() {
2425
  $user = variable_get('drupal_anonymous_user_object', new stdClass);
2426
  $user->uid = 0;
2427
  $user->hostname = ip_address();
2428
  $user->roles = array();
2429
  $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
2430
  $user->cache = 0;
2431
  return $user;
2432
}
2433

    
2434
/**
2435
 * Ensures Drupal is bootstrapped to the specified phase.
2436
 *
2437
 * In order to bootstrap Drupal from another PHP script, you can use this code:
2438
 * @code
2439
 *   define('DRUPAL_ROOT', '/path/to/drupal');
2440
 *   require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
2441
 *   drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
2442
 * @endcode
2443
 *
2444
 * @param int $phase
2445
 *   A constant telling which phase to bootstrap to. When you bootstrap to a
2446
 *   particular phase, all earlier phases are run automatically. Possible
2447
 *   values:
2448
 *   - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
2449
 *   - DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
2450
 *   - DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
2451
 *   - DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
2452
 *   - DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
2453
 *   - DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
2454
 *   - DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
2455
 *   - DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input
2456
 *     data.
2457
 * @param boolean $new_phase
2458
 *   A boolean, set to FALSE if calling drupal_bootstrap from inside a
2459
 *   function called from drupal_bootstrap (recursion).
2460
 *
2461
 * @return int
2462
 *   The most recently completed phase.
2463
 */
2464
function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
2465
  // Not drupal_static(), because does not depend on any run-time information.
2466
  static $phases = array(
2467
    DRUPAL_BOOTSTRAP_CONFIGURATION,
2468
    DRUPAL_BOOTSTRAP_PAGE_CACHE,
2469
    DRUPAL_BOOTSTRAP_DATABASE,
2470
    DRUPAL_BOOTSTRAP_VARIABLES,
2471
    DRUPAL_BOOTSTRAP_SESSION,
2472
    DRUPAL_BOOTSTRAP_PAGE_HEADER,
2473
    DRUPAL_BOOTSTRAP_LANGUAGE,
2474
    DRUPAL_BOOTSTRAP_FULL,
2475
  );
2476
  // Not drupal_static(), because the only legitimate API to control this is to
2477
  // call drupal_bootstrap() with a new phase parameter.
2478
  static $final_phase;
2479
  // Not drupal_static(), because it's impossible to roll back to an earlier
2480
  // bootstrap state.
2481
  static $stored_phase = -1;
2482

    
2483
  if (isset($phase)) {
2484
    // When not recursing, store the phase name so it's not forgotten while
2485
    // recursing but take care of not going backwards.
2486
    if ($new_phase && $phase >= $stored_phase) {
2487
      $final_phase = $phase;
2488
    }
2489

    
2490
    // Call a phase if it has not been called before and is below the requested
2491
    // phase.
2492
    while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
2493
      $current_phase = array_shift($phases);
2494

    
2495
      // This function is re-entrant. Only update the completed phase when the
2496
      // current call actually resulted in a progress in the bootstrap process.
2497
      if ($current_phase > $stored_phase) {
2498
        $stored_phase = $current_phase;
2499
      }
2500

    
2501
      switch ($current_phase) {
2502
        case DRUPAL_BOOTSTRAP_CONFIGURATION:
2503
          _drupal_bootstrap_configuration();
2504
          break;
2505

    
2506
        case DRUPAL_BOOTSTRAP_PAGE_CACHE:
2507
          _drupal_bootstrap_page_cache();
2508
          break;
2509

    
2510
        case DRUPAL_BOOTSTRAP_DATABASE:
2511
          _drupal_bootstrap_database();
2512
          break;
2513

    
2514
        case DRUPAL_BOOTSTRAP_VARIABLES:
2515
          _drupal_bootstrap_variables();
2516
          break;
2517

    
2518
        case DRUPAL_BOOTSTRAP_SESSION:
2519
          require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
2520
          drupal_session_initialize();
2521
          break;
2522

    
2523
        case DRUPAL_BOOTSTRAP_PAGE_HEADER:
2524
          _drupal_bootstrap_page_header();
2525
          break;
2526

    
2527
        case DRUPAL_BOOTSTRAP_LANGUAGE:
2528
          drupal_language_initialize();
2529
          break;
2530

    
2531
        case DRUPAL_BOOTSTRAP_FULL:
2532
          require_once DRUPAL_ROOT . '/includes/common.inc';
2533
          _drupal_bootstrap_full();
2534
          break;
2535
      }
2536
    }
2537
  }
2538
  return $stored_phase;
2539
}
2540

    
2541
/**
2542
 * Returns the time zone of the current user.
2543
 */
2544
function drupal_get_user_timezone() {
2545
  global $user;
2546
  if (variable_get('configurable_timezones', 1) && $user->uid && $user->timezone) {
2547
    return $user->timezone;
2548
  }
2549
  else {
2550
    // Ignore PHP strict notice if time zone has not yet been set in the php.ini
2551
    // configuration.
2552
    return variable_get('date_default_timezone', @date_default_timezone_get());
2553
  }
2554
}
2555

    
2556
/**
2557
 * Gets a salt useful for hardening against SQL injection.
2558
 *
2559
 * @return
2560
 *   A salt based on information in settings.php, not in the database.
2561
 */
2562
function drupal_get_hash_salt() {
2563
  global $drupal_hash_salt, $databases;
2564
  // If the $drupal_hash_salt variable is empty, a hash of the serialized
2565
  // database credentials is used as a fallback salt.
2566
  return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
2567
}
2568

    
2569
/**
2570
 * Provides custom PHP error handling.
2571
 *
2572
 * @param $error_level
2573
 *   The level of the error raised.
2574
 * @param $message
2575
 *   The error message.
2576
 * @param $filename
2577
 *   The filename that the error was raised in.
2578
 * @param $line
2579
 *   The line number the error was raised at.
2580
 * @param $context
2581
 *   An array that points to the active symbol table at the point the error
2582
 *   occurred.
2583
 */
2584
function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
2585
  require_once DRUPAL_ROOT . '/includes/errors.inc';
2586
  _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
2587
}
2588

    
2589
/**
2590
 * Provides custom PHP exception handling.
2591
 *
2592
 * Uncaught exceptions are those not enclosed in a try/catch block. They are
2593
 * always fatal: the execution of the script will stop as soon as the exception
2594
 * handler exits.
2595
 *
2596
 * @param $exception
2597
 *   The exception object that was thrown.
2598
 */
2599
function _drupal_exception_handler($exception) {
2600
  require_once DRUPAL_ROOT . '/includes/errors.inc';
2601

    
2602
  try {
2603
    // Log the message to the watchdog and return an error page to the user.
2604
    _drupal_log_error(_drupal_decode_exception($exception), TRUE);
2605
  }
2606
  catch (Exception $exception2) {
2607
    // Another uncaught exception was thrown while handling the first one.
2608
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
2609
    if (error_displayable()) {
2610
      print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
2611
      print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
2612
      print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
2613
    }
2614
  }
2615
}
2616

    
2617
/**
2618
 * Sets up the script environment and loads settings.php.
2619
 */
2620
function _drupal_bootstrap_configuration() {
2621
  // Set the Drupal custom error handler.
2622
  set_error_handler('_drupal_error_handler');
2623
  set_exception_handler('_drupal_exception_handler');
2624

    
2625
  drupal_environment_initialize();
2626
  // Start a page timer:
2627
  timer_start('page');
2628
  // Initialize the configuration, including variables from settings.php.
2629
  drupal_settings_initialize();
2630
}
2631

    
2632
/**
2633
 * Attempts to serve a page from the cache.
2634
 */
2635
function _drupal_bootstrap_page_cache() {
2636
  global $user;
2637

    
2638
  // Allow specifying special cache handlers in settings.php, like
2639
  // using memcached or files for storing cache information.
2640
  require_once DRUPAL_ROOT . '/includes/cache.inc';
2641
  foreach (variable_get('cache_backends', array()) as $include) {
2642
    require_once DRUPAL_ROOT . '/' . $include;
2643
  }
2644
  // Check for a cache mode force from settings.php.
2645
  if (variable_get('page_cache_without_database')) {
2646
    $cache_enabled = TRUE;
2647
  }
2648
  else {
2649
    drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
2650
    $cache_enabled = variable_get('cache');
2651
  }
2652
  drupal_block_denied(ip_address());
2653
  // If there is no session cookie and cache is enabled (or forced), try
2654
  // to serve a cached page.
2655
  if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
2656
    // Make sure there is a user object because its timestamp will be
2657
    // checked, hook_boot might check for anonymous user etc.
2658
    $user = drupal_anonymous_user();
2659
    // Get the page from the cache.
2660
    $cache = drupal_page_get_cache();
2661
    // If there is a cached page, display it.
2662
    if (is_object($cache)) {
2663
      header('X-Drupal-Cache: HIT');
2664
      // Restore the metadata cached with the page.
2665
      $_GET['q'] = $cache->data['path'];
2666
      drupal_set_title($cache->data['title'], PASS_THROUGH);
2667
      date_default_timezone_set(drupal_get_user_timezone());
2668
      // If the skipping of the bootstrap hooks is not enforced, call
2669
      // hook_boot.
2670
      if (variable_get('page_cache_invoke_hooks', TRUE)) {
2671
        bootstrap_invoke_all('boot');
2672
      }
2673
      drupal_serve_page_from_cache($cache);
2674
      // If the skipping of the bootstrap hooks is not enforced, call
2675
      // hook_exit.
2676
      if (variable_get('page_cache_invoke_hooks', TRUE)) {
2677
        bootstrap_invoke_all('exit');
2678
      }
2679
      // We are done.
2680
      exit;
2681
    }
2682
    else {
2683
      header('X-Drupal-Cache: MISS');
2684
    }
2685
  }
2686
}
2687

    
2688
/**
2689
 * Initializes the database system and registers autoload functions.
2690
 */
2691
function _drupal_bootstrap_database() {
2692
  // Redirect the user to the installation script if Drupal has not been
2693
  // installed yet (i.e., if no $databases array has been defined in the
2694
  // settings.php file) and we are not already installing.
2695
  if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
2696
    include_once DRUPAL_ROOT . '/includes/install.inc';
2697
    install_goto('install.php');
2698
  }
2699

    
2700
  // The user agent header is used to pass a database prefix in the request when
2701
  // running tests. However, for security reasons, it is imperative that we
2702
  // validate we ourselves made the request.
2703
  if ($test_prefix = drupal_valid_test_ua()) {
2704
    // Set the test run id for use in other parts of Drupal.
2705
    $test_info = &$GLOBALS['drupal_test_info'];
2706
    $test_info['test_run_id'] = $test_prefix;
2707
    $test_info['in_child_site'] = TRUE;
2708

    
2709
    foreach ($GLOBALS['databases']['default'] as &$value) {
2710
      // Extract the current default database prefix.
2711
      if (!isset($value['prefix'])) {
2712
        $current_prefix = '';
2713
      }
2714
      elseif (is_array($value['prefix'])) {
2715
        $current_prefix = $value['prefix']['default'];
2716
      }
2717
      else {
2718
        $current_prefix = $value['prefix'];
2719
      }
2720

    
2721
      // Remove the current database prefix and replace it by our own.
2722
      $value['prefix'] = array(
2723
        'default' => $current_prefix . $test_prefix,
2724
      );
2725
    }
2726
  }
2727

    
2728
  // Initialize the database system. Note that the connection
2729
  // won't be initialized until it is actually requested.
2730
  require_once DRUPAL_ROOT . '/includes/database/database.inc';
2731

    
2732
  // Register autoload functions so that we can access classes and interfaces.
2733
  // The database autoload routine comes first so that we can load the database
2734
  // system without hitting the database. That is especially important during
2735
  // the install or upgrade process.
2736
  spl_autoload_register('drupal_autoload_class');
2737
  spl_autoload_register('drupal_autoload_interface');
2738
  if (version_compare(PHP_VERSION, '5.4') >= 0) {
2739
    spl_autoload_register('drupal_autoload_trait');
2740
  }
2741
}
2742

    
2743
/**
2744
 * Loads system variables and all enabled bootstrap modules.
2745
 */
2746
function _drupal_bootstrap_variables() {
2747
  global $conf;
2748

    
2749
  // Initialize the lock system.
2750
  require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
2751
  lock_initialize();
2752

    
2753
  // Load variables from the database, but do not overwrite variables set in settings.php.
2754
  $conf = variable_initialize(isset($conf) ? $conf : array());
2755
  // Load bootstrap modules.
2756
  require_once DRUPAL_ROOT . '/includes/module.inc';
2757
  module_load_all(TRUE);
2758

    
2759
  // Sanitize the destination parameter (which is often used for redirects) to
2760
  // prevent open redirect attacks leading to other domains. Sanitize both
2761
  // $_GET['destination'] and $_REQUEST['destination'] to protect code that
2762
  // relies on either, but do not sanitize $_POST to avoid interfering with
2763
  // unrelated form submissions. The sanitization happens here because
2764
  // url_is_external() requires the variable system to be available.
2765
  if (isset($_GET['destination']) || isset($_REQUEST['destination'])) {
2766
    require_once DRUPAL_ROOT . '/includes/common.inc';
2767
    // If the destination is an external URL, remove it.
2768
    if (isset($_GET['destination']) && url_is_external($_GET['destination'])) {
2769
      unset($_GET['destination']);
2770
      unset($_REQUEST['destination']);
2771
    }
2772
    // If there's still something in $_REQUEST['destination'] that didn't come
2773
    // from $_GET, check it too.
2774
    if (isset($_REQUEST['destination']) && (!isset($_GET['destination']) || $_REQUEST['destination'] != $_GET['destination']) && url_is_external($_REQUEST['destination'])) {
2775
      unset($_REQUEST['destination']);
2776
    }
2777
  }
2778
}
2779

    
2780
/**
2781
 * Invokes hook_boot(), initializes locking system, and sends HTTP headers.
2782
 */
2783
function _drupal_bootstrap_page_header() {
2784
  bootstrap_invoke_all('boot');
2785

    
2786
  if (!drupal_is_cli()) {
2787
    ob_start();
2788
    drupal_page_header();
2789
  }
2790
}
2791

    
2792
/**
2793
 * Returns the current bootstrap phase for this Drupal process.
2794
 *
2795
 * The current phase is the one most recently completed by drupal_bootstrap().
2796
 *
2797
 * @see drupal_bootstrap()
2798
 */
2799
function drupal_get_bootstrap_phase() {
2800
  return drupal_bootstrap(NULL, FALSE);
2801
}
2802

    
2803
/**
2804
 * Returns the test prefix if this is an internal request from SimpleTest.
2805
 *
2806
 * @return
2807
 *   Either the simpletest prefix (the string "simpletest" followed by any
2808
 *   number of digits) or FALSE if the user agent does not contain a valid
2809
 *   HMAC and timestamp.
2810
 */
2811
function drupal_valid_test_ua() {
2812
  // No reason to reset this.
2813
  static $test_prefix;
2814

    
2815
  if (isset($test_prefix)) {
2816
    return $test_prefix;
2817
  }
2818

    
2819
  if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
2820
    list(, $prefix, $time, $salt, $hmac) = $matches;
2821
    $check_string =  $prefix . ';' . $time . ';' . $salt;
2822
    // We use the salt from settings.php to make the HMAC key, since
2823
    // the database is not yet initialized and we can't access any Drupal variables.
2824
    // The file properties add more entropy not easily accessible to others.
2825
    $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
2826
    $time_diff = REQUEST_TIME - $time;
2827
    // Since we are making a local request a 5 second time window is allowed,
2828
    // and the HMAC must match.
2829
    if ($time_diff >= 0 && $time_diff <= 5 && $hmac == drupal_hmac_base64($check_string, $key)) {
2830
      $test_prefix = $prefix;
2831
      return $test_prefix;
2832
    }
2833
  }
2834

    
2835
  $test_prefix = FALSE;
2836
  return $test_prefix;
2837
}
2838

    
2839
/**
2840
 * Generates a user agent string with a HMAC and timestamp for simpletest.
2841
 */
2842
function drupal_generate_test_ua($prefix) {
2843
  static $key;
2844

    
2845
  if (!isset($key)) {
2846
    // We use the salt from settings.php to make the HMAC key, since
2847
    // the database is not yet initialized and we can't access any Drupal variables.
2848
    // The file properties add more entropy not easily accessible to others.
2849
    $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
2850
  }
2851
  // Generate a moderately secure HMAC based on the database credentials.
2852
  $salt = uniqid('', TRUE);
2853
  $check_string = $prefix . ';' . time() . ';' . $salt;
2854
  return $check_string . ';' . drupal_hmac_base64($check_string, $key);
2855
}
2856

    
2857
/**
2858
 * Enables use of the theme system without requiring database access.
2859
 *
2860
 * Loads and initializes the theme system for site installs, updates and when
2861
 * the site is in maintenance mode. This also applies when the database fails.
2862
 *
2863
 * @see _drupal_maintenance_theme()
2864
 */
2865
function drupal_maintenance_theme() {
2866
  require_once DRUPAL_ROOT . '/includes/theme.maintenance.inc';
2867
  _drupal_maintenance_theme();
2868
}
2869

    
2870
/**
2871
 * Returns a simple 404 Not Found page.
2872
 *
2873
 * If fast 404 pages are enabled, and this is a matching page then print a
2874
 * simple 404 page and exit.
2875
 *
2876
 * This function is called from drupal_deliver_html_page() at the time when a
2877
 * a normal 404 page is generated, but it can also optionally be called directly
2878
 * from settings.php to prevent a Drupal bootstrap on these pages. See
2879
 * documentation in settings.php for the benefits and drawbacks of using this.
2880
 *
2881
 * Paths to dynamically-generated content, such as image styles, should also be
2882
 * accounted for in this function.
2883
 */
2884
function drupal_fast_404() {
2885
  $exclude_paths = variable_get('404_fast_paths_exclude', FALSE);
2886
  if ($exclude_paths && !preg_match($exclude_paths, $_GET['q'])) {
2887
    $fast_paths = variable_get('404_fast_paths', FALSE);
2888
    if ($fast_paths && preg_match($fast_paths, $_GET['q'])) {
2889
      drupal_add_http_header('Status', '404 Not Found');
2890
      $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>');
2891
      // Replace @path in the variable with the page path.
2892
      print strtr($fast_404_html, array('@path' => check_plain(request_uri())));
2893
      exit;
2894
    }
2895
  }
2896
}
2897

    
2898
/**
2899
 * Returns TRUE if a Drupal installation is currently being attempted.
2900
 */
2901
function drupal_installation_attempted() {
2902
  return defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install';
2903
}
2904

    
2905
/**
2906
 * Returns the name of the proper localization function.
2907
 *
2908
 * get_t() exists to support localization for code that might run during
2909
 * the installation phase, when some elements of the system might not have
2910
 * loaded.
2911
 *
2912
 * This would include implementations of hook_install(), which could run
2913
 * during the Drupal installation phase, and might also be run during
2914
 * non-installation time, such as while installing the module from the
2915
 * module administration page.
2916
 *
2917
 * Example usage:
2918
 * @code
2919
 *   $t = get_t();
2920
 *   $translated = $t('translate this');
2921
 * @endcode
2922
 *
2923
 * Use t() if your code will never run during the Drupal installation phase.
2924
 * Use st() if your code will only run during installation and never any other
2925
 * time. Use get_t() if your code could run in either circumstance.
2926
 *
2927
 * @see t()
2928
 * @see st()
2929
 * @ingroup sanitization
2930
 */
2931
function get_t() {
2932
  static $t;
2933
  // This is not converted to drupal_static because there is no point in
2934
  // resetting this as it can not change in the course of a request.
2935
  if (!isset($t)) {
2936
    $t = drupal_installation_attempted() ? 'st' : 't';
2937
  }
2938
  return $t;
2939
}
2940

    
2941
/**
2942
 * Initializes all the defined language types.
2943
 */
2944
function drupal_language_initialize() {
2945
  $types = language_types();
2946

    
2947
  // Ensure the language is correctly returned, even without multilanguage
2948
  // support. Also make sure we have a $language fallback, in case a language
2949
  // negotiation callback needs to do a full bootstrap.
2950
  // Useful for eg. XML/HTML 'lang' attributes.
2951
  $default = language_default();
2952
  foreach ($types as $type) {
2953
    $GLOBALS[$type] = $default;
2954
  }
2955
  if (drupal_multilingual()) {
2956
    include_once DRUPAL_ROOT . '/includes/language.inc';
2957
    foreach ($types as $type) {
2958
      $GLOBALS[$type] = language_initialize($type);
2959
    }
2960
    // Allow modules to react on language system initialization in multilingual
2961
    // environments.
2962
    bootstrap_invoke_all('language_init');
2963
  }
2964
}
2965

    
2966
/**
2967
 * Returns a list of the built-in language types.
2968
 *
2969
 * @return
2970
 *   An array of key-values pairs where the key is the language type and the
2971
 *   value is its configurability.
2972
 */
2973
function drupal_language_types() {
2974
  return array(
2975
    LANGUAGE_TYPE_INTERFACE => TRUE,
2976
    LANGUAGE_TYPE_CONTENT => FALSE,
2977
    LANGUAGE_TYPE_URL => FALSE,
2978
  );
2979
}
2980

    
2981
/**
2982
 * Returns TRUE if there is more than one language enabled.
2983
 *
2984
 * @return
2985
 *   TRUE if more than one language is enabled.
2986
 */
2987
function drupal_multilingual() {
2988
  // The "language_count" variable stores the number of enabled languages to
2989
  // avoid unnecessarily querying the database when building the list of
2990
  // enabled languages on monolingual sites.
2991
  return variable_get('language_count', 1) > 1;
2992
}
2993

    
2994
/**
2995
 * Returns an array of the available language types.
2996
 *
2997
 * @return
2998
 *   An array of all language types where the keys of each are the language type
2999
 *   name and its value is its configurability (TRUE/FALSE).
3000
 */
3001
function language_types() {
3002
  return array_keys(variable_get('language_types', drupal_language_types()));
3003
}
3004

    
3005
/**
3006
 * Returns a list of installed languages, indexed by the specified key.
3007
 *
3008
 * @param $field
3009
 *   (optional) The field to index the list with.
3010
 *
3011
 * @return
3012
 *   An associative array, keyed on the values of $field.
3013
 *   - If $field is 'weight' or 'enabled', the array is nested, with the outer
3014
 *     array's values each being associative arrays with language codes as
3015
 *     keys and language objects as values.
3016
 *   - For all other values of $field, the array is only one level deep, and
3017
 *     the array's values are language objects.
3018
 */
3019
function language_list($field = 'language') {
3020
  $languages = &drupal_static(__FUNCTION__);
3021
  // Init language list
3022
  if (!isset($languages)) {
3023
    if (drupal_multilingual() || module_exists('locale')) {
3024
      $languages['language'] = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC')->fetchAllAssoc('language');
3025
      // Users cannot uninstall the native English language. However, we allow
3026
      // it to be hidden from the installed languages. Therefore, at least one
3027
      // other language must be enabled then.
3028
      if (!$languages['language']['en']->enabled && !variable_get('language_native_enabled', TRUE)) {
3029
        unset($languages['language']['en']);
3030
      }
3031
    }
3032
    else {
3033
      // No locale module, so use the default language only.
3034
      $default = language_default();
3035
      $languages['language'][$default->language] = $default;
3036
    }
3037
  }
3038

    
3039
  // Return the array indexed by the right field
3040
  if (!isset($languages[$field])) {
3041
    $languages[$field] = array();
3042
    foreach ($languages['language'] as $lang) {
3043
      // Some values should be collected into an array
3044
      if (in_array($field, array('enabled', 'weight'))) {
3045
        $languages[$field][$lang->$field][$lang->language] = $lang;
3046
      }
3047
      else {
3048
        $languages[$field][$lang->$field] = $lang;
3049
      }
3050
    }
3051
  }
3052
  return $languages[$field];
3053
}
3054

    
3055
/**
3056
 * Returns the default language, as an object, or one of its properties.
3057
 *
3058
 * @param $property
3059
 *   (optional) The property of the language object to return.
3060
 *
3061
 * @return
3062
 *   Either the language object for the default language used on the site,
3063
 *   or the property of that object named in the $property parameter.
3064
 */
3065
function language_default($property = NULL) {
3066
  $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' => ''));
3067
  return $property ? $language->$property : $language;
3068
}
3069

    
3070
/**
3071
 * Returns the requested URL path of the page being viewed.
3072
 *
3073
 * Examples:
3074
 * - http://example.com/node/306 returns "node/306".
3075
 * - http://example.com/drupalfolder/node/306 returns "node/306" while
3076
 *   base_path() returns "/drupalfolder/".
3077
 * - http://example.com/path/alias (which is a path alias for node/306) returns
3078
 *   "path/alias" as opposed to the internal path.
3079
 * - http://example.com/index.php returns an empty string (meaning: front page).
3080
 * - http://example.com/index.php?page=1 returns an empty string.
3081
 *
3082
 * @return
3083
 *   The requested Drupal URL path.
3084
 *
3085
 * @see current_path()
3086
 */
3087
function request_path() {
3088
  static $path;
3089

    
3090
  if (isset($path)) {
3091
    return $path;
3092
  }
3093

    
3094
  if (isset($_GET['q']) && is_string($_GET['q'])) {
3095
    // This is a request with a ?q=foo/bar query string. $_GET['q'] is
3096
    // overwritten in drupal_path_initialize(), but request_path() is called
3097
    // very early in the bootstrap process, so the original value is saved in
3098
    // $path and returned in later calls.
3099
    $path = $_GET['q'];
3100
  }
3101
  elseif (isset($_SERVER['REQUEST_URI'])) {
3102
    // This request is either a clean URL, or 'index.php', or nonsense.
3103
    // Extract the path from REQUEST_URI.
3104
    $request_path = strtok($_SERVER['REQUEST_URI'], '?');
3105
    $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
3106
    // Unescape and strip $base_path prefix, leaving q without a leading slash.
3107
    $path = substr(urldecode($request_path), $base_path_len + 1);
3108
    // If the path equals the script filename, either because 'index.php' was
3109
    // explicitly provided in the URL, or because the server added it to
3110
    // $_SERVER['REQUEST_URI'] even when it wasn't provided in the URL (some
3111
    // versions of Microsoft IIS do this), the front page should be served.
3112
    if ($path == basename($_SERVER['PHP_SELF'])) {
3113
      $path = '';
3114
    }
3115
  }
3116
  else {
3117
    // This is the front page.
3118
    $path = '';
3119
  }
3120

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

    
3126
  return $path;
3127
}
3128

    
3129
/**
3130
 * Returns a component of the current Drupal path.
3131
 *
3132
 * When viewing a page at the path "admin/structure/types", for example, arg(0)
3133
 * returns "admin", arg(1) returns "structure", and arg(2) returns "types".
3134
 *
3135
 * Avoid use of this function where possible, as resulting code is hard to
3136
 * read. In menu callback functions, attempt to use named arguments. See the
3137
 * explanation in menu.inc for how to construct callbacks that take arguments.
3138
 * When attempting to use this function to load an element from the current
3139
 * path, e.g. loading the node on a node page, use menu_get_object() instead.
3140
 *
3141
 * @param $index
3142
 *   The index of the component, where each component is separated by a '/'
3143
 *   (forward-slash), and where the first component has an index of 0 (zero).
3144
 * @param $path
3145
 *   A path to break into components. Defaults to the path of the current page.
3146
 *
3147
 * @return
3148
 *   The component specified by $index, or NULL if the specified component was
3149
 *   not found. If called without arguments, it returns an array containing all
3150
 *   the components of the current path.
3151
 */
3152
function arg($index = NULL, $path = NULL) {
3153
  // Even though $arguments doesn't need to be resettable for any functional
3154
  // reasons (the result of explode() does not depend on any run-time
3155
  // information), it should be resettable anyway in case a module needs to
3156
  // free up the memory used by it.
3157
  // Use the advanced drupal_static() pattern, since this is called very often.
3158
  static $drupal_static_fast;
3159
  if (!isset($drupal_static_fast)) {
3160
    $drupal_static_fast['arguments'] = &drupal_static(__FUNCTION__);
3161
  }
3162
  $arguments = &$drupal_static_fast['arguments'];
3163

    
3164
  if (!isset($path)) {
3165
    $path = $_GET['q'];
3166
  }
3167
  if (!isset($arguments[$path])) {
3168
    $arguments[$path] = explode('/', $path);
3169
  }
3170
  if (!isset($index)) {
3171
    return $arguments[$path];
3172
  }
3173
  if (isset($arguments[$path][$index])) {
3174
    return $arguments[$path][$index];
3175
  }
3176
}
3177

    
3178
/**
3179
 * Returns the IP address of the client machine.
3180
 *
3181
 * If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
3182
 * instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of
3183
 * the proxy server, and not the client's. The actual header name can be
3184
 * configured by the reverse_proxy_header variable.
3185
 *
3186
 * @return
3187
 *   IP address of client machine, adjusted for reverse proxy and/or cluster
3188
 *   environments.
3189
 */
3190
function ip_address() {
3191
  $ip_address = &drupal_static(__FUNCTION__);
3192

    
3193
  if (!isset($ip_address)) {
3194
    $ip_address = $_SERVER['REMOTE_ADDR'];
3195

    
3196
    if (variable_get('reverse_proxy', 0)) {
3197
      $reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
3198
      if (!empty($_SERVER[$reverse_proxy_header])) {
3199
        // If an array of known reverse proxy IPs is provided, then trust
3200
        // the XFF header if request really comes from one of them.
3201
        $reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
3202

    
3203
        // Turn XFF header into an array.
3204
        $forwarded = explode(',', $_SERVER[$reverse_proxy_header]);
3205

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

    
3209
        // Tack direct client IP onto end of forwarded array.
3210
        $forwarded[] = $ip_address;
3211

    
3212
        // Eliminate all trusted IPs.
3213
        $untrusted = array_diff($forwarded, $reverse_proxy_addresses);
3214

    
3215
        if (!empty($untrusted)) {
3216
          // The right-most IP is the most specific we can trust.
3217
          $ip_address = array_pop($untrusted);
3218
        }
3219
        else {
3220
          // All IP addresses in the forwarded array are configured proxy IPs
3221
          // (and thus trusted). We take the leftmost IP.
3222
          $ip_address = array_shift($forwarded);
3223
        }
3224
      }
3225
    }
3226
  }
3227

    
3228
  return $ip_address;
3229
}
3230

    
3231
/**
3232
 * @addtogroup schemaapi
3233
 * @{
3234
 */
3235

    
3236
/**
3237
 * Gets the schema definition of a table, or the whole database schema.
3238
 *
3239
 * The returned schema will include any modifications made by any
3240
 * module that implements hook_schema_alter(). To get the schema without
3241
 * modifications, use drupal_get_schema_unprocessed().
3242
 *
3243
 *
3244
 * @param $table
3245
 *   The name of the table. If not given, the schema of all tables is returned.
3246
 * @param $rebuild
3247
 *   If true, the schema will be rebuilt instead of retrieved from the cache.
3248
 */
3249
function drupal_get_schema($table = NULL, $rebuild = FALSE) {
3250
  static $schema;
3251

    
3252
  if ($rebuild || !isset($table)) {
3253
    $schema = drupal_get_complete_schema($rebuild);
3254
  }
3255
  elseif (!isset($schema)) {
3256
    $schema = new SchemaCache();
3257
  }
3258

    
3259
  if (!isset($table)) {
3260
    return $schema;
3261
  }
3262
  if (isset($schema[$table])) {
3263
    return $schema[$table];
3264
  }
3265
  else {
3266
    return FALSE;
3267
  }
3268
}
3269

    
3270
/**
3271
 * Extends DrupalCacheArray to allow for dynamic building of the schema cache.
3272
 */
3273
class SchemaCache extends DrupalCacheArray {
3274

    
3275
  /**
3276
   * Constructs a SchemaCache object.
3277
   */
3278
  public function __construct() {
3279
    // Cache by request method.
3280
    parent::__construct('schema:runtime:' . ($_SERVER['REQUEST_METHOD'] == 'GET'), 'cache');
3281
  }
3282

    
3283
  /**
3284
   * Overrides DrupalCacheArray::resolveCacheMiss().
3285
   */
3286
  protected function resolveCacheMiss($offset) {
3287
    $complete_schema = drupal_get_complete_schema();
3288
    $value = isset($complete_schema[$offset]) ? $complete_schema[$offset] :  NULL;
3289
    $this->storage[$offset] = $value;
3290
    $this->persist($offset);
3291
    return $value;
3292
  }
3293
}
3294

    
3295
/**
3296
 * Gets the whole database schema.
3297
 *
3298
 * The returned schema will include any modifications made by any
3299
 * module that implements hook_schema_alter().
3300
 *
3301
 * @param $rebuild
3302
 *   If true, the schema will be rebuilt instead of retrieved from the cache.
3303
 */
3304
function drupal_get_complete_schema($rebuild = FALSE) {
3305
  static $schema = array();
3306

    
3307
  if (empty($schema) || $rebuild) {
3308
    // Try to load the schema from cache.
3309
    if (!$rebuild && $cached = cache_get('schema')) {
3310
      $schema = $cached->data;
3311
    }
3312
    // Otherwise, rebuild the schema cache.
3313
    else {
3314
      $schema = array();
3315
      // Load the .install files to get hook_schema.
3316
      // On some databases this function may be called before bootstrap has
3317
      // been completed, so we force the functions we need to load just in case.
3318
      if (function_exists('module_load_all_includes')) {
3319
        // This function can be called very early in the bootstrap process, so
3320
        // we force the module_list() cache to be refreshed to ensure that it
3321
        // contains the complete list of modules before we go on to call
3322
        // module_load_all_includes().
3323
        module_list(TRUE);
3324
        module_load_all_includes('install');
3325
      }
3326

    
3327
      require_once DRUPAL_ROOT . '/includes/common.inc';
3328
      // Invoke hook_schema for all modules.
3329
      foreach (module_implements('schema') as $module) {
3330
        // Cast the result of hook_schema() to an array, as a NULL return value
3331
        // would cause array_merge() to set the $schema variable to NULL as well.
3332
        // That would break modules which use $schema further down the line.
3333
        $current = (array) module_invoke($module, 'schema');
3334
        // Set 'module' and 'name' keys for each table, and remove descriptions,
3335
        // as they needlessly slow down cache_get() for every single request.
3336
        _drupal_schema_initialize($current, $module);
3337
        $schema = array_merge($schema, $current);
3338
      }
3339

    
3340
      drupal_alter('schema', $schema);
3341
      // If the schema is empty, avoid saving it: some database engines require
3342
      // the schema to perform queries, and this could lead to infinite loops.
3343
      if (!empty($schema) && (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL)) {
3344
        cache_set('schema', $schema);
3345
      }
3346
      if ($rebuild) {
3347
        cache_clear_all('schema:', 'cache', TRUE);
3348
      }
3349
    }
3350
  }
3351

    
3352
  return $schema;
3353
}
3354

    
3355
/**
3356
 * @} End of "addtogroup schemaapi".
3357
 */
3358

    
3359

    
3360
/**
3361
 * @addtogroup registry
3362
 * @{
3363
 */
3364

    
3365
/**
3366
 * Confirms that an interface is available.
3367
 *
3368
 * This function is rarely called directly. Instead, it is registered as an
3369
 * spl_autoload()  handler, and PHP calls it for us when necessary.
3370
 *
3371
 * @param $interface
3372
 *   The name of the interface to check or load.
3373
 *
3374
 * @return
3375
 *   TRUE if the interface is currently available, FALSE otherwise.
3376
 */
3377
function drupal_autoload_interface($interface) {
3378
  return _registry_check_code('interface', $interface);
3379
}
3380

    
3381
/**
3382
 * Confirms that a class is available.
3383
 *
3384
 * This function is rarely called directly. Instead, it is registered as an
3385
 * spl_autoload()  handler, and PHP calls it for us when necessary.
3386
 *
3387
 * @param $class
3388
 *   The name of the class to check or load.
3389
 *
3390
 * @return
3391
 *   TRUE if the class is currently available, FALSE otherwise.
3392
 */
3393
function drupal_autoload_class($class) {
3394
  return _registry_check_code('class', $class);
3395
}
3396

    
3397
/**
3398
 * Confirms that a trait is available.
3399
 *
3400
 * This function is rarely called directly. Instead, it is registered as an
3401
 * spl_autoload() handler, and PHP calls it for us when necessary.
3402
 *
3403
 * @param string $trait
3404
 *   The name of the trait to check or load.
3405
 *
3406
 * @return bool
3407
 *   TRUE if the trait is currently available, FALSE otherwise.
3408
 */
3409
function drupal_autoload_trait($trait) {
3410
  return _registry_check_code('trait', $trait);
3411
}
3412

    
3413
/**
3414
 * Checks for a resource in the registry.
3415
 *
3416
 * @param $type
3417
 *   The type of resource we are looking up, or one of the constants
3418
 *   REGISTRY_RESET_LOOKUP_CACHE or REGISTRY_WRITE_LOOKUP_CACHE, which
3419
 *   signal that we should reset or write the cache, respectively.
3420
 * @param $name
3421
 *   The name of the resource, or NULL if either of the REGISTRY_* constants
3422
 *   is passed in.
3423
 *
3424
 * @return
3425
 *   TRUE if the resource was found, FALSE if not.
3426
 *   NULL if either of the REGISTRY_* constants is passed in as $type.
3427
 */
3428
function _registry_check_code($type, $name = NULL) {
3429
  static $lookup_cache, $cache_update_needed;
3430

    
3431
  if ($type == 'class' && class_exists($name) || $type == 'interface' && interface_exists($name) || $type == 'trait' && trait_exists($name)) {
3432
    return TRUE;
3433
  }
3434

    
3435
  if (!isset($lookup_cache)) {
3436
    $lookup_cache = array();
3437
    if ($cache = cache_get('lookup_cache', 'cache_bootstrap')) {
3438
      $lookup_cache = $cache->data;
3439
    }
3440
  }
3441

    
3442
  // When we rebuild the registry, we need to reset this cache so
3443
  // we don't keep lookups for resources that changed during the rebuild.
3444
  if ($type == REGISTRY_RESET_LOOKUP_CACHE) {
3445
    $cache_update_needed = TRUE;
3446
    $lookup_cache = NULL;
3447
    return;
3448
  }
3449

    
3450
  // Called from drupal_page_footer, we write to permanent storage if there
3451
  // changes to the lookup cache for this request.
3452
  if ($type == REGISTRY_WRITE_LOOKUP_CACHE) {
3453
    if ($cache_update_needed) {
3454
      cache_set('lookup_cache', $lookup_cache, 'cache_bootstrap');
3455
    }
3456
    return;
3457
  }
3458

    
3459
  // $type is either 'interface' or 'class', so we only need the first letter to
3460
  // keep the cache key unique.
3461
  $cache_key = $type[0] . $name;
3462
  if (isset($lookup_cache[$cache_key])) {
3463
    if ($lookup_cache[$cache_key]) {
3464
      include_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
3465
    }
3466
    return (bool) $lookup_cache[$cache_key];
3467
  }
3468

    
3469
  // This function may get called when the default database is not active, but
3470
  // there is no reason we'd ever want to not use the default database for
3471
  // this query.
3472
  $file = Database::getConnection('default', 'default')
3473
    ->select('registry', 'r', array('target' => 'default'))
3474
    ->fields('r', array('filename'))
3475
    // Use LIKE here to make the query case-insensitive.
3476
    ->condition('r.name', db_like($name), 'LIKE')
3477
    ->condition('r.type', $type)
3478
    ->execute()
3479
    ->fetchField();
3480

    
3481
  // Flag that we've run a lookup query and need to update the cache.
3482
  $cache_update_needed = TRUE;
3483

    
3484
  // Misses are valuable information worth caching, so cache even if
3485
  // $file is FALSE.
3486
  $lookup_cache[$cache_key] = $file;
3487

    
3488
  if ($file) {
3489
    include_once DRUPAL_ROOT . '/' . $file;
3490
    return TRUE;
3491
  }
3492
  else {
3493
    return FALSE;
3494
  }
3495
}
3496

    
3497
/**
3498
 * Rescans all enabled modules and rebuilds the registry.
3499
 *
3500
 * Rescans all code in modules or includes directories, storing the location of
3501
 * each interface or class in the database.
3502
 */
3503
function registry_rebuild() {
3504
  system_rebuild_module_data();
3505
  registry_update();
3506
}
3507

    
3508
/**
3509
 * Updates the registry based on the latest files listed in the database.
3510
 *
3511
 * This function should be used when system_rebuild_module_data() does not need
3512
 * to be called, because it is already known that the list of files in the
3513
 * {system} table matches those in the file system.
3514
 *
3515
 * @return
3516
 *   TRUE if the registry was rebuilt, FALSE if another thread was rebuilding
3517
 *   in parallel and the current thread just waited for completion.
3518
 *
3519
 * @see registry_rebuild()
3520
 */
3521
function registry_update() {
3522
  // install_system_module() calls module_enable() which calls into this
3523
  // function during initial system installation, so the lock system is neither
3524
  // loaded nor does its storage exist yet.
3525
  $in_installer = drupal_installation_attempted();
3526
  if (!$in_installer && !lock_acquire(__FUNCTION__)) {
3527
    // Another request got the lock, wait for it to finish.
3528
    lock_wait(__FUNCTION__);
3529
    return FALSE;
3530
  }
3531

    
3532
  require_once DRUPAL_ROOT . '/includes/registry.inc';
3533
  _registry_update();
3534

    
3535
  if (!$in_installer) {
3536
    lock_release(__FUNCTION__);
3537
  }
3538
  return TRUE;
3539
}
3540

    
3541
/**
3542
 * @} End of "addtogroup registry".
3543
 */
3544

    
3545
/**
3546
 * Provides central static variable storage.
3547
 *
3548
 * All functions requiring a static variable to persist or cache data within
3549
 * a single page request are encouraged to use this function unless it is
3550
 * absolutely certain that the static variable will not need to be reset during
3551
 * the page request. By centralizing static variable storage through this
3552
 * function, other functions can rely on a consistent API for resetting any
3553
 * other function's static variables.
3554
 *
3555
 * Example:
3556
 * @code
3557
 * function language_list($field = 'language') {
3558
 *   $languages = &drupal_static(__FUNCTION__);
3559
 *   if (!isset($languages)) {
3560
 *     // If this function is being called for the first time after a reset,
3561
 *     // query the database and execute any other code needed to retrieve
3562
 *     // information about the supported languages.
3563
 *     ...
3564
 *   }
3565
 *   if (!isset($languages[$field])) {
3566
 *     // If this function is being called for the first time for a particular
3567
 *     // index field, then execute code needed to index the information already
3568
 *     // available in $languages by the desired field.
3569
 *     ...
3570
 *   }
3571
 *   // Subsequent invocations of this function for a particular index field
3572
 *   // skip the above two code blocks and quickly return the already indexed
3573
 *   // information.
3574
 *   return $languages[$field];
3575
 * }
3576
 * function locale_translate_overview_screen() {
3577
 *   // When building the content for the translations overview page, make
3578
 *   // sure to get completely fresh information about the supported languages.
3579
 *   drupal_static_reset('language_list');
3580
 *   ...
3581
 * }
3582
 * @endcode
3583
 *
3584
 * In a few cases, a function can have certainty that there is no legitimate
3585
 * use-case for resetting that function's static variable. This is rare,
3586
 * because when writing a function, it's hard to forecast all the situations in
3587
 * which it will be used. A guideline is that if a function's static variable
3588
 * does not depend on any information outside of the function that might change
3589
 * during a single page request, then it's ok to use the "static" keyword
3590
 * instead of the drupal_static() function.
3591
 *
3592
 * Example:
3593
 * @code
3594
 * function actions_do(...) {
3595
 *   // $stack tracks the number of recursive calls.
3596
 *   static $stack;
3597
 *   $stack++;
3598
 *   if ($stack > variable_get('actions_max_stack', 35)) {
3599
 *     ...
3600
 *     return;
3601
 *   }
3602
 *   ...
3603
 *   $stack--;
3604
 * }
3605
 * @endcode
3606
 *
3607
 * In a few cases, a function needs a resettable static variable, but the
3608
 * function is called many times (100+) during a single page request, so
3609
 * every microsecond of execution time that can be removed from the function
3610
 * counts. These functions can use a more cumbersome, but faster variant of
3611
 * calling drupal_static(). It works by storing the reference returned by
3612
 * drupal_static() in the calling function's own static variable, thereby
3613
 * removing the need to call drupal_static() for each iteration of the function.
3614
 * Conceptually, it replaces:
3615
 * @code
3616
 * $foo = &drupal_static(__FUNCTION__);
3617
 * @endcode
3618
 * with:
3619
 * @code
3620
 * // Unfortunately, this does not work.
3621
 * static $foo = &drupal_static(__FUNCTION__);
3622
 * @endcode
3623
 * However, the above line of code does not work, because PHP only allows static
3624
 * variables to be initializied by literal values, and does not allow static
3625
 * variables to be assigned to references.
3626
 * - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
3627
 * - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
3628
 * The example below shows the syntax needed to work around both limitations.
3629
 * For benchmarks and more information, see http://drupal.org/node/619666.
3630
 *
3631
 * Example:
3632
 * @code
3633
 * function user_access($string, $account = NULL) {
3634
 *   // Use the advanced drupal_static() pattern, since this is called very often.
3635
 *   static $drupal_static_fast;
3636
 *   if (!isset($drupal_static_fast)) {
3637
 *     $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
3638
 *   }
3639
 *   $perm = &$drupal_static_fast['perm'];
3640
 *   ...
3641
 * }
3642
 * @endcode
3643
 *
3644
 * @param $name
3645
 *   Globally unique name for the variable. For a function with only one static,
3646
 *   variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
3647
 *   is recommended. For a function with multiple static variables add a
3648
 *   distinguishing suffix to the function name for each one.
3649
 * @param $default_value
3650
 *   Optional default value.
3651
 * @param $reset
3652
 *   TRUE to reset one or all variables(s). This parameter is only used
3653
 *   internally and should not be passed in; use drupal_static_reset() instead.
3654
 *   (This function's return value should not be used when TRUE is passed in.)
3655
 *
3656
 * @return
3657
 *   Returns a variable by reference.
3658
 *
3659
 * @see drupal_static_reset()
3660
 */
3661
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
3662
  static $data = array(), $default = array();
3663
  // First check if dealing with a previously defined static variable.
3664
  if (isset($data[$name]) || array_key_exists($name, $data)) {
3665
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
3666
    if ($reset) {
3667
      // Reset pre-existing static variable to its default value.
3668
      $data[$name] = $default[$name];
3669
    }
3670
    return $data[$name];
3671
  }
3672
  // Neither $data[$name] nor $default[$name] static variables exist.
3673
  if (isset($name)) {
3674
    if ($reset) {
3675
      // Reset was called before a default is set and yet a variable must be
3676
      // returned.
3677
      return $data;
3678
    }
3679
    // First call with new non-NULL $name. Initialize a new static variable.
3680
    $default[$name] = $data[$name] = $default_value;
3681
    return $data[$name];
3682
  }
3683
  // Reset all: ($name == NULL). This needs to be done one at a time so that
3684
  // references returned by earlier invocations of drupal_static() also get
3685
  // reset.
3686
  foreach ($default as $name => $value) {
3687
    $data[$name] = $value;
3688
  }
3689
  // As the function returns a reference, the return should always be a
3690
  // variable.
3691
  return $data;
3692
}
3693

    
3694
/**
3695
 * Resets one or all centrally stored static variable(s).
3696
 *
3697
 * @param $name
3698
 *   Name of the static variable to reset. Omit to reset all variables.
3699
 *   Resetting all variables should only be used, for example, for running unit
3700
 *   tests with a clean environment.
3701
 */
3702
function drupal_static_reset($name = NULL) {
3703
  drupal_static($name, NULL, TRUE);
3704
}
3705

    
3706
/**
3707
 * Detects whether the current script is running in a command-line environment.
3708
 */
3709
function drupal_is_cli() {
3710
  return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
3711
}
3712

    
3713
/**
3714
 * Formats text for emphasized display in a placeholder inside a sentence.
3715
 *
3716
 * Used automatically by format_string().
3717
 *
3718
 * @param $text
3719
 *   The text to format (plain-text).
3720
 *
3721
 * @return
3722
 *   The formatted text (html).
3723
 */
3724
function drupal_placeholder($text) {
3725
  return '<em class="placeholder">' . check_plain($text) . '</em>';
3726
}
3727

    
3728
/**
3729
 * Registers a function for execution on shutdown.
3730
 *
3731
 * Wrapper for register_shutdown_function() that catches thrown exceptions to
3732
 * avoid "Exception thrown without a stack frame in Unknown".
3733
 *
3734
 * @param $callback
3735
 *   The shutdown function to register.
3736
 * @param ...
3737
 *   Additional arguments to pass to the shutdown function.
3738
 *
3739
 * @return
3740
 *   Array of shutdown functions to be executed.
3741
 *
3742
 * @see register_shutdown_function()
3743
 * @ingroup php_wrappers
3744
 */
3745
function &drupal_register_shutdown_function($callback = NULL) {
3746
  // We cannot use drupal_static() here because the static cache is reset during
3747
  // batch processing, which breaks batch handling.
3748
  static $callbacks = array();
3749

    
3750
  if (isset($callback)) {
3751
    // Only register the internal shutdown function once.
3752
    if (empty($callbacks)) {
3753
      register_shutdown_function('_drupal_shutdown_function');
3754
    }
3755
    $args = func_get_args();
3756
    array_shift($args);
3757
    // Save callback and arguments
3758
    $callbacks[] = array('callback' => $callback, 'arguments' => $args);
3759
  }
3760
  return $callbacks;
3761
}
3762

    
3763
/**
3764
 * Executes registered shutdown functions.
3765
 */
3766
function _drupal_shutdown_function() {
3767
  $callbacks = &drupal_register_shutdown_function();
3768

    
3769
  // Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
3770
  // was in the normal context of execution.
3771
  chdir(DRUPAL_ROOT);
3772

    
3773
  try {
3774
    while (list($key, $callback) = each($callbacks)) {
3775
      call_user_func_array($callback['callback'], $callback['arguments']);
3776
    }
3777
  }
3778
  catch (Exception $exception) {
3779
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
3780
   require_once DRUPAL_ROOT . '/includes/errors.inc';
3781
   if (error_displayable()) {
3782
      print '<h1>Uncaught exception thrown in shutdown function.</h1>';
3783
      print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
3784
    }
3785
  }
3786
}
3787

    
3788
/**
3789
 * Compares the memory required for an operation to the available memory.
3790
 *
3791
 * @param $required
3792
 *   The memory required for the operation, expressed as a number of bytes with
3793
 *   optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
3794
 *   9mbytes).
3795
 * @param $memory_limit
3796
 *   (optional) The memory limit for the operation, expressed as a number of
3797
 *   bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
3798
 *   6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
3799
 *   memory_limit will be used. Defaults to NULL.
3800
 *
3801
 * @return
3802
 *   TRUE if there is sufficient memory to allow the operation, or FALSE
3803
 *   otherwise.
3804
 */
3805
function drupal_check_memory_limit($required, $memory_limit = NULL) {
3806
  if (!isset($memory_limit)) {
3807
    $memory_limit = ini_get('memory_limit');
3808
  }
3809

    
3810
  // There is sufficient memory if:
3811
  // - No memory limit is set.
3812
  // - The memory limit is set to unlimited (-1).
3813
  // - The memory limit is greater than the memory required for the operation.
3814
  return ((!$memory_limit) || ($memory_limit == -1) || (parse_size($memory_limit) >= parse_size($required)));
3815
}
3816

    
3817
/**
3818
 * Invalidates a PHP file from any active opcode caches.
3819
 *
3820
 * If the opcode cache does not support the invalidation of individual files,
3821
 * the entire cache will be flushed.
3822
 *
3823
 * @param string $filepath
3824
 *   The absolute path of the PHP file to invalidate.
3825
 */
3826
function drupal_clear_opcode_cache($filepath) {
3827
  if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300) {
3828
    // Below PHP 5.3, clearstatcache does not accept any function parameters.
3829
    clearstatcache();
3830
  }
3831
  else {
3832
    clearstatcache(TRUE, $filepath);
3833
  }
3834

    
3835
  // Zend OPcache.
3836
  if (function_exists('opcache_invalidate')) {
3837
    opcache_invalidate($filepath, TRUE);
3838
  }
3839
  // APC.
3840
  if (function_exists('apc_delete_file')) {
3841
    // apc_delete_file() throws a PHP warning in case the specified file was
3842
    // not compiled yet.
3843
    // @see http://php.net/apc-delete-file
3844
    @apc_delete_file($filepath);
3845
  }
3846
}