bootstrap.inc 138 KB

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