bootstrap.inc 116 KB

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