bootstrap.inc 114 KB

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