bootstrap.inc 132 KB

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