bootstrap.inc 131 KB

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