common.inc 309 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559
  1. <?php
  2. /**
  3. * @file
  4. * Common functions that many Drupal modules will need to reference.
  5. *
  6. * The functions that are critical and need to be available even when serving
  7. * a cached page are instead located in bootstrap.inc.
  8. */
  9. /**
  10. * @defgroup php_wrappers PHP wrapper functions
  11. * @{
  12. * Functions that are wrappers or custom implementations of PHP functions.
  13. *
  14. * Certain PHP functions should not be used in Drupal. Instead, Drupal's
  15. * replacement functions should be used.
  16. *
  17. * For example, for improved or more secure UTF8-handling, or RFC-compliant
  18. * handling of URLs in Drupal.
  19. *
  20. * For ease of use and memorizing, all these wrapper functions use the same name
  21. * as the original PHP function, but prefixed with "drupal_". Beware, however,
  22. * that not all wrapper functions support the same arguments as the original
  23. * functions.
  24. *
  25. * You should always use these wrapper functions in your code.
  26. *
  27. * Wrong:
  28. * @code
  29. * $my_substring = substr($original_string, 0, 5);
  30. * @endcode
  31. *
  32. * Correct:
  33. * @code
  34. * $my_substring = drupal_substr($original_string, 0, 5);
  35. * @endcode
  36. *
  37. * @}
  38. */
  39. /**
  40. * Return status for saving which involved creating a new item.
  41. */
  42. define('SAVED_NEW', 1);
  43. /**
  44. * Return status for saving which involved an update to an existing item.
  45. */
  46. define('SAVED_UPDATED', 2);
  47. /**
  48. * Return status for saving which deleted an existing item.
  49. */
  50. define('SAVED_DELETED', 3);
  51. /**
  52. * The default group for system CSS files added to the page.
  53. */
  54. define('CSS_SYSTEM', -100);
  55. /**
  56. * The default group for module CSS files added to the page.
  57. */
  58. define('CSS_DEFAULT', 0);
  59. /**
  60. * The default group for theme CSS files added to the page.
  61. */
  62. define('CSS_THEME', 100);
  63. /**
  64. * The default group for JavaScript and jQuery libraries added to the page.
  65. */
  66. define('JS_LIBRARY', -100);
  67. /**
  68. * The default group for module JavaScript code added to the page.
  69. */
  70. define('JS_DEFAULT', 0);
  71. /**
  72. * The default group for theme JavaScript code added to the page.
  73. */
  74. define('JS_THEME', 100);
  75. /**
  76. * Error code indicating that the request exceeded the specified timeout.
  77. *
  78. * @see drupal_http_request()
  79. */
  80. define('HTTP_REQUEST_TIMEOUT', -1);
  81. /**
  82. * @defgroup block_caching Block Caching
  83. * @{
  84. * Constants that define each block's caching state.
  85. *
  86. * Modules specify how their blocks can be cached in their hook_block_info()
  87. * implementations. Caching can be turned off (DRUPAL_NO_CACHE), managed by the
  88. * module declaring the block (DRUPAL_CACHE_CUSTOM), or managed by the core
  89. * Block module. If the Block module is managing the cache, you can specify that
  90. * the block is the same for every page and user (DRUPAL_CACHE_GLOBAL), or that
  91. * it can change depending on the page (DRUPAL_CACHE_PER_PAGE) or by user
  92. * (DRUPAL_CACHE_PER_ROLE or DRUPAL_CACHE_PER_USER). Page and user settings can
  93. * be combined with a bitwise-binary or operator; for example,
  94. * DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change
  95. * depending on the user role or page it is on.
  96. *
  97. * The block cache is cleared in cache_clear_all(), and uses the same clearing
  98. * policy than page cache (node, comment, user, taxonomy added or updated...).
  99. * Blocks requiring more fine-grained clearing might consider disabling the
  100. * built-in block cache (DRUPAL_NO_CACHE) and roll their own.
  101. *
  102. * Note that user 1 is excluded from block caching.
  103. */
  104. /**
  105. * The block should not get cached.
  106. *
  107. * This setting should be used:
  108. * - For simple blocks (notably those that do not perform any db query), where
  109. * querying the db cache would be more expensive than directly generating the
  110. * content.
  111. * - For blocks that change too frequently.
  112. */
  113. define('DRUPAL_NO_CACHE', -1);
  114. /**
  115. * The block is handling its own caching in its hook_block_view().
  116. *
  117. * This setting is useful when time based expiration is needed or a site uses a
  118. * node access which invalidates standard block cache.
  119. */
  120. define('DRUPAL_CACHE_CUSTOM', -2);
  121. /**
  122. * The block or element can change depending on the user's roles.
  123. *
  124. * This is the default setting for blocks, used when the block does not specify
  125. * anything.
  126. */
  127. define('DRUPAL_CACHE_PER_ROLE', 0x0001);
  128. /**
  129. * The block or element can change depending on the user.
  130. *
  131. * This setting can be resource-consuming for sites with large number of users,
  132. * and thus should only be used when DRUPAL_CACHE_PER_ROLE is not sufficient.
  133. */
  134. define('DRUPAL_CACHE_PER_USER', 0x0002);
  135. /**
  136. * The block or element can change depending on the page being viewed.
  137. */
  138. define('DRUPAL_CACHE_PER_PAGE', 0x0004);
  139. /**
  140. * The block or element is the same for every user and page that it is visible.
  141. */
  142. define('DRUPAL_CACHE_GLOBAL', 0x0008);
  143. /**
  144. * @} End of "defgroup block_caching".
  145. */
  146. /**
  147. * Adds content to a specified region.
  148. *
  149. * @param $region
  150. * Page region the content is added to.
  151. * @param $data
  152. * Content to be added.
  153. */
  154. function drupal_add_region_content($region = NULL, $data = NULL) {
  155. static $content = array();
  156. if (isset($region) && isset($data)) {
  157. $content[$region][] = $data;
  158. }
  159. return $content;
  160. }
  161. /**
  162. * Gets assigned content for a given region.
  163. *
  164. * @param $region
  165. * A specified region to fetch content for. If NULL, all regions will be
  166. * returned.
  167. * @param $delimiter
  168. * Content to be inserted between imploded array elements.
  169. */
  170. function drupal_get_region_content($region = NULL, $delimiter = ' ') {
  171. $content = drupal_add_region_content();
  172. if (isset($region)) {
  173. if (isset($content[$region]) && is_array($content[$region])) {
  174. return implode($delimiter, $content[$region]);
  175. }
  176. }
  177. else {
  178. foreach (array_keys($content) as $region) {
  179. if (is_array($content[$region])) {
  180. $content[$region] = implode($delimiter, $content[$region]);
  181. }
  182. }
  183. return $content;
  184. }
  185. }
  186. /**
  187. * Gets the name of the currently active installation profile.
  188. *
  189. * When this function is called during Drupal's initial installation process,
  190. * the name of the profile that's about to be installed is stored in the global
  191. * installation state. At all other times, the standard Drupal systems variable
  192. * table contains the name of the current profile, and we can call
  193. * variable_get() to determine what one is active.
  194. *
  195. * @return $profile
  196. * The name of the installation profile.
  197. */
  198. function drupal_get_profile() {
  199. global $install_state;
  200. if (isset($install_state['parameters']['profile'])) {
  201. $profile = $install_state['parameters']['profile'];
  202. }
  203. else {
  204. $profile = variable_get('install_profile', 'standard');
  205. }
  206. return $profile;
  207. }
  208. /**
  209. * Sets the breadcrumb trail for the current page.
  210. *
  211. * @param $breadcrumb
  212. * Array of links, starting with "home" and proceeding up to but not including
  213. * the current page.
  214. */
  215. function drupal_set_breadcrumb($breadcrumb = NULL) {
  216. $stored_breadcrumb = &drupal_static(__FUNCTION__);
  217. if (isset($breadcrumb)) {
  218. $stored_breadcrumb = $breadcrumb;
  219. }
  220. return $stored_breadcrumb;
  221. }
  222. /**
  223. * Gets the breadcrumb trail for the current page.
  224. */
  225. function drupal_get_breadcrumb() {
  226. $breadcrumb = drupal_set_breadcrumb();
  227. if (!isset($breadcrumb)) {
  228. $breadcrumb = menu_get_active_breadcrumb();
  229. }
  230. return $breadcrumb;
  231. }
  232. /**
  233. * Returns a string containing RDF namespace declarations for use in XML and
  234. * XHTML output.
  235. */
  236. function drupal_get_rdf_namespaces() {
  237. $xml_rdf_namespaces = array();
  238. // Serializes the RDF namespaces in XML namespace syntax.
  239. if (function_exists('rdf_get_namespaces')) {
  240. foreach (rdf_get_namespaces() as $prefix => $uri) {
  241. $xml_rdf_namespaces[] = 'xmlns:' . $prefix . '="' . $uri . '"';
  242. }
  243. }
  244. return count($xml_rdf_namespaces) ? "\n " . implode("\n ", $xml_rdf_namespaces) : '';
  245. }
  246. /**
  247. * Adds output to the HEAD tag of the HTML page.
  248. *
  249. * This function can be called as long as the headers aren't sent. Pass no
  250. * arguments (or NULL for both) to retrieve the currently stored elements.
  251. *
  252. * @param $data
  253. * A renderable array. If the '#type' key is not set then 'html_tag' will be
  254. * added as the default '#type'.
  255. * @param $key
  256. * A unique string key to allow implementations of hook_html_head_alter() to
  257. * identify the element in $data. Required if $data is not NULL.
  258. *
  259. * @return
  260. * An array of all stored HEAD elements.
  261. *
  262. * @see theme_html_tag()
  263. */
  264. function drupal_add_html_head($data = NULL, $key = NULL) {
  265. $stored_head = &drupal_static(__FUNCTION__);
  266. if (!isset($stored_head)) {
  267. // Make sure the defaults, including Content-Type, come first.
  268. $stored_head = _drupal_default_html_head();
  269. }
  270. if (isset($data) && isset($key)) {
  271. if (!isset($data['#type'])) {
  272. $data['#type'] = 'html_tag';
  273. }
  274. $stored_head[$key] = $data;
  275. }
  276. return $stored_head;
  277. }
  278. /**
  279. * Returns elements that are always displayed in the HEAD tag of the HTML page.
  280. */
  281. function _drupal_default_html_head() {
  282. // Add default elements. Make sure the Content-Type comes first because the
  283. // IE browser may be vulnerable to XSS via encoding attacks from any content
  284. // that comes before this META tag, such as a TITLE tag.
  285. $elements['system_meta_content_type'] = array(
  286. '#type' => 'html_tag',
  287. '#tag' => 'meta',
  288. '#attributes' => array(
  289. 'http-equiv' => 'Content-Type',
  290. 'content' => 'text/html; charset=utf-8',
  291. ),
  292. // Security: This always has to be output first.
  293. '#weight' => -1000,
  294. );
  295. // Show Drupal and the major version number in the META GENERATOR tag.
  296. // Get the major version.
  297. list($version, ) = explode('.', VERSION);
  298. $elements['system_meta_generator'] = array(
  299. '#type' => 'html_tag',
  300. '#tag' => 'meta',
  301. '#attributes' => array(
  302. 'name' => 'Generator',
  303. 'content' => 'Drupal ' . $version . ' (http://drupal.org)',
  304. ),
  305. );
  306. // Also send the generator in the HTTP header.
  307. $elements['system_meta_generator']['#attached']['drupal_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
  308. return $elements;
  309. }
  310. /**
  311. * Retrieves output to be displayed in the HEAD tag of the HTML page.
  312. */
  313. function drupal_get_html_head() {
  314. $elements = drupal_add_html_head();
  315. drupal_alter('html_head', $elements);
  316. return drupal_render($elements);
  317. }
  318. /**
  319. * Adds a feed URL for the current page.
  320. *
  321. * This function can be called as long the HTML header hasn't been sent.
  322. *
  323. * @param $url
  324. * An internal system path or a fully qualified external URL of the feed.
  325. * @param $title
  326. * The title of the feed.
  327. */
  328. function drupal_add_feed($url = NULL, $title = '') {
  329. $stored_feed_links = &drupal_static(__FUNCTION__, array());
  330. if (isset($url)) {
  331. $stored_feed_links[$url] = theme('feed_icon', array('url' => $url, 'title' => $title));
  332. drupal_add_html_head_link(array(
  333. 'rel' => 'alternate',
  334. 'type' => 'application/rss+xml',
  335. 'title' => $title,
  336. // Force the URL to be absolute, for consistency with other <link> tags
  337. // output by Drupal.
  338. 'href' => url($url, array('absolute' => TRUE)),
  339. ));
  340. }
  341. return $stored_feed_links;
  342. }
  343. /**
  344. * Gets the feed URLs for the current page.
  345. *
  346. * @param $delimiter
  347. * A delimiter to split feeds by.
  348. */
  349. function drupal_get_feeds($delimiter = "\n") {
  350. $feeds = drupal_add_feed();
  351. return implode($feeds, $delimiter);
  352. }
  353. /**
  354. * @defgroup http_handling HTTP handling
  355. * @{
  356. * Functions to properly handle HTTP responses.
  357. */
  358. /**
  359. * Processes a URL query parameter array to remove unwanted elements.
  360. *
  361. * @param $query
  362. * (optional) An array to be processed. Defaults to $_GET.
  363. * @param $exclude
  364. * (optional) A list of $query array keys to remove. Use "parent[child]" to
  365. * exclude nested items. Defaults to array('q').
  366. * @param $parent
  367. * Internal use only. Used to build the $query array key for nested items.
  368. *
  369. * @return
  370. * An array containing query parameters, which can be used for url().
  371. */
  372. function drupal_get_query_parameters(array $query = NULL, array $exclude = array('q'), $parent = '') {
  373. // Set defaults, if none given.
  374. if (!isset($query)) {
  375. $query = $_GET;
  376. }
  377. // If $exclude is empty, there is nothing to filter.
  378. if (empty($exclude)) {
  379. return $query;
  380. }
  381. elseif (!$parent) {
  382. $exclude = array_flip($exclude);
  383. }
  384. $params = array();
  385. foreach ($query as $key => $value) {
  386. $string_key = ($parent ? $parent . '[' . $key . ']' : $key);
  387. if (isset($exclude[$string_key])) {
  388. continue;
  389. }
  390. if (is_array($value)) {
  391. $params[$key] = drupal_get_query_parameters($value, $exclude, $string_key);
  392. }
  393. else {
  394. $params[$key] = $value;
  395. }
  396. }
  397. return $params;
  398. }
  399. /**
  400. * Splits a URL-encoded query string into an array.
  401. *
  402. * @param $query
  403. * The query string to split.
  404. *
  405. * @return
  406. * An array of URL decoded couples $param_name => $value.
  407. */
  408. function drupal_get_query_array($query) {
  409. $result = array();
  410. if (!empty($query)) {
  411. foreach (explode('&', $query) as $param) {
  412. $param = explode('=', $param, 2);
  413. $result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';
  414. }
  415. }
  416. return $result;
  417. }
  418. /**
  419. * Parses an array into a valid, rawurlencoded query string.
  420. *
  421. * This differs from http_build_query() as we need to rawurlencode() (instead of
  422. * urlencode()) all query parameters.
  423. *
  424. * @param $query
  425. * The query parameter array to be processed, e.g. $_GET.
  426. * @param $parent
  427. * Internal use only. Used to build the $query array key for nested items.
  428. *
  429. * @return
  430. * A rawurlencoded string which can be used as or appended to the URL query
  431. * string.
  432. *
  433. * @see drupal_get_query_parameters()
  434. * @ingroup php_wrappers
  435. */
  436. function drupal_http_build_query(array $query, $parent = '') {
  437. $params = array();
  438. foreach ($query as $key => $value) {
  439. $key = $parent ? $parent . rawurlencode('[' . $key . ']') : rawurlencode($key);
  440. // Recurse into children.
  441. if (is_array($value)) {
  442. $params[] = drupal_http_build_query($value, $key);
  443. }
  444. // If a query parameter value is NULL, only append its key.
  445. elseif (!isset($value)) {
  446. $params[] = $key;
  447. }
  448. else {
  449. // For better readability of paths in query strings, we decode slashes.
  450. $params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
  451. }
  452. }
  453. return implode('&', $params);
  454. }
  455. /**
  456. * Prepares a 'destination' URL query parameter for use with drupal_goto().
  457. *
  458. * Used to direct the user back to the referring page after completing a form.
  459. * By default the current URL is returned. If a destination exists in the
  460. * previous request, that destination is returned. As such, a destination can
  461. * persist across multiple pages.
  462. *
  463. * @return
  464. * An associative array containing the key:
  465. * - destination: The path provided via the destination query string or, if
  466. * not available, the current path.
  467. *
  468. * @see current_path()
  469. * @see drupal_goto()
  470. */
  471. function drupal_get_destination() {
  472. $destination = &drupal_static(__FUNCTION__);
  473. if (isset($destination)) {
  474. return $destination;
  475. }
  476. if (isset($_GET['destination'])) {
  477. $destination = array('destination' => $_GET['destination']);
  478. }
  479. else {
  480. $path = $_GET['q'];
  481. $query = drupal_http_build_query(drupal_get_query_parameters());
  482. if ($query != '') {
  483. $path .= '?' . $query;
  484. }
  485. $destination = array('destination' => $path);
  486. }
  487. return $destination;
  488. }
  489. /**
  490. * Parses a URL string into its path, query, and fragment components.
  491. *
  492. * This function splits both internal paths like @code node?b=c#d @endcode and
  493. * external URLs like @code https://example.com/a?b=c#d @endcode into their
  494. * component parts. See
  495. * @link http://tools.ietf.org/html/rfc3986#section-3 RFC 3986 @endlink for an
  496. * explanation of what the component parts are.
  497. *
  498. * Note that, unlike the RFC, when passed an external URL, this function
  499. * groups the scheme, authority, and path together into the path component.
  500. *
  501. * @param string $url
  502. * The internal path or external URL string to parse.
  503. *
  504. * @return array
  505. * An associative array containing:
  506. * - path: The path component of $url. If $url is an external URL, this
  507. * includes the scheme, authority, and path.
  508. * - query: An array of query parameters from $url, if they exist.
  509. * - fragment: The fragment component from $url, if it exists.
  510. *
  511. * @see drupal_goto()
  512. * @see l()
  513. * @see url()
  514. * @see http://tools.ietf.org/html/rfc3986
  515. *
  516. * @ingroup php_wrappers
  517. */
  518. function drupal_parse_url($url) {
  519. $options = array(
  520. 'path' => NULL,
  521. 'query' => array(),
  522. 'fragment' => '',
  523. );
  524. // External URLs: not using parse_url() here, so we do not have to rebuild
  525. // the scheme, host, and path without having any use for it.
  526. if (strpos($url, '://') !== FALSE) {
  527. // Split off everything before the query string into 'path'.
  528. $parts = explode('?', $url);
  529. $options['path'] = $parts[0];
  530. // If there is a query string, transform it into keyed query parameters.
  531. if (isset($parts[1])) {
  532. $query_parts = explode('#', $parts[1]);
  533. parse_str($query_parts[0], $options['query']);
  534. // Take over the fragment, if there is any.
  535. if (isset($query_parts[1])) {
  536. $options['fragment'] = $query_parts[1];
  537. }
  538. }
  539. }
  540. // Internal URLs.
  541. else {
  542. // parse_url() does not support relative URLs, so make it absolute. E.g. the
  543. // relative URL "foo/bar:1" isn't properly parsed.
  544. $parts = parse_url('http://example.com/' . $url);
  545. // Strip the leading slash that was just added.
  546. $options['path'] = substr($parts['path'], 1);
  547. if (isset($parts['query'])) {
  548. parse_str($parts['query'], $options['query']);
  549. }
  550. if (isset($parts['fragment'])) {
  551. $options['fragment'] = $parts['fragment'];
  552. }
  553. }
  554. // The 'q' parameter contains the path of the current page if clean URLs are
  555. // disabled. It overrides the 'path' of the URL when present, even if clean
  556. // URLs are enabled, due to how Apache rewriting rules work. The path
  557. // parameter must be a string.
  558. if (isset($options['query']['q']) && is_string($options['query']['q'])) {
  559. $options['path'] = $options['query']['q'];
  560. unset($options['query']['q']);
  561. }
  562. return $options;
  563. }
  564. /**
  565. * Encodes a Drupal path for use in a URL.
  566. *
  567. * For aesthetic reasons slashes are not escaped.
  568. *
  569. * Note that url() takes care of calling this function, so a path passed to that
  570. * function should not be encoded in advance.
  571. *
  572. * @param $path
  573. * The Drupal path to encode.
  574. */
  575. function drupal_encode_path($path) {
  576. return str_replace('%2F', '/', rawurlencode($path));
  577. }
  578. /**
  579. * Sends the user to a different page.
  580. *
  581. * This issues an on-site HTTP redirect. The function makes sure the redirected
  582. * URL is formatted correctly.
  583. *
  584. * Usually the redirected URL is constructed from this function's input
  585. * parameters. However you may override that behavior by setting a
  586. * destination in either the $_REQUEST-array (i.e. by using
  587. * the query string of an URI) This is used to direct the user back to
  588. * the proper page after completing a form. For example, after editing
  589. * a post on the 'admin/content'-page or after having logged on using the
  590. * 'user login'-block in a sidebar. The function drupal_get_destination()
  591. * can be used to help set the destination URL.
  592. *
  593. * Drupal will ensure that messages set by drupal_set_message() and other
  594. * session data are written to the database before the user is redirected.
  595. *
  596. * This function ends the request; use it instead of a return in your menu
  597. * callback.
  598. *
  599. * @param $path
  600. * (optional) A Drupal path or a full URL, which will be passed to url() to
  601. * compute the redirect for the URL.
  602. * @param $options
  603. * (optional) An associative array of additional URL options to pass to url().
  604. * @param $http_response_code
  605. * (optional) The HTTP status code to use for the redirection, defaults to
  606. * 302. The valid values for 3xx redirection status codes are defined in
  607. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3 RFC 2616 @endlink
  608. * and the
  609. * @link http://tools.ietf.org/html/draft-reschke-http-status-308-07 draft for the new HTTP status codes: @endlink
  610. * - 301: Moved Permanently (the recommended value for most redirects).
  611. * - 302: Found (default in Drupal and PHP, sometimes used for spamming search
  612. * engines).
  613. * - 303: See Other.
  614. * - 304: Not Modified.
  615. * - 305: Use Proxy.
  616. * - 307: Temporary Redirect.
  617. *
  618. * @see drupal_get_destination()
  619. * @see url()
  620. */
  621. function drupal_goto($path = '', array $options = array(), $http_response_code = 302) {
  622. // A destination in $_GET always overrides the function arguments.
  623. // We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
  624. if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
  625. $destination = drupal_parse_url($_GET['destination']);
  626. $path = $destination['path'];
  627. $options['query'] = $destination['query'];
  628. $options['fragment'] = $destination['fragment'];
  629. }
  630. // In some cases modules call drupal_goto(current_path()). We need to ensure
  631. // that such a redirect is not to an external URL.
  632. if ($path === current_path() && empty($options['external']) && url_is_external($path)) {
  633. // Force url() to generate a non-external URL.
  634. $options['external'] = FALSE;
  635. }
  636. drupal_alter('drupal_goto', $path, $options, $http_response_code);
  637. // The 'Location' HTTP header must be absolute.
  638. $options['absolute'] = TRUE;
  639. $url = url($path, $options);
  640. header('Location: ' . $url, TRUE, $http_response_code);
  641. // The "Location" header sends a redirect status code to the HTTP daemon. In
  642. // some cases this can be wrong, so we make sure none of the code below the
  643. // drupal_goto() call gets executed upon redirection.
  644. drupal_exit($url);
  645. }
  646. /**
  647. * Delivers a "site is under maintenance" message to the browser.
  648. *
  649. * Page callback functions wanting to report a "site offline" message should
  650. * return MENU_SITE_OFFLINE instead of calling drupal_site_offline(). However,
  651. * functions that are invoked in contexts where that return value might not
  652. * bubble up to menu_execute_active_handler() should call drupal_site_offline().
  653. */
  654. function drupal_site_offline() {
  655. drupal_deliver_page(MENU_SITE_OFFLINE);
  656. }
  657. /**
  658. * Delivers a "page not found" error to the browser.
  659. *
  660. * Page callback functions wanting to report a "page not found" message should
  661. * return MENU_NOT_FOUND instead of calling drupal_not_found(). However,
  662. * functions that are invoked in contexts where that return value might not
  663. * bubble up to menu_execute_active_handler() should call drupal_not_found().
  664. */
  665. function drupal_not_found() {
  666. drupal_deliver_page(MENU_NOT_FOUND);
  667. }
  668. /**
  669. * Delivers an "access denied" error to the browser.
  670. *
  671. * Page callback functions wanting to report an "access denied" message should
  672. * return MENU_ACCESS_DENIED instead of calling drupal_access_denied(). However,
  673. * functions that are invoked in contexts where that return value might not
  674. * bubble up to menu_execute_active_handler() should call
  675. * drupal_access_denied().
  676. */
  677. function drupal_access_denied() {
  678. drupal_deliver_page(MENU_ACCESS_DENIED);
  679. }
  680. /**
  681. * Performs an HTTP request.
  682. *
  683. * This is a flexible and powerful HTTP client implementation. Correctly
  684. * handles GET, POST, PUT or any other HTTP requests. Handles redirects.
  685. *
  686. * @param $url
  687. * A string containing a fully qualified URI.
  688. * @param array $options
  689. * (optional) An array that can have one or more of the following elements:
  690. * - headers: An array containing request headers to send as name/value pairs.
  691. * - method: A string containing the request method. Defaults to 'GET'.
  692. * - data: An array containing the values for the request body or a string
  693. * containing the request body, formatted as
  694. * 'param=value&param=value&...'; to generate this, use
  695. * drupal_http_build_query(). Defaults to NULL.
  696. * - max_redirects: An integer representing how many times a redirect
  697. * may be followed. Defaults to 3.
  698. * - timeout: A float representing the maximum number of seconds the function
  699. * call may take. The default is 30 seconds. If a timeout occurs, the error
  700. * code is set to the HTTP_REQUEST_TIMEOUT constant.
  701. * - context: A context resource created with stream_context_create().
  702. *
  703. * @return object
  704. * An object that can have one or more of the following components:
  705. * - request: A string containing the request body that was sent.
  706. * - code: An integer containing the response status code, or the error code
  707. * if an error occurred.
  708. * - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
  709. * - status_message: The status message from the response, if a response was
  710. * received.
  711. * - redirect_code: If redirected, an integer containing the initial response
  712. * status code.
  713. * - redirect_url: If redirected, a string containing the URL of the redirect
  714. * target.
  715. * - error: If an error occurred, the error message. Otherwise not set.
  716. * - headers: An array containing the response headers as name/value pairs.
  717. * HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
  718. * easy access the array keys are returned in lower case.
  719. * - data: A string containing the response body that was received.
  720. *
  721. * @see drupal_http_build_query()
  722. */
  723. function drupal_http_request($url, array $options = array()) {
  724. // Allow an alternate HTTP client library to replace Drupal's default
  725. // implementation.
  726. $override_function = variable_get('drupal_http_request_function', FALSE);
  727. if (!empty($override_function) && function_exists($override_function)) {
  728. return $override_function($url, $options);
  729. }
  730. $result = new stdClass();
  731. // Parse the URL and make sure we can handle the schema.
  732. $uri = @parse_url($url);
  733. if ($uri == FALSE) {
  734. $result->error = 'unable to parse URL';
  735. $result->code = -1001;
  736. return $result;
  737. }
  738. if (!isset($uri['scheme'])) {
  739. $result->error = 'missing schema';
  740. $result->code = -1002;
  741. return $result;
  742. }
  743. timer_start(__FUNCTION__);
  744. // Merge the default options.
  745. $options += array(
  746. 'headers' => array(),
  747. 'method' => 'GET',
  748. 'data' => NULL,
  749. 'max_redirects' => 3,
  750. 'timeout' => 30.0,
  751. 'context' => NULL,
  752. );
  753. // Merge the default headers.
  754. $options['headers'] += array(
  755. 'User-Agent' => 'Drupal (+http://drupal.org/)',
  756. );
  757. // stream_socket_client() requires timeout to be a float.
  758. $options['timeout'] = (float) $options['timeout'];
  759. // Use a proxy if one is defined and the host is not on the excluded list.
  760. $proxy_server = variable_get('proxy_server', '');
  761. if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
  762. // Set the scheme so we open a socket to the proxy server.
  763. $uri['scheme'] = 'proxy';
  764. // Set the path to be the full URL.
  765. $uri['path'] = $url;
  766. // Since the URL is passed as the path, we won't use the parsed query.
  767. unset($uri['query']);
  768. // Add in username and password to Proxy-Authorization header if needed.
  769. if ($proxy_username = variable_get('proxy_username', '')) {
  770. $proxy_password = variable_get('proxy_password', '');
  771. $options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
  772. }
  773. // Some proxies reject requests with any User-Agent headers, while others
  774. // require a specific one.
  775. $proxy_user_agent = variable_get('proxy_user_agent', '');
  776. // The default value matches neither condition.
  777. if ($proxy_user_agent === NULL) {
  778. unset($options['headers']['User-Agent']);
  779. }
  780. elseif ($proxy_user_agent) {
  781. $options['headers']['User-Agent'] = $proxy_user_agent;
  782. }
  783. }
  784. switch ($uri['scheme']) {
  785. case 'proxy':
  786. // Make the socket connection to a proxy server.
  787. $socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
  788. // The Host header still needs to match the real request.
  789. if (!isset($options['headers']['Host'])) {
  790. $options['headers']['Host'] = $uri['host'];
  791. $options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
  792. }
  793. break;
  794. case 'http':
  795. case 'feed':
  796. $port = isset($uri['port']) ? $uri['port'] : 80;
  797. $socket = 'tcp://' . $uri['host'] . ':' . $port;
  798. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  799. // We don't add the standard port to prevent from breaking rewrite rules
  800. // checking the host that do not take into account the port number.
  801. if (!isset($options['headers']['Host'])) {
  802. $options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
  803. }
  804. break;
  805. case 'https':
  806. // Note: Only works when PHP is compiled with OpenSSL support.
  807. $port = isset($uri['port']) ? $uri['port'] : 443;
  808. $socket = 'ssl://' . $uri['host'] . ':' . $port;
  809. if (!isset($options['headers']['Host'])) {
  810. $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
  811. }
  812. break;
  813. default:
  814. $result->error = 'invalid schema ' . $uri['scheme'];
  815. $result->code = -1003;
  816. return $result;
  817. }
  818. if (empty($options['context'])) {
  819. $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
  820. }
  821. else {
  822. // Create a stream with context. Allows verification of a SSL certificate.
  823. $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
  824. }
  825. // Make sure the socket opened properly.
  826. if (!$fp) {
  827. // When a network error occurs, we use a negative number so it does not
  828. // clash with the HTTP status codes.
  829. $result->code = -$errno;
  830. $result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));
  831. // Mark that this request failed. This will trigger a check of the web
  832. // server's ability to make outgoing HTTP requests the next time that
  833. // requirements checking is performed.
  834. // See system_requirements().
  835. variable_set('drupal_http_request_fails', TRUE);
  836. return $result;
  837. }
  838. // Construct the path to act on.
  839. $path = isset($uri['path']) ? $uri['path'] : '/';
  840. if (isset($uri['query'])) {
  841. $path .= '?' . $uri['query'];
  842. }
  843. // Convert array $options['data'] to query string.
  844. if (is_array($options['data'])) {
  845. $options['data'] = drupal_http_build_query($options['data']);
  846. }
  847. // Only add Content-Length if we actually have any content or if it is a POST
  848. // or PUT request. Some non-standard servers get confused by Content-Length in
  849. // at least HEAD/GET requests, and Squid always requires Content-Length in
  850. // POST/PUT requests.
  851. $content_length = strlen($options['data']);
  852. if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
  853. $options['headers']['Content-Length'] = $content_length;
  854. }
  855. // If the server URL has a user then attempt to use basic authentication.
  856. if (isset($uri['user'])) {
  857. $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
  858. }
  859. // If the database prefix is being used by SimpleTest to run the tests in a copied
  860. // database then set the user-agent header to the database prefix so that any
  861. // calls to other Drupal pages will run the SimpleTest prefixed database. The
  862. // user-agent is used to ensure that multiple testing sessions running at the
  863. // same time won't interfere with each other as they would if the database
  864. // prefix were stored statically in a file or database variable.
  865. $test_info = &$GLOBALS['drupal_test_info'];
  866. if (!empty($test_info['test_run_id'])) {
  867. $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
  868. }
  869. $request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
  870. foreach ($options['headers'] as $name => $value) {
  871. $request .= $name . ': ' . trim($value) . "\r\n";
  872. }
  873. $request .= "\r\n" . $options['data'];
  874. $result->request = $request;
  875. // Calculate how much time is left of the original timeout value.
  876. $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
  877. if ($timeout > 0) {
  878. stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
  879. fwrite($fp, $request);
  880. }
  881. // Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
  882. // and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
  883. // instead must invoke stream_get_meta_data() each iteration.
  884. $info = stream_get_meta_data($fp);
  885. $alive = !$info['eof'] && !$info['timed_out'];
  886. $response = '';
  887. while ($alive) {
  888. // Calculate how much time is left of the original timeout value.
  889. $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
  890. if ($timeout <= 0) {
  891. $info['timed_out'] = TRUE;
  892. break;
  893. }
  894. stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
  895. $chunk = fread($fp, 1024);
  896. $response .= $chunk;
  897. $info = stream_get_meta_data($fp);
  898. $alive = !$info['eof'] && !$info['timed_out'] && $chunk;
  899. }
  900. fclose($fp);
  901. if ($info['timed_out']) {
  902. $result->code = HTTP_REQUEST_TIMEOUT;
  903. $result->error = 'request timed out';
  904. return $result;
  905. }
  906. // Parse response headers from the response body.
  907. // Be tolerant of malformed HTTP responses that separate header and body with
  908. // \n\n or \r\r instead of \r\n\r\n.
  909. list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
  910. $response = preg_split("/\r\n|\n|\r/", $response);
  911. // Parse the response status line.
  912. $response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
  913. $result->protocol = $response_status_array['http_version'];
  914. $result->status_message = $response_status_array['reason_phrase'];
  915. $code = $response_status_array['response_code'];
  916. $result->headers = array();
  917. // Parse the response headers.
  918. while ($line = trim(array_shift($response))) {
  919. list($name, $value) = explode(':', $line, 2);
  920. $name = strtolower($name);
  921. if (isset($result->headers[$name]) && $name == 'set-cookie') {
  922. // RFC 2109: the Set-Cookie response header comprises the token Set-
  923. // Cookie:, followed by a comma-separated list of one or more cookies.
  924. $result->headers[$name] .= ',' . trim($value);
  925. }
  926. else {
  927. $result->headers[$name] = trim($value);
  928. }
  929. }
  930. $responses = array(
  931. 100 => 'Continue',
  932. 101 => 'Switching Protocols',
  933. 200 => 'OK',
  934. 201 => 'Created',
  935. 202 => 'Accepted',
  936. 203 => 'Non-Authoritative Information',
  937. 204 => 'No Content',
  938. 205 => 'Reset Content',
  939. 206 => 'Partial Content',
  940. 300 => 'Multiple Choices',
  941. 301 => 'Moved Permanently',
  942. 302 => 'Found',
  943. 303 => 'See Other',
  944. 304 => 'Not Modified',
  945. 305 => 'Use Proxy',
  946. 307 => 'Temporary Redirect',
  947. 400 => 'Bad Request',
  948. 401 => 'Unauthorized',
  949. 402 => 'Payment Required',
  950. 403 => 'Forbidden',
  951. 404 => 'Not Found',
  952. 405 => 'Method Not Allowed',
  953. 406 => 'Not Acceptable',
  954. 407 => 'Proxy Authentication Required',
  955. 408 => 'Request Time-out',
  956. 409 => 'Conflict',
  957. 410 => 'Gone',
  958. 411 => 'Length Required',
  959. 412 => 'Precondition Failed',
  960. 413 => 'Request Entity Too Large',
  961. 414 => 'Request-URI Too Large',
  962. 415 => 'Unsupported Media Type',
  963. 416 => 'Requested range not satisfiable',
  964. 417 => 'Expectation Failed',
  965. 500 => 'Internal Server Error',
  966. 501 => 'Not Implemented',
  967. 502 => 'Bad Gateway',
  968. 503 => 'Service Unavailable',
  969. 504 => 'Gateway Time-out',
  970. 505 => 'HTTP Version not supported',
  971. );
  972. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  973. // base code in their class.
  974. if (!isset($responses[$code])) {
  975. $code = floor($code / 100) * 100;
  976. }
  977. $result->code = $code;
  978. switch ($code) {
  979. case 200: // OK
  980. case 201: // Created
  981. case 202: // Accepted
  982. case 203: // Non-Authoritative Information
  983. case 204: // No Content
  984. case 205: // Reset Content
  985. case 206: // Partial Content
  986. case 304: // Not modified
  987. break;
  988. case 301: // Moved permanently
  989. case 302: // Moved temporarily
  990. case 307: // Moved temporarily
  991. $location = $result->headers['location'];
  992. $options['timeout'] -= timer_read(__FUNCTION__) / 1000;
  993. if ($options['timeout'] <= 0) {
  994. $result->code = HTTP_REQUEST_TIMEOUT;
  995. $result->error = 'request timed out';
  996. }
  997. elseif ($options['max_redirects']) {
  998. // Redirect to the new location.
  999. $options['max_redirects']--;
  1000. // We need to unset the 'Host' header
  1001. // as we are redirecting to a new location.
  1002. unset($options['headers']['Host']);
  1003. $result = drupal_http_request($location, $options);
  1004. $result->redirect_code = $code;
  1005. }
  1006. if (!isset($result->redirect_url)) {
  1007. $result->redirect_url = $location;
  1008. }
  1009. break;
  1010. default:
  1011. $result->error = $result->status_message;
  1012. }
  1013. return $result;
  1014. }
  1015. /**
  1016. * Splits an HTTP response status line into components.
  1017. *
  1018. * See the @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html status line definition @endlink
  1019. * in RFC 2616.
  1020. *
  1021. * @param string $respone
  1022. * The response status line, for example 'HTTP/1.1 500 Internal Server Error'.
  1023. *
  1024. * @return array
  1025. * Keyed array containing the component parts. If the response is malformed,
  1026. * all possible parts will be extracted. 'reason_phrase' could be empty.
  1027. * Possible keys:
  1028. * - 'http_version'
  1029. * - 'response_code'
  1030. * - 'reason_phrase'
  1031. */
  1032. function _drupal_parse_response_status($response) {
  1033. $response_array = explode(' ', trim($response), 3);
  1034. // Set up empty values.
  1035. $result = array(
  1036. 'reason_phrase' => '',
  1037. );
  1038. $result['http_version'] = $response_array[0];
  1039. $result['response_code'] = $response_array[1];
  1040. if (isset($response_array[2])) {
  1041. $result['reason_phrase'] = $response_array[2];
  1042. }
  1043. return $result;
  1044. }
  1045. /**
  1046. * Helper function for determining hosts excluded from needing a proxy.
  1047. *
  1048. * @return
  1049. * TRUE if a proxy should be used for this host.
  1050. */
  1051. function _drupal_http_use_proxy($host) {
  1052. $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
  1053. return !in_array(strtolower($host), $proxy_exceptions, TRUE);
  1054. }
  1055. /**
  1056. * @} End of "HTTP handling".
  1057. */
  1058. /**
  1059. * Strips slashes from a string or array of strings.
  1060. *
  1061. * Callback for array_walk() within fix_gpx_magic().
  1062. *
  1063. * @param $item
  1064. * An individual string or array of strings from superglobals.
  1065. */
  1066. function _fix_gpc_magic(&$item) {
  1067. if (is_array($item)) {
  1068. array_walk($item, '_fix_gpc_magic');
  1069. }
  1070. else {
  1071. $item = stripslashes($item);
  1072. }
  1073. }
  1074. /**
  1075. * Strips slashes from $_FILES items.
  1076. *
  1077. * Callback for array_walk() within fix_gpc_magic().
  1078. *
  1079. * The tmp_name key is skipped keys since PHP generates single backslashes for
  1080. * file paths on Windows systems.
  1081. *
  1082. * @param $item
  1083. * An item from $_FILES.
  1084. * @param $key
  1085. * The key for the item within $_FILES.
  1086. *
  1087. * @see http://php.net/manual/features.file-upload.php#42280
  1088. */
  1089. function _fix_gpc_magic_files(&$item, $key) {
  1090. if ($key != 'tmp_name') {
  1091. if (is_array($item)) {
  1092. array_walk($item, '_fix_gpc_magic_files');
  1093. }
  1094. else {
  1095. $item = stripslashes($item);
  1096. }
  1097. }
  1098. }
  1099. /**
  1100. * Fixes double-escaping caused by "magic quotes" in some PHP installations.
  1101. *
  1102. * @see _fix_gpc_magic()
  1103. * @see _fix_gpc_magic_files()
  1104. */
  1105. function fix_gpc_magic() {
  1106. static $fixed = FALSE;
  1107. if (!$fixed && ini_get('magic_quotes_gpc')) {
  1108. array_walk($_GET, '_fix_gpc_magic');
  1109. array_walk($_POST, '_fix_gpc_magic');
  1110. array_walk($_COOKIE, '_fix_gpc_magic');
  1111. array_walk($_REQUEST, '_fix_gpc_magic');
  1112. array_walk($_FILES, '_fix_gpc_magic_files');
  1113. }
  1114. $fixed = TRUE;
  1115. }
  1116. /**
  1117. * @defgroup validation Input validation
  1118. * @{
  1119. * Functions to validate user input.
  1120. */
  1121. /**
  1122. * Verifies the syntax of the given e-mail address.
  1123. *
  1124. * This uses the
  1125. * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
  1126. *
  1127. * @param $mail
  1128. * A string containing an e-mail address.
  1129. *
  1130. * @return
  1131. * TRUE if the address is in a valid format.
  1132. */
  1133. function valid_email_address($mail) {
  1134. return (bool)filter_var($mail, FILTER_VALIDATE_EMAIL);
  1135. }
  1136. /**
  1137. * Verifies the syntax of the given URL.
  1138. *
  1139. * This function should only be used on actual URLs. It should not be used for
  1140. * Drupal menu paths, which can contain arbitrary characters.
  1141. * Valid values per RFC 3986.
  1142. * @param $url
  1143. * The URL to verify.
  1144. * @param $absolute
  1145. * Whether the URL is absolute (beginning with a scheme such as "http:").
  1146. *
  1147. * @return
  1148. * TRUE if the URL is in a valid format.
  1149. */
  1150. function valid_url($url, $absolute = FALSE) {
  1151. if ($absolute) {
  1152. return (bool)preg_match("
  1153. /^ # Start at the beginning of the text
  1154. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  1155. (?: # Userinfo (optional) which is typically
  1156. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  1157. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  1158. )?
  1159. (?:
  1160. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  1161. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  1162. )
  1163. (?::[0-9]+)? # Server port number (optional)
  1164. (?:[\/|\?]
  1165. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  1166. *)?
  1167. $/xi", $url);
  1168. }
  1169. else {
  1170. return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
  1171. }
  1172. }
  1173. /**
  1174. * @} End of "defgroup validation".
  1175. */
  1176. /**
  1177. * Registers an event for the current visitor to the flood control mechanism.
  1178. *
  1179. * @param $name
  1180. * The name of an event.
  1181. * @param $window
  1182. * Optional number of seconds before this event expires. Defaults to 3600 (1
  1183. * hour). Typically uses the same value as the flood_is_allowed() $window
  1184. * parameter. Expired events are purged on cron run to prevent the flood table
  1185. * from growing indefinitely.
  1186. * @param $identifier
  1187. * Optional identifier (defaults to the current user's IP address).
  1188. */
  1189. function flood_register_event($name, $window = 3600, $identifier = NULL) {
  1190. if (!isset($identifier)) {
  1191. $identifier = ip_address();
  1192. }
  1193. db_insert('flood')
  1194. ->fields(array(
  1195. 'event' => $name,
  1196. 'identifier' => $identifier,
  1197. 'timestamp' => REQUEST_TIME,
  1198. 'expiration' => REQUEST_TIME + $window,
  1199. ))
  1200. ->execute();
  1201. }
  1202. /**
  1203. * Makes the flood control mechanism forget an event for the current visitor.
  1204. *
  1205. * @param $name
  1206. * The name of an event.
  1207. * @param $identifier
  1208. * Optional identifier (defaults to the current user's IP address).
  1209. */
  1210. function flood_clear_event($name, $identifier = NULL) {
  1211. if (!isset($identifier)) {
  1212. $identifier = ip_address();
  1213. }
  1214. db_delete('flood')
  1215. ->condition('event', $name)
  1216. ->condition('identifier', $identifier)
  1217. ->execute();
  1218. }
  1219. /**
  1220. * Checks whether a user is allowed to proceed with the specified event.
  1221. *
  1222. * Events can have thresholds saying that each user can only do that event
  1223. * a certain number of times in a time window. This function verifies that the
  1224. * current user has not exceeded this threshold.
  1225. *
  1226. * @param $name
  1227. * The unique name of the event.
  1228. * @param $threshold
  1229. * The maximum number of times each user can do this event per time window.
  1230. * @param $window
  1231. * Number of seconds in the time window for this event (default is 3600
  1232. * seconds, or 1 hour).
  1233. * @param $identifier
  1234. * Unique identifier of the current user. Defaults to their IP address.
  1235. *
  1236. * @return
  1237. * TRUE if the user is allowed to proceed. FALSE if they have exceeded the
  1238. * threshold and should not be allowed to proceed.
  1239. */
  1240. function flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) {
  1241. if (!isset($identifier)) {
  1242. $identifier = ip_address();
  1243. }
  1244. $number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", array(
  1245. ':event' => $name,
  1246. ':identifier' => $identifier,
  1247. ':timestamp' => REQUEST_TIME - $window))
  1248. ->fetchField();
  1249. return ($number < $threshold);
  1250. }
  1251. /**
  1252. * @defgroup sanitization Sanitization functions
  1253. * @{
  1254. * Functions to sanitize values.
  1255. *
  1256. * See http://drupal.org/writing-secure-code for information
  1257. * on writing secure code.
  1258. */
  1259. /**
  1260. * Strips dangerous protocols (e.g. 'javascript:') from a URI.
  1261. *
  1262. * This function must be called for all URIs within user-entered input prior
  1263. * to being output to an HTML attribute value. It is often called as part of
  1264. * check_url() or filter_xss(), but those functions return an HTML-encoded
  1265. * string, so this function can be called independently when the output needs to
  1266. * be a plain-text string for passing to t(), l(), drupal_attributes(), or
  1267. * another function that will call check_plain() separately.
  1268. *
  1269. * @param $uri
  1270. * A plain-text URI that might contain dangerous protocols.
  1271. *
  1272. * @return
  1273. * A plain-text URI stripped of dangerous protocols. As with all plain-text
  1274. * strings, this return value must not be output to an HTML page without
  1275. * check_plain() being called on it. However, it can be passed to functions
  1276. * expecting plain-text strings.
  1277. *
  1278. * @see check_url()
  1279. */
  1280. function drupal_strip_dangerous_protocols($uri) {
  1281. static $allowed_protocols;
  1282. if (!isset($allowed_protocols)) {
  1283. $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
  1284. }
  1285. // Iteratively remove any invalid protocol found.
  1286. do {
  1287. $before = $uri;
  1288. $colonpos = strpos($uri, ':');
  1289. if ($colonpos > 0) {
  1290. // We found a colon, possibly a protocol. Verify.
  1291. $protocol = substr($uri, 0, $colonpos);
  1292. // If a colon is preceded by a slash, question mark or hash, it cannot
  1293. // possibly be part of the URL scheme. This must be a relative URL, which
  1294. // inherits the (safe) protocol of the base document.
  1295. if (preg_match('![/?#]!', $protocol)) {
  1296. break;
  1297. }
  1298. // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
  1299. // (URI Comparison) scheme comparison must be case-insensitive.
  1300. if (!isset($allowed_protocols[strtolower($protocol)])) {
  1301. $uri = substr($uri, $colonpos + 1);
  1302. }
  1303. }
  1304. } while ($before != $uri);
  1305. return $uri;
  1306. }
  1307. /**
  1308. * Strips dangerous protocols from a URI and encodes it for output to HTML.
  1309. *
  1310. * @param $uri
  1311. * A plain-text URI that might contain dangerous protocols.
  1312. *
  1313. * @return
  1314. * A URI stripped of dangerous protocols and encoded for output to an HTML
  1315. * attribute value. Because it is already encoded, it should not be set as a
  1316. * value within a $attributes array passed to drupal_attributes(), because
  1317. * drupal_attributes() expects those values to be plain-text strings. To pass
  1318. * a filtered URI to drupal_attributes(), call
  1319. * drupal_strip_dangerous_protocols() instead.
  1320. *
  1321. * @see drupal_strip_dangerous_protocols()
  1322. */
  1323. function check_url($uri) {
  1324. return check_plain(drupal_strip_dangerous_protocols($uri));
  1325. }
  1326. /**
  1327. * Applies a very permissive XSS/HTML filter for admin-only use.
  1328. *
  1329. * Use only for fields where it is impractical to use the
  1330. * whole filter system, but where some (mainly inline) mark-up
  1331. * is desired (so check_plain() is not acceptable).
  1332. *
  1333. * Allows all tags that can be used inside an HTML body, save
  1334. * for scripts and styles.
  1335. */
  1336. function filter_xss_admin($string) {
  1337. return filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'menu', 'meter', 'nav', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr'));
  1338. }
  1339. /**
  1340. * Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
  1341. *
  1342. * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
  1343. * For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
  1344. *
  1345. * This code does four things:
  1346. * - Removes characters and constructs that can trick browsers.
  1347. * - Makes sure all HTML entities are well-formed.
  1348. * - Makes sure all HTML tags and attributes are well-formed.
  1349. * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
  1350. * javascript:).
  1351. *
  1352. * @param $string
  1353. * The string with raw HTML in it. It will be stripped of everything that can
  1354. * cause an XSS attack.
  1355. * @param $allowed_tags
  1356. * An array of allowed tags.
  1357. *
  1358. * @return
  1359. * An XSS safe version of $string, or an empty string if $string is not
  1360. * valid UTF-8.
  1361. *
  1362. * @see drupal_validate_utf8()
  1363. */
  1364. function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
  1365. // Only operate on valid UTF-8 strings. This is necessary to prevent cross
  1366. // site scripting issues on Internet Explorer 6.
  1367. if (!drupal_validate_utf8($string)) {
  1368. return '';
  1369. }
  1370. // Store the text format.
  1371. _filter_xss_split($allowed_tags, TRUE);
  1372. // Remove NULL characters (ignored by some browsers).
  1373. $string = str_replace(chr(0), '', $string);
  1374. // Remove Netscape 4 JS entities.
  1375. $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
  1376. // Defuse all HTML entities.
  1377. $string = str_replace('&', '&amp;', $string);
  1378. // Change back only well-formed entities in our whitelist:
  1379. // Decimal numeric entities.
  1380. $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
  1381. // Hexadecimal numeric entities.
  1382. $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
  1383. // Named entities.
  1384. $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
  1385. return preg_replace_callback('%
  1386. (
  1387. <(?=[^a-zA-Z!/]) # a lone <
  1388. | # or
  1389. <!--.*?--> # a comment
  1390. | # or
  1391. <[^>]*(>|$) # a string that starts with a <, up until the > or the end of the string
  1392. | # or
  1393. > # just a >
  1394. )%x', '_filter_xss_split', $string);
  1395. }
  1396. /**
  1397. * Processes an HTML tag.
  1398. *
  1399. * @param $m
  1400. * An array with various meaning depending on the value of $store.
  1401. * If $store is TRUE then the array contains the allowed tags.
  1402. * If $store is FALSE then the array has one element, the HTML tag to process.
  1403. * @param $store
  1404. * Whether to store $m.
  1405. *
  1406. * @return
  1407. * If the element isn't allowed, an empty string. Otherwise, the cleaned up
  1408. * version of the HTML element.
  1409. */
  1410. function _filter_xss_split($m, $store = FALSE) {
  1411. static $allowed_html;
  1412. if ($store) {
  1413. $allowed_html = array_flip($m);
  1414. return;
  1415. }
  1416. $string = $m[1];
  1417. if (substr($string, 0, 1) != '<') {
  1418. // We matched a lone ">" character.
  1419. return '&gt;';
  1420. }
  1421. elseif (strlen($string) == 1) {
  1422. // We matched a lone "<" character.
  1423. return '&lt;';
  1424. }
  1425. if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
  1426. // Seriously malformed.
  1427. return '';
  1428. }
  1429. $slash = trim($matches[1]);
  1430. $elem = &$matches[2];
  1431. $attrlist = &$matches[3];
  1432. $comment = &$matches[4];
  1433. if ($comment) {
  1434. $elem = '!--';
  1435. }
  1436. if (!isset($allowed_html[strtolower($elem)])) {
  1437. // Disallowed HTML element.
  1438. return '';
  1439. }
  1440. if ($comment) {
  1441. return $comment;
  1442. }
  1443. if ($slash != '') {
  1444. return "</$elem>";
  1445. }
  1446. // Is there a closing XHTML slash at the end of the attributes?
  1447. $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
  1448. $xhtml_slash = $count ? ' /' : '';
  1449. // Clean up attributes.
  1450. $attr2 = implode(' ', _filter_xss_attributes($attrlist));
  1451. $attr2 = preg_replace('/[<>]/', '', $attr2);
  1452. $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
  1453. return "<$elem$attr2$xhtml_slash>";
  1454. }
  1455. /**
  1456. * Processes a string of HTML attributes.
  1457. *
  1458. * @return
  1459. * Cleaned up version of the HTML attributes.
  1460. */
  1461. function _filter_xss_attributes($attr) {
  1462. $attrarr = array();
  1463. $mode = 0;
  1464. $attrname = '';
  1465. while (strlen($attr) != 0) {
  1466. // Was the last operation successful?
  1467. $working = 0;
  1468. switch ($mode) {
  1469. case 0:
  1470. // Attribute name, href for instance.
  1471. if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
  1472. $attrname = strtolower($match[1]);
  1473. $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
  1474. $working = $mode = 1;
  1475. $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
  1476. }
  1477. break;
  1478. case 1:
  1479. // Equals sign or valueless ("selected").
  1480. if (preg_match('/^\s*=\s*/', $attr)) {
  1481. $working = 1; $mode = 2;
  1482. $attr = preg_replace('/^\s*=\s*/', '', $attr);
  1483. break;
  1484. }
  1485. if (preg_match('/^\s+/', $attr)) {
  1486. $working = 1; $mode = 0;
  1487. if (!$skip) {
  1488. $attrarr[] = $attrname;
  1489. }
  1490. $attr = preg_replace('/^\s+/', '', $attr);
  1491. }
  1492. break;
  1493. case 2:
  1494. // Attribute value, a URL after href= for instance.
  1495. if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
  1496. $thisval = filter_xss_bad_protocol($match[1]);
  1497. if (!$skip) {
  1498. $attrarr[] = "$attrname=\"$thisval\"";
  1499. }
  1500. $working = 1;
  1501. $mode = 0;
  1502. $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
  1503. break;
  1504. }
  1505. if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
  1506. $thisval = filter_xss_bad_protocol($match[1]);
  1507. if (!$skip) {
  1508. $attrarr[] = "$attrname='$thisval'";
  1509. }
  1510. $working = 1; $mode = 0;
  1511. $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
  1512. break;
  1513. }
  1514. if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
  1515. $thisval = filter_xss_bad_protocol($match[1]);
  1516. if (!$skip) {
  1517. $attrarr[] = "$attrname=\"$thisval\"";
  1518. }
  1519. $working = 1; $mode = 0;
  1520. $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
  1521. }
  1522. break;
  1523. }
  1524. if ($working == 0) {
  1525. // Not well formed; remove and try again.
  1526. $attr = preg_replace('/
  1527. ^
  1528. (
  1529. "[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
  1530. | # or
  1531. \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
  1532. | # or
  1533. \S # - a non-whitespace character
  1534. )* # any number of the above three
  1535. \s* # any number of whitespaces
  1536. /x', '', $attr);
  1537. $mode = 0;
  1538. }
  1539. }
  1540. // The attribute list ends with a valueless attribute like "selected".
  1541. if ($mode == 1 && !$skip) {
  1542. $attrarr[] = $attrname;
  1543. }
  1544. return $attrarr;
  1545. }
  1546. /**
  1547. * Processes an HTML attribute value and strips dangerous protocols from URLs.
  1548. *
  1549. * @param $string
  1550. * The string with the attribute value.
  1551. * @param $decode
  1552. * (deprecated) Whether to decode entities in the $string. Set to FALSE if the
  1553. * $string is in plain text, TRUE otherwise. Defaults to TRUE. This parameter
  1554. * is deprecated and will be removed in Drupal 8. To process a plain-text URI,
  1555. * call drupal_strip_dangerous_protocols() or check_url() instead.
  1556. *
  1557. * @return
  1558. * Cleaned up and HTML-escaped version of $string.
  1559. */
  1560. function filter_xss_bad_protocol($string, $decode = TRUE) {
  1561. // Get the plain text representation of the attribute value (i.e. its meaning).
  1562. // @todo Remove the $decode parameter in Drupal 8, and always assume an HTML
  1563. // string that needs decoding.
  1564. if ($decode) {
  1565. if (!function_exists('decode_entities')) {
  1566. require_once DRUPAL_ROOT . '/includes/unicode.inc';
  1567. }
  1568. $string = decode_entities($string);
  1569. }
  1570. return check_plain(drupal_strip_dangerous_protocols($string));
  1571. }
  1572. /**
  1573. * @} End of "defgroup sanitization".
  1574. */
  1575. /**
  1576. * @defgroup format Formatting
  1577. * @{
  1578. * Functions to format numbers, strings, dates, etc.
  1579. */
  1580. /**
  1581. * Formats an RSS channel.
  1582. *
  1583. * Arbitrary elements may be added using the $args associative array.
  1584. */
  1585. function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
  1586. global $language_content;
  1587. $langcode = $langcode ? $langcode : $language_content->language;
  1588. $output = "<channel>\n";
  1589. $output .= ' <title>' . check_plain($title) . "</title>\n";
  1590. $output .= ' <link>' . check_url($link) . "</link>\n";
  1591. // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
  1592. // We strip all HTML tags, but need to prevent double encoding from properly
  1593. // escaped source data (such as &amp becoming &amp;amp;).
  1594. $output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
  1595. $output .= ' <language>' . check_plain($langcode) . "</language>\n";
  1596. $output .= format_xml_elements($args);
  1597. $output .= $items;
  1598. $output .= "</channel>\n";
  1599. return $output;
  1600. }
  1601. /**
  1602. * Formats a single RSS item.
  1603. *
  1604. * Arbitrary elements may be added using the $args associative array.
  1605. */
  1606. function format_rss_item($title, $link, $description, $args = array()) {
  1607. $output = "<item>\n";
  1608. $output .= ' <title>' . check_plain($title) . "</title>\n";
  1609. $output .= ' <link>' . check_url($link) . "</link>\n";
  1610. $output .= ' <description>' . check_plain($description) . "</description>\n";
  1611. $output .= format_xml_elements($args);
  1612. $output .= "</item>\n";
  1613. return $output;
  1614. }
  1615. /**
  1616. * Formats XML elements.
  1617. *
  1618. * @param $array
  1619. * An array where each item represents an element and is either a:
  1620. * - (key => value) pair (<key>value</key>)
  1621. * - Associative array with fields:
  1622. * - 'key': element name
  1623. * - 'value': element contents
  1624. * - 'attributes': associative array of element attributes
  1625. * - 'encoded': TRUE if 'value' is already encoded
  1626. *
  1627. * In both cases, 'value' can be a simple string, or it can be another array
  1628. * with the same format as $array itself for nesting.
  1629. *
  1630. * If 'encoded' is TRUE it is up to the caller to ensure that 'value' is either
  1631. * entity-encoded or CDATA-escaped. Using this option is not recommended when
  1632. * working with untrusted user input, since failing to escape the data
  1633. * correctly has security implications.
  1634. */
  1635. function format_xml_elements($array) {
  1636. $output = '';
  1637. foreach ($array as $key => $value) {
  1638. if (is_numeric($key)) {
  1639. if ($value['key']) {
  1640. $output .= ' <' . $value['key'];
  1641. if (isset($value['attributes']) && is_array($value['attributes'])) {
  1642. $output .= drupal_attributes($value['attributes']);
  1643. }
  1644. if (isset($value['value']) && $value['value'] != '') {
  1645. $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : (!empty($value['encoded']) ? $value['value'] : check_plain($value['value']))) . '</' . $value['key'] . ">\n";
  1646. }
  1647. else {
  1648. $output .= " />\n";
  1649. }
  1650. }
  1651. }
  1652. else {
  1653. $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
  1654. }
  1655. }
  1656. return $output;
  1657. }
  1658. /**
  1659. * Formats a string containing a count of items.
  1660. *
  1661. * This function ensures that the string is pluralized correctly. Since t() is
  1662. * called by this function, make sure not to pass already-localized strings to
  1663. * it.
  1664. *
  1665. * For example:
  1666. * @code
  1667. * $output = format_plural($node->comment_count, '1 comment', '@count comments');
  1668. * @endcode
  1669. *
  1670. * Example with additional replacements:
  1671. * @code
  1672. * $output = format_plural($update_count,
  1673. * 'Changed the content type of 1 post from %old-type to %new-type.',
  1674. * 'Changed the content type of @count posts from %old-type to %new-type.',
  1675. * array('%old-type' => $info->old_type, '%new-type' => $info->new_type));
  1676. * @endcode
  1677. *
  1678. * @param $count
  1679. * The item count to display.
  1680. * @param $singular
  1681. * The string for the singular case. Make sure it is clear this is singular,
  1682. * to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not
  1683. * use @count in the singular string.
  1684. * @param $plural
  1685. * The string for the plural case. Make sure it is clear this is plural, to
  1686. * ease translation. Use @count in place of the item count, as in
  1687. * "@count new comments".
  1688. * @param $args
  1689. * An associative array of replacements to make after translation. Instances
  1690. * of any key in this array are replaced with the corresponding value.
  1691. * Based on the first character of the key, the value is escaped and/or
  1692. * themed. See format_string(). Note that you do not need to include @count
  1693. * in this array; this replacement is done automatically for the plural case.
  1694. * @param $options
  1695. * An associative array of additional options. See t() for allowed keys.
  1696. *
  1697. * @return
  1698. * A translated string.
  1699. *
  1700. * @see t()
  1701. * @see format_string()
  1702. */
  1703. function format_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
  1704. $args['@count'] = $count;
  1705. if ($count == 1) {
  1706. return t($singular, $args, $options);
  1707. }
  1708. // Get the plural index through the gettext formula.
  1709. $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
  1710. // If the index cannot be computed, use the plural as a fallback (which
  1711. // allows for most flexiblity with the replaceable @count value).
  1712. if ($index < 0) {
  1713. return t($plural, $args, $options);
  1714. }
  1715. else {
  1716. switch ($index) {
  1717. case "0":
  1718. return t($singular, $args, $options);
  1719. case "1":
  1720. return t($plural, $args, $options);
  1721. default:
  1722. unset($args['@count']);
  1723. $args['@count[' . $index . ']'] = $count;
  1724. return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
  1725. }
  1726. }
  1727. }
  1728. /**
  1729. * Parses a given byte count.
  1730. *
  1731. * @param $size
  1732. * A size expressed as a number of bytes with optional SI or IEC binary unit
  1733. * prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
  1734. *
  1735. * @return
  1736. * An integer representation of the size in bytes.
  1737. */
  1738. function parse_size($size) {
  1739. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
  1740. $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
  1741. if ($unit) {
  1742. // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
  1743. return round($size * pow(DRUPAL_KILOBYTE, stripos('bkmgtpezy', $unit[0])));
  1744. }
  1745. else {
  1746. return round($size);
  1747. }
  1748. }
  1749. /**
  1750. * Generates a string representation for the given byte count.
  1751. *
  1752. * @param $size
  1753. * A size in bytes.
  1754. * @param $langcode
  1755. * Optional language code to translate to a language other than what is used
  1756. * to display the page.
  1757. *
  1758. * @return
  1759. * A translated string representation of the size.
  1760. */
  1761. function format_size($size, $langcode = NULL) {
  1762. if ($size < DRUPAL_KILOBYTE) {
  1763. return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
  1764. }
  1765. else {
  1766. $size = $size / DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
  1767. $units = array(
  1768. t('@size KB', array(), array('langcode' => $langcode)),
  1769. t('@size MB', array(), array('langcode' => $langcode)),
  1770. t('@size GB', array(), array('langcode' => $langcode)),
  1771. t('@size TB', array(), array('langcode' => $langcode)),
  1772. t('@size PB', array(), array('langcode' => $langcode)),
  1773. t('@size EB', array(), array('langcode' => $langcode)),
  1774. t('@size ZB', array(), array('langcode' => $langcode)),
  1775. t('@size YB', array(), array('langcode' => $langcode)),
  1776. );
  1777. foreach ($units as $unit) {
  1778. if (round($size, 2) >= DRUPAL_KILOBYTE) {
  1779. $size = $size / DRUPAL_KILOBYTE;
  1780. }
  1781. else {
  1782. break;
  1783. }
  1784. }
  1785. return str_replace('@size', round($size, 2), $unit);
  1786. }
  1787. }
  1788. /**
  1789. * Formats a time interval with the requested granularity.
  1790. *
  1791. * @param $interval
  1792. * The length of the interval in seconds.
  1793. * @param $granularity
  1794. * How many different units to display in the string.
  1795. * @param $langcode
  1796. * Optional language code to translate to a language other than
  1797. * what is used to display the page.
  1798. *
  1799. * @return
  1800. * A translated string representation of the interval.
  1801. */
  1802. function format_interval($interval, $granularity = 2, $langcode = NULL) {
  1803. $units = array(
  1804. '1 year|@count years' => 31536000,
  1805. '1 month|@count months' => 2592000,
  1806. '1 week|@count weeks' => 604800,
  1807. '1 day|@count days' => 86400,
  1808. '1 hour|@count hours' => 3600,
  1809. '1 min|@count min' => 60,
  1810. '1 sec|@count sec' => 1
  1811. );
  1812. $output = '';
  1813. foreach ($units as $key => $value) {
  1814. $key = explode('|', $key);
  1815. if ($interval >= $value) {
  1816. $output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
  1817. $interval %= $value;
  1818. $granularity--;
  1819. }
  1820. if ($granularity == 0) {
  1821. break;
  1822. }
  1823. }
  1824. return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
  1825. }
  1826. /**
  1827. * Formats a date, using a date type or a custom date format string.
  1828. *
  1829. * @param $timestamp
  1830. * A UNIX timestamp to format.
  1831. * @param $type
  1832. * (optional) The format to use, one of:
  1833. * - 'short', 'medium', or 'long' (the corresponding built-in date formats).
  1834. * - The name of a date type defined by a module in hook_date_format_types(),
  1835. * if it's been assigned a format.
  1836. * - The machine name of an administrator-defined date format.
  1837. * - 'custom', to use $format.
  1838. * Defaults to 'medium'.
  1839. * @param $format
  1840. * (optional) If $type is 'custom', a PHP date format string suitable for
  1841. * input to date(). Use a backslash to escape ordinary text, so it does not
  1842. * get interpreted as date format characters.
  1843. * @param $timezone
  1844. * (optional) Time zone identifier, as described at
  1845. * http://php.net/manual/timezones.php Defaults to the time zone used to
  1846. * display the page.
  1847. * @param $langcode
  1848. * (optional) Language code to translate to. Defaults to the language used to
  1849. * display the page.
  1850. *
  1851. * @return
  1852. * A translated date string in the requested format.
  1853. */
  1854. function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
  1855. // Use the advanced drupal_static() pattern, since this is called very often.
  1856. static $drupal_static_fast;
  1857. if (!isset($drupal_static_fast)) {
  1858. $drupal_static_fast['timezones'] = &drupal_static(__FUNCTION__);
  1859. }
  1860. $timezones = &$drupal_static_fast['timezones'];
  1861. if (!isset($timezone)) {
  1862. $timezone = date_default_timezone_get();
  1863. }
  1864. // Store DateTimeZone objects in an array rather than repeatedly
  1865. // constructing identical objects over the life of a request.
  1866. if (!isset($timezones[$timezone])) {
  1867. $timezones[$timezone] = timezone_open($timezone);
  1868. }
  1869. // Use the default langcode if none is set.
  1870. global $language;
  1871. if (empty($langcode)) {
  1872. $langcode = isset($language->language) ? $language->language : 'en';
  1873. }
  1874. switch ($type) {
  1875. case 'short':
  1876. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  1877. break;
  1878. case 'long':
  1879. $format = variable_get('date_format_long', 'l, F j, Y - H:i');
  1880. break;
  1881. case 'custom':
  1882. // No change to format.
  1883. break;
  1884. case 'medium':
  1885. default:
  1886. // Retrieve the format of the custom $type passed.
  1887. if ($type != 'medium') {
  1888. $format = variable_get('date_format_' . $type, '');
  1889. }
  1890. // Fall back to 'medium'.
  1891. if ($format === '') {
  1892. $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  1893. }
  1894. break;
  1895. }
  1896. // Create a DateTime object from the timestamp.
  1897. $date_time = date_create('@' . $timestamp);
  1898. // Set the time zone for the DateTime object.
  1899. date_timezone_set($date_time, $timezones[$timezone]);
  1900. // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
  1901. // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
  1902. // input string.
  1903. // Paired backslashes are isolated to prevent errors in read-ahead evaluation.
  1904. // The read-ahead expression ensures that A matches, but not \A.
  1905. $format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);
  1906. // Call date_format().
  1907. $format = date_format($date_time, $format);
  1908. // Pass the langcode to _format_date_callback().
  1909. _format_date_callback(NULL, $langcode);
  1910. // Translate the marked sequences.
  1911. return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
  1912. }
  1913. /**
  1914. * Returns an ISO8601 formatted date based on the given date.
  1915. *
  1916. * Callback for use within hook_rdf_mapping() implementations.
  1917. *
  1918. * @param $date
  1919. * A UNIX timestamp.
  1920. *
  1921. * @return string
  1922. * An ISO8601 formatted date.
  1923. */
  1924. function date_iso8601($date) {
  1925. // The DATE_ISO8601 constant cannot be used here because it does not match
  1926. // date('c') and produces invalid RDF markup.
  1927. return date('c', $date);
  1928. }
  1929. /**
  1930. * Translates a formatted date string.
  1931. *
  1932. * Callback for preg_replace_callback() within format_date().
  1933. */
  1934. function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
  1935. // We cache translations to avoid redundant and rather costly calls to t().
  1936. static $cache, $langcode;
  1937. if (!isset($matches)) {
  1938. $langcode = $new_langcode;
  1939. return;
  1940. }
  1941. $code = $matches[1];
  1942. $string = $matches[2];
  1943. if (!isset($cache[$langcode][$code][$string])) {
  1944. $options = array(
  1945. 'langcode' => $langcode,
  1946. );
  1947. if ($code == 'F') {
  1948. $options['context'] = 'Long month name';
  1949. }
  1950. if ($code == '') {
  1951. $cache[$langcode][$code][$string] = $string;
  1952. }
  1953. else {
  1954. $cache[$langcode][$code][$string] = t($string, array(), $options);
  1955. }
  1956. }
  1957. return $cache[$langcode][$code][$string];
  1958. }
  1959. /**
  1960. * Format a username.
  1961. *
  1962. * This is also the label callback implementation of
  1963. * callback_entity_info_label() for user_entity_info().
  1964. *
  1965. * By default, the passed-in object's 'name' property is used if it exists, or
  1966. * else, the site-defined value for the 'anonymous' variable. However, a module
  1967. * may override this by implementing hook_username_alter(&$name, $account).
  1968. *
  1969. * @see hook_username_alter()
  1970. *
  1971. * @param $account
  1972. * The account object for the user whose name is to be formatted.
  1973. *
  1974. * @return
  1975. * An unsanitized string with the username to display. The code receiving
  1976. * this result must ensure that check_plain() is called on it before it is
  1977. * printed to the page.
  1978. */
  1979. function format_username($account) {
  1980. $name = !empty($account->name) ? $account->name : variable_get('anonymous', t('Anonymous'));
  1981. drupal_alter('username', $name, $account);
  1982. return $name;
  1983. }
  1984. /**
  1985. * @} End of "defgroup format".
  1986. */
  1987. /**
  1988. * Generates an internal or external URL.
  1989. *
  1990. * When creating links in modules, consider whether l() could be a better
  1991. * alternative than url().
  1992. *
  1993. * @param $path
  1994. * (optional) The internal path or external URL being linked to, such as
  1995. * "node/34" or "http://example.com/foo". The default value is equivalent to
  1996. * passing in '<front>'. A few notes:
  1997. * - If you provide a full URL, it will be considered an external URL.
  1998. * - If you provide only the path (e.g. "node/34"), it will be
  1999. * considered an internal link. In this case, it should be a system URL,
  2000. * and it will be replaced with the alias, if one exists. Additional query
  2001. * arguments for internal paths must be supplied in $options['query'], not
  2002. * included in $path.
  2003. * - If you provide an internal path and $options['alias'] is set to TRUE, the
  2004. * path is assumed already to be the correct path alias, and the alias is
  2005. * not looked up.
  2006. * - The special string '<front>' generates a link to the site's base URL.
  2007. * - If your external URL contains a query (e.g. http://example.com/foo?a=b),
  2008. * then you can either URL encode the query keys and values yourself and
  2009. * include them in $path, or use $options['query'] to let this function
  2010. * URL encode them.
  2011. * @param $options
  2012. * (optional) An associative array of additional options, with the following
  2013. * elements:
  2014. * - 'query': An array of query key/value-pairs (without any URL-encoding) to
  2015. * append to the URL.
  2016. * - 'fragment': A fragment identifier (named anchor) to append to the URL.
  2017. * Do not include the leading '#' character.
  2018. * - 'absolute': Defaults to FALSE. Whether to force the output to be an
  2019. * absolute link (beginning with http:). Useful for links that will be
  2020. * displayed outside the site, such as in an RSS feed.
  2021. * - 'alias': Defaults to FALSE. Whether the given path is a URL alias
  2022. * already.
  2023. * - 'external': Whether the given path is an external URL.
  2024. * - 'language': An optional language object. If the path being linked to is
  2025. * internal to the site, $options['language'] is used to look up the alias
  2026. * for the URL. If $options['language'] is omitted, the global $language_url
  2027. * will be used.
  2028. * - 'https': Whether this URL should point to a secure location. If not
  2029. * defined, the current scheme is used, so the user stays on HTTP or HTTPS
  2030. * respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
  2031. * only be enforced when the variable 'https' is set to TRUE.
  2032. * - 'base_url': Only used internally, to modify the base URL when a language
  2033. * dependent URL requires so.
  2034. * - 'prefix': Only used internally, to modify the path when a language
  2035. * dependent URL requires so.
  2036. * - 'script': The script filename in Drupal's root directory to use when
  2037. * clean URLs are disabled, such as 'index.php'. Defaults to an empty
  2038. * string, as most modern web servers automatically find 'index.php'. If
  2039. * clean URLs are disabled, the value of $path is appended as query
  2040. * parameter 'q' to $options['script'] in the returned URL. When deploying
  2041. * Drupal on a web server that cannot be configured to automatically find
  2042. * index.php, then hook_url_outbound_alter() can be implemented to force
  2043. * this value to 'index.php'.
  2044. * - 'entity_type': The entity type of the object that called url(). Only
  2045. * set if url() is invoked by entity_uri().
  2046. * - 'entity': The entity object (such as a node) for which the URL is being
  2047. * generated. Only set if url() is invoked by entity_uri().
  2048. *
  2049. * @return
  2050. * A string containing a URL to the given path.
  2051. */
  2052. function url($path = NULL, array $options = array()) {
  2053. // Merge in defaults.
  2054. $options += array(
  2055. 'fragment' => '',
  2056. 'query' => array(),
  2057. 'absolute' => FALSE,
  2058. 'alias' => FALSE,
  2059. 'prefix' => ''
  2060. );
  2061. // Determine whether this is an external link, but ensure that the current
  2062. // path is always treated as internal by default (to prevent external link
  2063. // injection vulnerabilities).
  2064. if (!isset($options['external'])) {
  2065. $options['external'] = $path === $_GET['q'] ? FALSE : url_is_external($path);
  2066. }
  2067. // Preserve the original path before altering or aliasing.
  2068. $original_path = $path;
  2069. // Allow other modules to alter the outbound URL and options.
  2070. drupal_alter('url_outbound', $path, $options, $original_path);
  2071. if (isset($options['fragment']) && $options['fragment'] !== '') {
  2072. $options['fragment'] = '#' . $options['fragment'];
  2073. }
  2074. if ($options['external']) {
  2075. // Split off the fragment.
  2076. if (strpos($path, '#') !== FALSE) {
  2077. list($path, $old_fragment) = explode('#', $path, 2);
  2078. // If $options contains no fragment, take it over from the path.
  2079. if (isset($old_fragment) && !$options['fragment']) {
  2080. $options['fragment'] = '#' . $old_fragment;
  2081. }
  2082. }
  2083. // Append the query.
  2084. if ($options['query']) {
  2085. $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
  2086. }
  2087. if (isset($options['https']) && variable_get('https', FALSE)) {
  2088. if ($options['https'] === TRUE) {
  2089. $path = str_replace('http://', 'https://', $path);
  2090. }
  2091. elseif ($options['https'] === FALSE) {
  2092. $path = str_replace('https://', 'http://', $path);
  2093. }
  2094. }
  2095. // Reassemble.
  2096. return $path . $options['fragment'];
  2097. }
  2098. // Strip leading slashes from internal paths to prevent them becoming external
  2099. // URLs without protocol. /example.com should not be turned into
  2100. // //example.com.
  2101. $path = ltrim($path, '/');
  2102. global $base_url, $base_secure_url, $base_insecure_url;
  2103. // The base_url might be rewritten from the language rewrite in domain mode.
  2104. if (!isset($options['base_url'])) {
  2105. if (isset($options['https']) && variable_get('https', FALSE)) {
  2106. if ($options['https'] === TRUE) {
  2107. $options['base_url'] = $base_secure_url;
  2108. $options['absolute'] = TRUE;
  2109. }
  2110. elseif ($options['https'] === FALSE) {
  2111. $options['base_url'] = $base_insecure_url;
  2112. $options['absolute'] = TRUE;
  2113. }
  2114. }
  2115. else {
  2116. $options['base_url'] = $base_url;
  2117. }
  2118. }
  2119. // The special path '<front>' links to the default front page.
  2120. if ($path == '<front>') {
  2121. $path = '';
  2122. }
  2123. elseif (!empty($path) && !$options['alias']) {
  2124. $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
  2125. $alias = drupal_get_path_alias($original_path, $language);
  2126. if ($alias != $original_path) {
  2127. // Strip leading slashes from internal path aliases to prevent them
  2128. // becoming external URLs without protocol. /example.com should not be
  2129. // turned into //example.com.
  2130. $path = ltrim($alias, '/');
  2131. }
  2132. }
  2133. $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
  2134. $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
  2135. // With Clean URLs.
  2136. if (!empty($GLOBALS['conf']['clean_url'])) {
  2137. $path = drupal_encode_path($prefix . $path);
  2138. if ($options['query']) {
  2139. return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
  2140. }
  2141. else {
  2142. return $base . $path . $options['fragment'];
  2143. }
  2144. }
  2145. // Without Clean URLs.
  2146. else {
  2147. $path = $prefix . $path;
  2148. $query = array();
  2149. if (!empty($path)) {
  2150. $query['q'] = $path;
  2151. }
  2152. if ($options['query']) {
  2153. // We do not use array_merge() here to prevent overriding $path via query
  2154. // parameters.
  2155. $query += $options['query'];
  2156. }
  2157. $query = $query ? ('?' . drupal_http_build_query($query)) : '';
  2158. $script = isset($options['script']) ? $options['script'] : '';
  2159. return $base . $script . $query . $options['fragment'];
  2160. }
  2161. }
  2162. /**
  2163. * Returns TRUE if a path is external to Drupal (e.g. http://example.com).
  2164. *
  2165. * If a path cannot be assessed by Drupal's menu handler, then we must
  2166. * treat it as potentially insecure.
  2167. *
  2168. * @param $path
  2169. * The internal path or external URL being linked to, such as "node/34" or
  2170. * "http://example.com/foo".
  2171. *
  2172. * @return
  2173. * Boolean TRUE or FALSE, where TRUE indicates an external path.
  2174. */
  2175. function url_is_external($path) {
  2176. $colonpos = strpos($path, ':');
  2177. // Some browsers treat \ as / so normalize to forward slashes.
  2178. $path = str_replace('\\', '/', $path);
  2179. // If the path starts with 2 slashes then it is always considered an external
  2180. // URL without an explicit protocol part.
  2181. return (strpos($path, '//') === 0)
  2182. // Leading control characters may be ignored or mishandled by browsers, so
  2183. // assume such a path may lead to an external location. The \p{C} character
  2184. // class matches all UTF-8 control, unassigned, and private characters.
  2185. || (preg_match('/^\p{C}/u', $path) !== 0)
  2186. // Avoid calling drupal_strip_dangerous_protocols() if there is any slash
  2187. // (/), hash (#) or question_mark (?) before the colon (:) occurrence - if
  2188. // any - as this would clearly mean it is not a URL.
  2189. || ($colonpos !== FALSE
  2190. && !preg_match('![/?#]!', substr($path, 0, $colonpos))
  2191. && drupal_strip_dangerous_protocols($path) == $path);
  2192. }
  2193. /**
  2194. * Formats an attribute string for an HTTP header.
  2195. *
  2196. * @param $attributes
  2197. * An associative array of attributes such as 'rel'.
  2198. *
  2199. * @return
  2200. * A ; separated string ready for insertion in a HTTP header. No escaping is
  2201. * performed for HTML entities, so this string is not safe to be printed.
  2202. *
  2203. * @see drupal_add_http_header()
  2204. */
  2205. function drupal_http_header_attributes(array $attributes = array()) {
  2206. foreach ($attributes as $attribute => &$data) {
  2207. if (is_array($data)) {
  2208. $data = implode(' ', $data);
  2209. }
  2210. $data = $attribute . '="' . $data . '"';
  2211. }
  2212. return $attributes ? ' ' . implode('; ', $attributes) : '';
  2213. }
  2214. /**
  2215. * Converts an associative array to an XML/HTML tag attribute string.
  2216. *
  2217. * Each array key and its value will be formatted into an attribute string.
  2218. * If a value is itself an array, then its elements are concatenated to a single
  2219. * space-delimited string (for example, a class attribute with multiple values).
  2220. *
  2221. * Attribute values are sanitized by running them through check_plain().
  2222. * Attribute names are not automatically sanitized. When using user-supplied
  2223. * attribute names, it is strongly recommended to allow only white-listed names,
  2224. * since certain attributes carry security risks and can be abused.
  2225. *
  2226. * Examples of security aspects when using drupal_attributes:
  2227. * @code
  2228. * // By running the value in the following statement through check_plain,
  2229. * // the malicious script is neutralized.
  2230. * drupal_attributes(array('title' => t('<script>steal_cookie();</script>')));
  2231. *
  2232. * // The statement below demonstrates dangerous use of drupal_attributes, and
  2233. * // will return an onmouseout attribute with JavaScript code that, when used
  2234. * // as attribute in a tag, will cause users to be redirected to another site.
  2235. * //
  2236. * // In this case, the 'onmouseout' attribute should not be whitelisted --
  2237. * // you don't want users to have the ability to add this attribute or others
  2238. * // that take JavaScript commands.
  2239. * drupal_attributes(array('onmouseout' => 'window.location="http://malicious.com/";')));
  2240. * @endcode
  2241. *
  2242. * @param $attributes
  2243. * An associative array of key-value pairs to be converted to attributes.
  2244. *
  2245. * @return
  2246. * A string ready for insertion in a tag (starts with a space).
  2247. *
  2248. * @ingroup sanitization
  2249. */
  2250. function drupal_attributes(array $attributes = array()) {
  2251. foreach ($attributes as $attribute => &$data) {
  2252. $data = implode(' ', (array) $data);
  2253. $data = $attribute . '="' . check_plain($data) . '"';
  2254. }
  2255. return $attributes ? ' ' . implode(' ', $attributes) : '';
  2256. }
  2257. /**
  2258. * Formats an internal or external URL link as an HTML anchor tag.
  2259. *
  2260. * This function correctly handles aliased paths and adds an 'active' class
  2261. * attribute to links that point to the current page (for theming), so all
  2262. * internal links output by modules should be generated by this function if
  2263. * possible.
  2264. *
  2265. * However, for links enclosed in translatable text you should use t() and
  2266. * embed the HTML anchor tag directly in the translated string. For example:
  2267. * @code
  2268. * t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));
  2269. * @endcode
  2270. * This keeps the context of the link title ('settings' in the example) for
  2271. * translators.
  2272. *
  2273. * @param string $text
  2274. * The translated link text for the anchor tag.
  2275. * @param string $path
  2276. * The internal path or external URL being linked to, such as "node/34" or
  2277. * "http://example.com/foo". After the url() function is called to construct
  2278. * the URL from $path and $options, the resulting URL is passed through
  2279. * check_plain() before it is inserted into the HTML anchor tag, to ensure
  2280. * well-formed HTML. See url() for more information and notes.
  2281. * @param array $options
  2282. * An associative array of additional options. Defaults to an empty array. It
  2283. * may contain the following elements.
  2284. * - 'attributes': An associative array of HTML attributes to apply to the
  2285. * anchor tag. If element 'class' is included, it must be an array; 'title'
  2286. * must be a string; other elements are more flexible, as they just need
  2287. * to work in a call to drupal_attributes($options['attributes']).
  2288. * - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
  2289. * example, to make an image tag into a link, this must be set to TRUE, or
  2290. * you will see the escaped HTML image tag. $text is not sanitized if
  2291. * 'html' is TRUE. The calling function must ensure that $text is already
  2292. * safe.
  2293. * - 'language': An optional language object. If the path being linked to is
  2294. * internal to the site, $options['language'] is used to determine whether
  2295. * the link is "active", or pointing to the current page (the language as
  2296. * well as the path must match). This element is also used by url().
  2297. * - Additional $options elements used by the url() function.
  2298. *
  2299. * @return string
  2300. * An HTML string containing a link to the given path.
  2301. *
  2302. * @see url()
  2303. */
  2304. function l($text, $path, array $options = array()) {
  2305. global $language_url;
  2306. static $use_theme = NULL;
  2307. // Merge in defaults.
  2308. $options += array(
  2309. 'attributes' => array(),
  2310. 'html' => FALSE,
  2311. );
  2312. // Append active class.
  2313. if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
  2314. (empty($options['language']) || $options['language']->language == $language_url->language)) {
  2315. $options['attributes']['class'][] = 'active';
  2316. }
  2317. // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
  2318. // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
  2319. if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
  2320. $options['attributes']['title'] = strip_tags($options['attributes']['title']);
  2321. }
  2322. // Determine if rendering of the link is to be done with a theme function
  2323. // or the inline default. Inline is faster, but if the theme system has been
  2324. // loaded and a module or theme implements a preprocess or process function
  2325. // or overrides the theme_link() function, then invoke theme(). Preliminary
  2326. // benchmarks indicate that invoking theme() can slow down the l() function
  2327. // by 20% or more, and that some of the link-heavy Drupal pages spend more
  2328. // than 10% of the total page request time in the l() function.
  2329. if (!isset($use_theme) && function_exists('theme')) {
  2330. // Allow edge cases to prevent theme initialization and force inline link
  2331. // rendering.
  2332. if (variable_get('theme_link', TRUE)) {
  2333. drupal_theme_initialize();
  2334. $registry = theme_get_registry(FALSE);
  2335. // We don't want to duplicate functionality that's in theme(), so any
  2336. // hint of a module or theme doing anything at all special with the 'link'
  2337. // theme hook should simply result in theme() being called. This includes
  2338. // the overriding of theme_link() with an alternate function or template,
  2339. // the presence of preprocess or process functions, or the presence of
  2340. // include files.
  2341. $use_theme = !isset($registry['link']['function']) || ($registry['link']['function'] != 'theme_link');
  2342. $use_theme = $use_theme || !empty($registry['link']['preprocess functions']) || !empty($registry['link']['process functions']) || !empty($registry['link']['includes']);
  2343. }
  2344. else {
  2345. $use_theme = FALSE;
  2346. }
  2347. }
  2348. if ($use_theme) {
  2349. return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
  2350. }
  2351. // The result of url() is a plain-text URL. Because we are using it here
  2352. // in an HTML argument context, we need to encode it properly.
  2353. return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
  2354. }
  2355. /**
  2356. * Delivers a page callback result to the browser in the appropriate format.
  2357. *
  2358. * This function is most commonly called by menu_execute_active_handler(), but
  2359. * can also be called by error conditions such as drupal_not_found(),
  2360. * drupal_access_denied(), and drupal_site_offline().
  2361. *
  2362. * When a user requests a page, index.php calls menu_execute_active_handler(),
  2363. * which calls the 'page callback' function registered in hook_menu(). The page
  2364. * callback function can return one of:
  2365. * - NULL: to indicate no content.
  2366. * - An integer menu status constant: to indicate an error condition.
  2367. * - A string of HTML content.
  2368. * - A renderable array of content.
  2369. * Returning a renderable array rather than a string of HTML is preferred,
  2370. * because that provides modules with more flexibility in customizing the final
  2371. * result.
  2372. *
  2373. * When the page callback returns its constructed content to
  2374. * menu_execute_active_handler(), this function gets called. The purpose of
  2375. * this function is to determine the most appropriate 'delivery callback'
  2376. * function to route the content to. The delivery callback function then
  2377. * sends the content to the browser in the needed format. The default delivery
  2378. * callback is drupal_deliver_html_page(), which delivers the content as an HTML
  2379. * page, complete with blocks in addition to the content. This default can be
  2380. * overridden on a per menu router item basis by setting 'delivery callback' in
  2381. * hook_menu() or hook_menu_alter(), and can also be overridden on a per request
  2382. * basis in hook_page_delivery_callback_alter().
  2383. *
  2384. * For example, the same page callback function can be used for an HTML
  2385. * version of the page and an Ajax version of the page. The page callback
  2386. * function just needs to decide what content is to be returned and the
  2387. * delivery callback function will send it as an HTML page or an Ajax
  2388. * response, as appropriate.
  2389. *
  2390. * In order for page callbacks to be reusable in different delivery formats,
  2391. * they should not issue any "print" or "echo" statements, but instead just
  2392. * return content.
  2393. *
  2394. * Also note that this function does not perform access checks. The delivery
  2395. * callback function specified in hook_menu(), hook_menu_alter(), or
  2396. * hook_page_delivery_callback_alter() will be called even if the router item
  2397. * access checks fail. This is intentional (it is needed for JSON and other
  2398. * purposes), but it has security implications. Do not call this function
  2399. * directly unless you understand the security implications, and be careful in
  2400. * writing delivery callbacks, so that they do not violate security. See
  2401. * drupal_deliver_html_page() for an example of a delivery callback that
  2402. * respects security.
  2403. *
  2404. * @param $page_callback_result
  2405. * The result of a page callback. Can be one of:
  2406. * - NULL: to indicate no content.
  2407. * - An integer menu status constant: to indicate an error condition.
  2408. * - A string of HTML content.
  2409. * - A renderable array of content.
  2410. * @param $default_delivery_callback
  2411. * (Optional) If given, it is the name of a delivery function most likely
  2412. * to be appropriate for the page request as determined by the calling
  2413. * function (e.g., menu_execute_active_handler()). If not given, it is
  2414. * determined from the menu router information of the current page.
  2415. *
  2416. * @see menu_execute_active_handler()
  2417. * @see hook_menu()
  2418. * @see hook_menu_alter()
  2419. * @see hook_page_delivery_callback_alter()
  2420. */
  2421. function drupal_deliver_page($page_callback_result, $default_delivery_callback = NULL) {
  2422. if (!isset($default_delivery_callback) && ($router_item = menu_get_item())) {
  2423. $default_delivery_callback = $router_item['delivery_callback'];
  2424. }
  2425. $delivery_callback = !empty($default_delivery_callback) ? $default_delivery_callback : 'drupal_deliver_html_page';
  2426. // Give modules a chance to alter the delivery callback used, based on
  2427. // request-time context (e.g., HTTP request headers).
  2428. drupal_alter('page_delivery_callback', $delivery_callback);
  2429. if (function_exists($delivery_callback)) {
  2430. $delivery_callback($page_callback_result);
  2431. }
  2432. else {
  2433. // If a delivery callback is specified, but doesn't exist as a function,
  2434. // something is wrong, but don't print anything, since it's not known
  2435. // what format the response needs to be in.
  2436. watchdog('delivery callback not found', 'callback %callback not found: %q.', array('%callback' => $delivery_callback, '%q' => $_GET['q']), WATCHDOG_ERROR);
  2437. }
  2438. }
  2439. /**
  2440. * Packages and sends the result of a page callback to the browser as HTML.
  2441. *
  2442. * @param $page_callback_result
  2443. * The result of a page callback. Can be one of:
  2444. * - NULL: to indicate no content.
  2445. * - An integer menu status constant: to indicate an error condition.
  2446. * - A string of HTML content.
  2447. * - A renderable array of content.
  2448. *
  2449. * @see drupal_deliver_page()
  2450. */
  2451. function drupal_deliver_html_page($page_callback_result) {
  2452. // Emit the correct charset HTTP header, but not if the page callback
  2453. // result is NULL, since that likely indicates that it printed something
  2454. // in which case, no further headers may be sent, and not if code running
  2455. // for this page request has already set the content type header.
  2456. if (isset($page_callback_result) && is_null(drupal_get_http_header('Content-Type'))) {
  2457. drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
  2458. }
  2459. // Send appropriate HTTP-Header for browsers and search engines.
  2460. global $language;
  2461. drupal_add_http_header('Content-Language', $language->language);
  2462. // By default, do not allow the site to be rendered in an iframe on another
  2463. // domain, but provide a variable to override this. If the code running for
  2464. // this page request already set the X-Frame-Options header earlier, don't
  2465. // overwrite it here.
  2466. $frame_options = variable_get('x_frame_options', 'SAMEORIGIN');
  2467. if ($frame_options && is_null(drupal_get_http_header('X-Frame-Options'))) {
  2468. drupal_add_http_header('X-Frame-Options', $frame_options);
  2469. }
  2470. // Menu status constants are integers; page content is a string or array.
  2471. if (is_int($page_callback_result)) {
  2472. // @todo: Break these up into separate functions?
  2473. switch ($page_callback_result) {
  2474. case MENU_NOT_FOUND:
  2475. // Print a 404 page.
  2476. drupal_add_http_header('Status', '404 Not Found');
  2477. watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  2478. // Check for and return a fast 404 page if configured.
  2479. drupal_fast_404();
  2480. // Keep old path for reference, and to allow forms to redirect to it.
  2481. if (!isset($_GET['destination'])) {
  2482. // Make sure that the current path is not interpreted as external URL.
  2483. if (!url_is_external($_GET['q'])) {
  2484. $_GET['destination'] = $_GET['q'];
  2485. }
  2486. }
  2487. $path = drupal_get_normal_path(variable_get('site_404', ''));
  2488. if ($path && $path != $_GET['q']) {
  2489. // Custom 404 handler. Set the active item in case there are tabs to
  2490. // display, or other dependencies on the path.
  2491. menu_set_active_item($path);
  2492. $return = menu_execute_active_handler($path, FALSE);
  2493. }
  2494. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  2495. // Standard 404 handler.
  2496. drupal_set_title(t('Page not found'));
  2497. $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
  2498. }
  2499. drupal_set_page_content($return);
  2500. $page = element_info('page');
  2501. print drupal_render_page($page);
  2502. break;
  2503. case MENU_ACCESS_DENIED:
  2504. // Print a 403 page.
  2505. drupal_add_http_header('Status', '403 Forbidden');
  2506. watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  2507. // Keep old path for reference, and to allow forms to redirect to it.
  2508. if (!isset($_GET['destination'])) {
  2509. // Make sure that the current path is not interpreted as external URL.
  2510. if (!url_is_external($_GET['q'])) {
  2511. $_GET['destination'] = $_GET['q'];
  2512. }
  2513. }
  2514. $path = drupal_get_normal_path(variable_get('site_403', ''));
  2515. if ($path && $path != $_GET['q']) {
  2516. // Custom 403 handler. Set the active item in case there are tabs to
  2517. // display or other dependencies on the path.
  2518. menu_set_active_item($path);
  2519. $return = menu_execute_active_handler($path, FALSE);
  2520. }
  2521. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  2522. // Standard 403 handler.
  2523. drupal_set_title(t('Access denied'));
  2524. $return = t('You are not authorized to access this page.');
  2525. }
  2526. print drupal_render_page($return);
  2527. break;
  2528. case MENU_SITE_OFFLINE:
  2529. // Print a 503 page.
  2530. drupal_maintenance_theme();
  2531. drupal_add_http_header('Status', '503 Service unavailable');
  2532. drupal_set_title(t('Site under maintenance'));
  2533. print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
  2534. t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
  2535. break;
  2536. }
  2537. }
  2538. elseif (isset($page_callback_result)) {
  2539. // Print anything besides a menu constant, assuming it's not NULL or
  2540. // undefined.
  2541. print drupal_render_page($page_callback_result);
  2542. }
  2543. // Perform end-of-request tasks.
  2544. drupal_page_footer();
  2545. }
  2546. /**
  2547. * Performs end-of-request tasks.
  2548. *
  2549. * This function sets the page cache if appropriate, and allows modules to
  2550. * react to the closing of the page by calling hook_exit().
  2551. */
  2552. function drupal_page_footer() {
  2553. global $user;
  2554. module_invoke_all('exit');
  2555. // Commit the user session, if needed.
  2556. drupal_session_commit();
  2557. if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
  2558. drupal_serve_page_from_cache($cache);
  2559. }
  2560. else {
  2561. ob_flush();
  2562. }
  2563. _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
  2564. drupal_cache_system_paths();
  2565. module_implements_write_cache();
  2566. drupal_file_scan_write_cache();
  2567. system_run_automated_cron();
  2568. }
  2569. /**
  2570. * Performs end-of-request tasks.
  2571. *
  2572. * In some cases page requests need to end without calling drupal_page_footer().
  2573. * In these cases, call drupal_exit() instead. There should rarely be a reason
  2574. * to call exit instead of drupal_exit();
  2575. *
  2576. * @param $destination
  2577. * If this function is called from drupal_goto(), then this argument
  2578. * will be a fully-qualified URL that is the destination of the redirect.
  2579. * This should be passed along to hook_exit() implementations.
  2580. */
  2581. function drupal_exit($destination = NULL) {
  2582. if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
  2583. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  2584. module_invoke_all('exit', $destination);
  2585. }
  2586. drupal_session_commit();
  2587. }
  2588. exit;
  2589. }
  2590. /**
  2591. * Forms an associative array from a linear array.
  2592. *
  2593. * This function walks through the provided array and constructs an associative
  2594. * array out of it. The keys of the resulting array will be the values of the
  2595. * input array. The values will be the same as the keys unless a function is
  2596. * specified, in which case the output of the function is used for the values
  2597. * instead.
  2598. *
  2599. * @param $array
  2600. * A linear array.
  2601. * @param $function
  2602. * A name of a function to apply to all values before output.
  2603. *
  2604. * @return
  2605. * An associative array.
  2606. */
  2607. function drupal_map_assoc($array, $function = NULL) {
  2608. // array_combine() fails with empty arrays:
  2609. // http://bugs.php.net/bug.php?id=34857.
  2610. $array = !empty($array) ? array_combine($array, $array) : array();
  2611. if (is_callable($function)) {
  2612. $array = array_map($function, $array);
  2613. }
  2614. return $array;
  2615. }
  2616. /**
  2617. * Attempts to set the PHP maximum execution time.
  2618. *
  2619. * This function is a wrapper around the PHP function set_time_limit().
  2620. * When called, set_time_limit() restarts the timeout counter from zero.
  2621. * In other words, if the timeout is the default 30 seconds, and 25 seconds
  2622. * into script execution a call such as set_time_limit(20) is made, the
  2623. * script will run for a total of 45 seconds before timing out.
  2624. *
  2625. * If the current time limit is not unlimited it is possible to decrease the
  2626. * total time limit if the sum of the new time limit and the current time spent
  2627. * running the script is inferior to the original time limit. It is inherent to
  2628. * the way set_time_limit() works, it should rather be called with an
  2629. * appropriate value every time you need to allocate a certain amount of time
  2630. * to execute a task than only once at the beginning of the script.
  2631. *
  2632. * Before calling set_time_limit(), we check if this function is available
  2633. * because it could be disabled by the server administrator. We also hide all
  2634. * the errors that could occur when calling set_time_limit(), because it is
  2635. * not possible to reliably ensure that PHP or a security extension will
  2636. * not issue a warning/error if they prevent the use of this function.
  2637. *
  2638. * @param $time_limit
  2639. * An integer specifying the new time limit, in seconds. A value of 0
  2640. * indicates unlimited execution time.
  2641. *
  2642. * @ingroup php_wrappers
  2643. */
  2644. function drupal_set_time_limit($time_limit) {
  2645. if (function_exists('set_time_limit')) {
  2646. $current = ini_get('max_execution_time');
  2647. // Do not set time limit if it is currently unlimited.
  2648. if ($current != 0) {
  2649. @set_time_limit($time_limit);
  2650. }
  2651. }
  2652. }
  2653. /**
  2654. * Returns the path to a system item (module, theme, etc.).
  2655. *
  2656. * @param $type
  2657. * The type of the item (i.e. theme, theme_engine, module, profile).
  2658. * @param $name
  2659. * The name of the item for which the path is requested.
  2660. *
  2661. * @return
  2662. * The path to the requested item or an empty string if the item is not found.
  2663. */
  2664. function drupal_get_path($type, $name) {
  2665. return dirname(drupal_get_filename($type, $name));
  2666. }
  2667. /**
  2668. * Returns the base URL path (i.e., directory) of the Drupal installation.
  2669. *
  2670. * base_path() adds a "/" to the beginning and end of the returned path if the
  2671. * path is not empty. At the very least, this will return "/".
  2672. *
  2673. * Examples:
  2674. * - http://example.com returns "/" because the path is empty.
  2675. * - http://example.com/drupal/folder returns "/drupal/folder/".
  2676. */
  2677. function base_path() {
  2678. return $GLOBALS['base_path'];
  2679. }
  2680. /**
  2681. * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
  2682. *
  2683. * This function can be called as long the HTML header hasn't been sent, which
  2684. * on normal pages is up through the preprocess step of theme('html'). Adding
  2685. * a link will overwrite a prior link with the exact same 'rel' and 'href'
  2686. * attributes.
  2687. *
  2688. * @param $attributes
  2689. * Associative array of element attributes including 'href' and 'rel'.
  2690. * @param $header
  2691. * Optional flag to determine if a HTTP 'Link:' header should be sent.
  2692. */
  2693. function drupal_add_html_head_link($attributes, $header = FALSE) {
  2694. $element = array(
  2695. '#tag' => 'link',
  2696. '#attributes' => $attributes,
  2697. );
  2698. $href = $attributes['href'];
  2699. if ($header) {
  2700. // Also add a HTTP header "Link:".
  2701. $href = '<' . check_plain($attributes['href']) . '>;';
  2702. unset($attributes['href']);
  2703. $element['#attached']['drupal_add_http_header'][] = array('Link', $href . drupal_http_header_attributes($attributes), TRUE);
  2704. }
  2705. drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
  2706. }
  2707. /**
  2708. * Adds a cascading stylesheet to the stylesheet queue.
  2709. *
  2710. * Calling drupal_static_reset('drupal_add_css') will clear all cascading
  2711. * stylesheets added so far.
  2712. *
  2713. * If CSS aggregation/compression is enabled, all cascading style sheets added
  2714. * with $options['preprocess'] set to TRUE will be merged into one aggregate
  2715. * file and compressed by removing all extraneous white space.
  2716. * Preprocessed inline stylesheets will not be aggregated into this single file;
  2717. * instead, they are just compressed upon output on the page. Externally hosted
  2718. * stylesheets are never aggregated or compressed.
  2719. *
  2720. * The reason for aggregating the files is outlined quite thoroughly here:
  2721. * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
  2722. * to request overhead, one bigger file just loads faster than two smaller ones
  2723. * half its size."
  2724. *
  2725. * $options['preprocess'] should be only set to TRUE when a file is required for
  2726. * all typical visitors and most pages of a site. It is critical that all
  2727. * preprocessed files are added unconditionally on every page, even if the
  2728. * files do not happen to be needed on a page. This is normally done by calling
  2729. * drupal_add_css() in a hook_init() implementation.
  2730. *
  2731. * Non-preprocessed files should only be added to the page when they are
  2732. * actually needed.
  2733. *
  2734. * @param $data
  2735. * (optional) The stylesheet data to be added, depending on what is passed
  2736. * through to the $options['type'] parameter:
  2737. * - 'file': The path to the CSS file relative to the base_path(), or a
  2738. * stream wrapper URI. For example: "modules/devel/devel.css" or
  2739. * "public://generated_css/stylesheet_1.css". Note that Modules should
  2740. * always prefix the names of their CSS files with the module name; for
  2741. * example, system-menus.css rather than simply menus.css. Themes can
  2742. * override module-supplied CSS files based on their filenames, and this
  2743. * prefixing helps prevent confusing name collisions for theme developers.
  2744. * See drupal_get_css() where the overrides are performed. Also, if the
  2745. * direction of the current language is right-to-left (Hebrew, Arabic,
  2746. * etc.), the function will also look for an RTL CSS file and append it to
  2747. * the list. The name of this file should have an '-rtl.css' suffix. For
  2748. * example, a CSS file called 'mymodule-name.css' will have a
  2749. * 'mymodule-name-rtl.css' file added to the list, if exists in the same
  2750. * directory. This CSS file should contain overrides for properties which
  2751. * should be reversed or otherwise different in a right-to-left display.
  2752. * - 'inline': A string of CSS that should be placed in the given scope. Note
  2753. * that it is better practice to use 'file' stylesheets, rather than
  2754. * 'inline', as the CSS would then be aggregated and cached.
  2755. * - 'external': The absolute path to an external CSS file that is not hosted
  2756. * on the local server. These files will not be aggregated if CSS
  2757. * aggregation is enabled.
  2758. * @param $options
  2759. * (optional) A string defining the 'type' of CSS that is being added in the
  2760. * $data parameter ('file', 'inline', or 'external'), or an array which can
  2761. * have any or all of the following keys:
  2762. * - 'type': The type of stylesheet being added. Available options are 'file',
  2763. * 'inline' or 'external'. Defaults to 'file'.
  2764. * - 'basename': Force a basename for the file being added. Modules are
  2765. * expected to use stylesheets with unique filenames, but integration of
  2766. * external libraries may make this impossible. The basename of
  2767. * 'modules/node/node.css' is 'node.css'. If the external library "node.js"
  2768. * ships with a 'node.css', then a different, unique basename would be
  2769. * 'node.js.css'.
  2770. * - 'group': A number identifying the group in which to add the stylesheet.
  2771. * Available constants are:
  2772. * - CSS_SYSTEM: Any system-layer CSS.
  2773. * - CSS_DEFAULT: (default) Any module-layer CSS.
  2774. * - CSS_THEME: Any theme-layer CSS.
  2775. * The group number serves as a weight: the markup for loading a stylesheet
  2776. * within a lower weight group is output to the page before the markup for
  2777. * loading a stylesheet within a higher weight group, so CSS within higher
  2778. * weight groups take precendence over CSS within lower weight groups.
  2779. * - 'every_page': For optimal front-end performance when aggregation is
  2780. * enabled, this should be set to TRUE if the stylesheet is present on every
  2781. * page of the website for users for whom it is present at all. This
  2782. * defaults to FALSE. It is set to TRUE for stylesheets added via module and
  2783. * theme .info files. Modules that add stylesheets within hook_init()
  2784. * implementations, or from other code that ensures that the stylesheet is
  2785. * added to all website pages, should also set this flag to TRUE. All
  2786. * stylesheets within the same group that have the 'every_page' flag set to
  2787. * TRUE and do not have 'preprocess' set to FALSE are aggregated together
  2788. * into a single aggregate file, and that aggregate file can be reused
  2789. * across a user's entire site visit, leading to faster navigation between
  2790. * pages. However, stylesheets that are only needed on pages less frequently
  2791. * visited, can be added by code that only runs for those particular pages,
  2792. * and that code should not set the 'every_page' flag. This minimizes the
  2793. * size of the aggregate file that the user needs to download when first
  2794. * visiting the website. Stylesheets without the 'every_page' flag are
  2795. * aggregated into a separate aggregate file. This other aggregate file is
  2796. * likely to change from page to page, and each new aggregate file needs to
  2797. * be downloaded when first encountered, so it should be kept relatively
  2798. * small by ensuring that most commonly needed stylesheets are added to
  2799. * every page.
  2800. * - 'weight': The weight of the stylesheet specifies the order in which the
  2801. * CSS will appear relative to other stylesheets with the same group and
  2802. * 'every_page' flag. The exact ordering of stylesheets is as follows:
  2803. * - First by group.
  2804. * - Then by the 'every_page' flag, with TRUE coming before FALSE.
  2805. * - Then by weight.
  2806. * - Then by the order in which the CSS was added. For example, all else
  2807. * being the same, a stylesheet added by a call to drupal_add_css() that
  2808. * happened later in the page request gets added to the page after one for
  2809. * which drupal_add_css() happened earlier in the page request.
  2810. * - 'media': The media type for the stylesheet, e.g., all, print, screen.
  2811. * Defaults to 'all'.
  2812. * - 'preprocess': If TRUE and CSS aggregation/compression is enabled, the
  2813. * styles will be aggregated and compressed. Defaults to TRUE.
  2814. * - 'browsers': An array containing information specifying which browsers
  2815. * should load the CSS item. See drupal_pre_render_conditional_comments()
  2816. * for details.
  2817. *
  2818. * @return
  2819. * An array of queued cascading stylesheets.
  2820. *
  2821. * @see drupal_get_css()
  2822. */
  2823. function drupal_add_css($data = NULL, $options = NULL) {
  2824. $css = &drupal_static(__FUNCTION__, array());
  2825. $count = &drupal_static(__FUNCTION__ . '_count', 0);
  2826. // If the $css variable has been reset with drupal_static_reset(), there is
  2827. // no longer any CSS being tracked, so set the counter back to 0 also.
  2828. if (count($css) === 0) {
  2829. $count = 0;
  2830. }
  2831. // Construct the options, taking the defaults into consideration.
  2832. if (isset($options)) {
  2833. if (!is_array($options)) {
  2834. $options = array('type' => $options);
  2835. }
  2836. }
  2837. else {
  2838. $options = array();
  2839. }
  2840. // Create an array of CSS files for each media type first, since each type needs to be served
  2841. // to the browser differently.
  2842. if (isset($data)) {
  2843. $options += array(
  2844. 'type' => 'file',
  2845. 'group' => CSS_DEFAULT,
  2846. 'weight' => 0,
  2847. 'every_page' => FALSE,
  2848. 'media' => 'all',
  2849. 'preprocess' => TRUE,
  2850. 'data' => $data,
  2851. 'browsers' => array(),
  2852. );
  2853. $options['browsers'] += array(
  2854. 'IE' => TRUE,
  2855. '!IE' => TRUE,
  2856. );
  2857. // Files with a query string cannot be preprocessed.
  2858. if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
  2859. $options['preprocess'] = FALSE;
  2860. }
  2861. // Always add a tiny value to the weight, to conserve the insertion order.
  2862. $options['weight'] += $count / 1000;
  2863. $count++;
  2864. // Add the data to the CSS array depending on the type.
  2865. switch ($options['type']) {
  2866. case 'inline':
  2867. // For inline stylesheets, we don't want to use the $data as the array
  2868. // key as $data could be a very long string of CSS.
  2869. $css[] = $options;
  2870. break;
  2871. default:
  2872. // Local and external files must keep their name as the associative key
  2873. // so the same CSS file is not be added twice.
  2874. $css[$data] = $options;
  2875. }
  2876. }
  2877. return $css;
  2878. }
  2879. /**
  2880. * Returns a themed representation of all stylesheets to attach to the page.
  2881. *
  2882. * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
  2883. * This ensures proper cascading of styles so themes can easily override
  2884. * module styles through CSS selectors.
  2885. *
  2886. * Themes may replace module-defined CSS files by adding a stylesheet with the
  2887. * same filename. For example, themes/bartik/system-menus.css would replace
  2888. * modules/system/system-menus.css. This allows themes to override complete
  2889. * CSS files, rather than specific selectors, when necessary.
  2890. *
  2891. * If the original CSS file is being overridden by a theme, the theme is
  2892. * responsible for supplying an accompanying RTL CSS file to replace the
  2893. * module's.
  2894. *
  2895. * @param $css
  2896. * (optional) An array of CSS files. If no array is provided, the default
  2897. * stylesheets array is used instead.
  2898. * @param $skip_alter
  2899. * (optional) If set to TRUE, this function skips calling drupal_alter() on
  2900. * $css, useful when the calling function passes a $css array that has already
  2901. * been altered.
  2902. *
  2903. * @return
  2904. * A string of XHTML CSS tags.
  2905. *
  2906. * @see drupal_add_css()
  2907. */
  2908. function drupal_get_css($css = NULL, $skip_alter = FALSE) {
  2909. if (!isset($css)) {
  2910. $css = drupal_add_css();
  2911. }
  2912. // Allow modules and themes to alter the CSS items.
  2913. if (!$skip_alter) {
  2914. drupal_alter('css', $css);
  2915. }
  2916. // Sort CSS items, so that they appear in the correct order.
  2917. uasort($css, 'drupal_sort_css_js');
  2918. // Provide the page with information about the individual CSS files used,
  2919. // information not otherwise available when CSS aggregation is enabled. The
  2920. // setting is attached later in this function, but is set here, so that CSS
  2921. // files removed below are still considered "used" and prevented from being
  2922. // added in a later AJAX request.
  2923. // Skip if no files were added to the page or jQuery.extend() will overwrite
  2924. // the Drupal.settings.ajaxPageState.css object with an empty array.
  2925. if (!empty($css)) {
  2926. // Cast the array to an object to be on the safe side even if not empty.
  2927. $setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
  2928. }
  2929. // Remove the overridden CSS files. Later CSS files override former ones.
  2930. $previous_item = array();
  2931. foreach ($css as $key => $item) {
  2932. if ($item['type'] == 'file') {
  2933. // If defined, force a unique basename for this file.
  2934. $basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
  2935. if (isset($previous_item[$basename])) {
  2936. // Remove the previous item that shared the same base name.
  2937. unset($css[$previous_item[$basename]]);
  2938. }
  2939. $previous_item[$basename] = $key;
  2940. }
  2941. }
  2942. // Render the HTML needed to load the CSS.
  2943. $styles = array(
  2944. '#type' => 'styles',
  2945. '#items' => $css,
  2946. );
  2947. if (!empty($setting)) {
  2948. $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
  2949. }
  2950. return drupal_render($styles);
  2951. }
  2952. /**
  2953. * Sorts CSS and JavaScript resources.
  2954. *
  2955. * Callback for uasort() within:
  2956. * - drupal_get_css()
  2957. * - drupal_get_js()
  2958. *
  2959. * This sort order helps optimize front-end performance while providing modules
  2960. * and themes with the necessary control for ordering the CSS and JavaScript
  2961. * appearing on a page.
  2962. *
  2963. * @param $a
  2964. * First item for comparison. The compared items should be associative arrays
  2965. * of member items from drupal_add_css() or drupal_add_js().
  2966. * @param $b
  2967. * Second item for comparison.
  2968. *
  2969. * @see drupal_add_css()
  2970. * @see drupal_add_js()
  2971. */
  2972. function drupal_sort_css_js($a, $b) {
  2973. // First order by group, so that, for example, all items in the CSS_SYSTEM
  2974. // group appear before items in the CSS_DEFAULT group, which appear before
  2975. // all items in the CSS_THEME group. Modules may create additional groups by
  2976. // defining their own constants.
  2977. if ($a['group'] < $b['group']) {
  2978. return -1;
  2979. }
  2980. elseif ($a['group'] > $b['group']) {
  2981. return 1;
  2982. }
  2983. // Within a group, order all infrequently needed, page-specific files after
  2984. // common files needed throughout the website. Separating this way allows for
  2985. // the aggregate file generated for all of the common files to be reused
  2986. // across a site visit without being cut by a page using a less common file.
  2987. elseif ($a['every_page'] && !$b['every_page']) {
  2988. return -1;
  2989. }
  2990. elseif (!$a['every_page'] && $b['every_page']) {
  2991. return 1;
  2992. }
  2993. // Finally, order by weight.
  2994. elseif ($a['weight'] < $b['weight']) {
  2995. return -1;
  2996. }
  2997. elseif ($a['weight'] > $b['weight']) {
  2998. return 1;
  2999. }
  3000. else {
  3001. return 0;
  3002. }
  3003. }
  3004. /**
  3005. * Default callback to group CSS items.
  3006. *
  3007. * This function arranges the CSS items that are in the #items property of the
  3008. * styles element into groups. Arranging the CSS items into groups serves two
  3009. * purposes. When aggregation is enabled, files within a group are aggregated
  3010. * into a single file, significantly improving page loading performance by
  3011. * minimizing network traffic overhead. When aggregation is disabled, grouping
  3012. * allows multiple files to be loaded from a single STYLE tag, enabling sites
  3013. * with many modules enabled or a complex theme being used to stay within IE's
  3014. * 31 CSS inclusion tag limit: http://drupal.org/node/228818.
  3015. *
  3016. * This function puts multiple items into the same group if they are groupable
  3017. * and if they are for the same 'media' and 'browsers'. Items of the 'file' type
  3018. * are groupable if their 'preprocess' flag is TRUE, items of the 'inline' type
  3019. * are always groupable, and items of the 'external' type are never groupable.
  3020. * This function also ensures that the process of grouping items does not change
  3021. * their relative order. This requirement may result in multiple groups for the
  3022. * same type, media, and browsers, if needed to accommodate other items in
  3023. * between.
  3024. *
  3025. * @param $css
  3026. * An array of CSS items, as returned by drupal_add_css(), but after
  3027. * alteration performed by drupal_get_css().
  3028. *
  3029. * @return
  3030. * An array of CSS groups. Each group contains the same keys (e.g., 'media',
  3031. * 'data', etc.) as a CSS item from the $css parameter, with the value of
  3032. * each key applying to the group as a whole. Each group also contains an
  3033. * 'items' key, which is the subset of items from $css that are in the group.
  3034. *
  3035. * @see drupal_pre_render_styles()
  3036. * @see system_element_info()
  3037. */
  3038. function drupal_group_css($css) {
  3039. $groups = array();
  3040. // If a group can contain multiple items, we track the information that must
  3041. // be the same for each item in the group, so that when we iterate the next
  3042. // item, we can determine if it can be put into the current group, or if a
  3043. // new group needs to be made for it.
  3044. $current_group_keys = NULL;
  3045. // When creating a new group, we pre-increment $i, so by initializing it to
  3046. // -1, the first group will have index 0.
  3047. $i = -1;
  3048. foreach ($css as $item) {
  3049. // The browsers for which the CSS item needs to be loaded is part of the
  3050. // information that determines when a new group is needed, but the order of
  3051. // keys in the array doesn't matter, and we don't want a new group if all
  3052. // that's different is that order.
  3053. ksort($item['browsers']);
  3054. // If the item can be grouped with other items, set $group_keys to an array
  3055. // of information that must be the same for all items in its group. If the
  3056. // item can't be grouped with other items, set $group_keys to FALSE. We
  3057. // put items into a group that can be aggregated together: whether they will
  3058. // be aggregated is up to the _drupal_css_aggregate() function or an
  3059. // override of that function specified in hook_css_alter(), but regardless
  3060. // of the details of that function, a group represents items that can be
  3061. // aggregated. Since a group may be rendered with a single HTML tag, all
  3062. // items in the group must share the same information that would need to be
  3063. // part of that HTML tag.
  3064. switch ($item['type']) {
  3065. case 'file':
  3066. // Group file items if their 'preprocess' flag is TRUE.
  3067. // Help ensure maximum reuse of aggregate files by only grouping
  3068. // together items that share the same 'group' value and 'every_page'
  3069. // flag. See drupal_add_css() for details about that.
  3070. $group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
  3071. break;
  3072. case 'inline':
  3073. // Always group inline items.
  3074. $group_keys = array($item['type'], $item['media'], $item['browsers']);
  3075. break;
  3076. case 'external':
  3077. // Do not group external items.
  3078. $group_keys = FALSE;
  3079. break;
  3080. }
  3081. // If the group keys don't match the most recent group we're working with,
  3082. // then a new group must be made.
  3083. if ($group_keys !== $current_group_keys) {
  3084. $i++;
  3085. // Initialize the new group with the same properties as the first item
  3086. // being placed into it. The item's 'data' and 'weight' properties are
  3087. // unique to the item and should not be carried over to the group.
  3088. $groups[$i] = $item;
  3089. unset($groups[$i]['data'], $groups[$i]['weight']);
  3090. $groups[$i]['items'] = array();
  3091. $current_group_keys = $group_keys ? $group_keys : NULL;
  3092. }
  3093. // Add the item to the current group.
  3094. $groups[$i]['items'][] = $item;
  3095. }
  3096. return $groups;
  3097. }
  3098. /**
  3099. * Default callback to aggregate CSS files and inline content.
  3100. *
  3101. * Having the browser load fewer CSS files results in much faster page loads
  3102. * than when it loads many small files. This function aggregates files within
  3103. * the same group into a single file unless the site-wide setting to do so is
  3104. * disabled (commonly the case during site development). To optimize download,
  3105. * it also compresses the aggregate files by removing comments, whitespace, and
  3106. * other unnecessary content. Additionally, this functions aggregates inline
  3107. * content together, regardless of the site-wide aggregation setting.
  3108. *
  3109. * @param $css_groups
  3110. * An array of CSS groups as returned by drupal_group_css(). This function
  3111. * modifies the group's 'data' property for each group that is aggregated.
  3112. *
  3113. * @see drupal_group_css()
  3114. * @see drupal_pre_render_styles()
  3115. * @see system_element_info()
  3116. */
  3117. function drupal_aggregate_css(&$css_groups) {
  3118. $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  3119. // For each group that needs aggregation, aggregate its items.
  3120. foreach ($css_groups as $key => $group) {
  3121. switch ($group['type']) {
  3122. // If a file group can be aggregated into a single file, do so, and set
  3123. // the group's data property to the file path of the aggregate file.
  3124. case 'file':
  3125. if ($group['preprocess'] && $preprocess_css) {
  3126. $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
  3127. }
  3128. break;
  3129. // Aggregate all inline CSS content into the group's data property.
  3130. case 'inline':
  3131. $css_groups[$key]['data'] = '';
  3132. foreach ($group['items'] as $item) {
  3133. $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
  3134. }
  3135. break;
  3136. }
  3137. }
  3138. }
  3139. /**
  3140. * #pre_render callback to add the elements needed for CSS tags to be rendered.
  3141. *
  3142. * For production websites, LINK tags are preferable to STYLE tags with @import
  3143. * statements, because:
  3144. * - They are the standard tag intended for linking to a resource.
  3145. * - On Firefox 2 and perhaps other browsers, CSS files included with @import
  3146. * statements don't get saved when saving the complete web page for offline
  3147. * use: http://drupal.org/node/145218.
  3148. * - On IE, if only LINK tags and no @import statements are used, all the CSS
  3149. * files are downloaded in parallel, resulting in faster page load, but if
  3150. * @import statements are used and span across multiple STYLE tags, all the
  3151. * ones from one STYLE tag must be downloaded before downloading begins for
  3152. * the next STYLE tag. Furthermore, IE7 does not support media declaration on
  3153. * the @import statement, so multiple STYLE tags must be used when different
  3154. * files are for different media types. Non-IE browsers always download in
  3155. * parallel, so this is an IE-specific performance quirk:
  3156. * http://www.stevesouders.com/blog/2009/04/09/dont-use-import/.
  3157. *
  3158. * However, IE has an annoying limit of 31 total CSS inclusion tags
  3159. * (http://drupal.org/node/228818) and LINK tags are limited to one file per
  3160. * tag, whereas STYLE tags can contain multiple @import statements allowing
  3161. * multiple files to be loaded per tag. When CSS aggregation is disabled, a
  3162. * Drupal site can easily have more than 31 CSS files that need to be loaded, so
  3163. * using LINK tags exclusively would result in a site that would display
  3164. * incorrectly in IE. Depending on different needs, different strategies can be
  3165. * employed to decide when to use LINK tags and when to use STYLE tags.
  3166. *
  3167. * The strategy employed by this function is to use LINK tags for all aggregate
  3168. * files and for all files that cannot be aggregated (e.g., if 'preprocess' is
  3169. * set to FALSE or the type is 'external'), and to use STYLE tags for groups
  3170. * of files that could be aggregated together but aren't (e.g., if the site-wide
  3171. * aggregation setting is disabled). This results in all LINK tags when
  3172. * aggregation is enabled, a guarantee that as many or only slightly more tags
  3173. * are used with aggregation disabled than enabled (so that if the limit were to
  3174. * be crossed with aggregation enabled, the site developer would also notice the
  3175. * problem while aggregation is disabled), and an easy way for a developer to
  3176. * view HTML source while aggregation is disabled and know what files will be
  3177. * aggregated together when aggregation becomes enabled.
  3178. *
  3179. * This function evaluates the aggregation enabled/disabled condition on a group
  3180. * by group basis by testing whether an aggregate file has been made for the
  3181. * group rather than by testing the site-wide aggregation setting. This allows
  3182. * this function to work correctly even if modules have implemented custom
  3183. * logic for grouping and aggregating files.
  3184. *
  3185. * @param $element
  3186. * A render array containing:
  3187. * - '#items': The CSS items as returned by drupal_add_css() and altered by
  3188. * drupal_get_css().
  3189. * - '#group_callback': A function to call to group #items to enable the use
  3190. * of fewer tags by aggregating files and/or using multiple @import
  3191. * statements within a single tag.
  3192. * - '#aggregate_callback': A function to call to aggregate the items within
  3193. * the groups arranged by the #group_callback function.
  3194. *
  3195. * @return
  3196. * A render array that will render to a string of XHTML CSS tags.
  3197. *
  3198. * @see drupal_get_css()
  3199. */
  3200. function drupal_pre_render_styles($elements) {
  3201. // Group and aggregate the items.
  3202. if (isset($elements['#group_callback'])) {
  3203. $elements['#groups'] = $elements['#group_callback']($elements['#items']);
  3204. }
  3205. if (isset($elements['#aggregate_callback'])) {
  3206. $elements['#aggregate_callback']($elements['#groups']);
  3207. }
  3208. // A dummy query-string is added to filenames, to gain control over
  3209. // browser-caching. The string changes on every update or full cache
  3210. // flush, forcing browsers to load a new copy of the files, as the
  3211. // URL changed.
  3212. $query_string = variable_get('css_js_query_string', '0');
  3213. // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
  3214. // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
  3215. // comment out the CDATA-tag.
  3216. $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
  3217. $embed_suffix = "\n/*]]>*/-->\n";
  3218. // Defaults for LINK and STYLE elements.
  3219. $link_element_defaults = array(
  3220. '#type' => 'html_tag',
  3221. '#tag' => 'link',
  3222. '#attributes' => array(
  3223. 'type' => 'text/css',
  3224. 'rel' => 'stylesheet',
  3225. ),
  3226. );
  3227. $style_element_defaults = array(
  3228. '#type' => 'html_tag',
  3229. '#tag' => 'style',
  3230. '#attributes' => array(
  3231. 'type' => 'text/css',
  3232. ),
  3233. );
  3234. // Loop through each group.
  3235. foreach ($elements['#groups'] as $group) {
  3236. switch ($group['type']) {
  3237. // For file items, there are three possibilites.
  3238. // - The group has been aggregated: in this case, output a LINK tag for
  3239. // the aggregate file.
  3240. // - The group can be aggregated but has not been (most likely because
  3241. // the site administrator disabled the site-wide setting): in this case,
  3242. // output as few STYLE tags for the group as possible, using @import
  3243. // statement for each file in the group. This enables us to stay within
  3244. // IE's limit of 31 total CSS inclusion tags.
  3245. // - The group contains items not eligible for aggregation (their
  3246. // 'preprocess' flag has been set to FALSE): in this case, output a LINK
  3247. // tag for each file.
  3248. case 'file':
  3249. // The group has been aggregated into a single file: output a LINK tag
  3250. // for the aggregate file.
  3251. if (isset($group['data'])) {
  3252. $element = $link_element_defaults;
  3253. $element['#attributes']['href'] = file_create_url($group['data']);
  3254. $element['#attributes']['media'] = $group['media'];
  3255. $element['#browsers'] = $group['browsers'];
  3256. $elements[] = $element;
  3257. }
  3258. // The group can be aggregated, but hasn't been: combine multiple items
  3259. // into as few STYLE tags as possible.
  3260. elseif ($group['preprocess']) {
  3261. $import = array();
  3262. foreach ($group['items'] as $item) {
  3263. // A theme's .info file may have an entry for a file that doesn't
  3264. // exist as a way of overriding a module or base theme CSS file from
  3265. // being added to the page. Normally, file_exists() calls that need
  3266. // to run for every page request should be minimized, but this one
  3267. // is okay, because it only runs when CSS aggregation is disabled.
  3268. // On a server under heavy enough load that file_exists() calls need
  3269. // to be minimized, CSS aggregation should be enabled, in which case
  3270. // this code is not run. When aggregation is enabled,
  3271. // drupal_load_stylesheet() checks file_exists(), but only when
  3272. // building the aggregate file, which is then reused for many page
  3273. // requests.
  3274. if (file_exists($item['data'])) {
  3275. // The dummy query string needs to be added to the URL to control
  3276. // browser-caching. IE7 does not support a media type on the
  3277. // @import statement, so we instead specify the media for the
  3278. // group on the STYLE tag.
  3279. $import[] = '@import url("' . check_plain(file_create_url($item['data']) . '?' . $query_string) . '");';
  3280. }
  3281. }
  3282. // In addition to IE's limit of 31 total CSS inclusion tags, it also
  3283. // has a limit of 31 @import statements per STYLE tag.
  3284. while (!empty($import)) {
  3285. $import_batch = array_slice($import, 0, 31);
  3286. $import = array_slice($import, 31);
  3287. $element = $style_element_defaults;
  3288. // This simplifies the JavaScript regex, allowing each line
  3289. // (separated by \n) to be treated as a completely different string.
  3290. // This means that we can use ^ and $ on one line at a time, and not
  3291. // worry about style tags since they'll never match the regex.
  3292. $element['#value'] = "\n" . implode("\n", $import_batch) . "\n";
  3293. $element['#attributes']['media'] = $group['media'];
  3294. $element['#browsers'] = $group['browsers'];
  3295. $elements[] = $element;
  3296. }
  3297. }
  3298. // The group contains items ineligible for aggregation: output a LINK
  3299. // tag for each file.
  3300. else {
  3301. foreach ($group['items'] as $item) {
  3302. $element = $link_element_defaults;
  3303. // We do not check file_exists() here, because this code runs for
  3304. // files whose 'preprocess' is set to FALSE, and therefore, even
  3305. // when aggregation is enabled, and we want to avoid needlessly
  3306. // taxing a server that may be under heavy load. The file_exists()
  3307. // performed above for files whose 'preprocess' is TRUE is done for
  3308. // the benefit of theme .info files, but code that deals with files
  3309. // whose 'preprocess' is FALSE is responsible for ensuring the file
  3310. // exists.
  3311. // The dummy query string needs to be added to the URL to control
  3312. // browser-caching.
  3313. $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
  3314. $element['#attributes']['href'] = file_create_url($item['data']) . $query_string_separator . $query_string;
  3315. $element['#attributes']['media'] = $item['media'];
  3316. $element['#browsers'] = $group['browsers'];
  3317. $elements[] = $element;
  3318. }
  3319. }
  3320. break;
  3321. // For inline content, the 'data' property contains the CSS content. If
  3322. // the group's 'data' property is set, then output it in a single STYLE
  3323. // tag. Otherwise, output a separate STYLE tag for each item.
  3324. case 'inline':
  3325. if (isset($group['data'])) {
  3326. $element = $style_element_defaults;
  3327. $element['#value'] = $group['data'];
  3328. $element['#value_prefix'] = $embed_prefix;
  3329. $element['#value_suffix'] = $embed_suffix;
  3330. $element['#attributes']['media'] = $group['media'];
  3331. $element['#browsers'] = $group['browsers'];
  3332. $elements[] = $element;
  3333. }
  3334. else {
  3335. foreach ($group['items'] as $item) {
  3336. $element = $style_element_defaults;
  3337. $element['#value'] = $item['data'];
  3338. $element['#value_prefix'] = $embed_prefix;
  3339. $element['#value_suffix'] = $embed_suffix;
  3340. $element['#attributes']['media'] = $item['media'];
  3341. $element['#browsers'] = $group['browsers'];
  3342. $elements[] = $element;
  3343. }
  3344. }
  3345. break;
  3346. // Output a LINK tag for each external item. The item's 'data' property
  3347. // contains the full URL.
  3348. case 'external':
  3349. foreach ($group['items'] as $item) {
  3350. $element = $link_element_defaults;
  3351. $element['#attributes']['href'] = $item['data'];
  3352. $element['#attributes']['media'] = $item['media'];
  3353. $element['#browsers'] = $group['browsers'];
  3354. $elements[] = $element;
  3355. }
  3356. break;
  3357. }
  3358. }
  3359. return $elements;
  3360. }
  3361. /**
  3362. * Aggregates and optimizes CSS files into a cache file in the files directory.
  3363. *
  3364. * The file name for the CSS cache file is generated from the hash of the
  3365. * aggregated contents of the files in $css. This forces proxies and browsers
  3366. * to download new CSS when the CSS changes.
  3367. *
  3368. * The cache file name is retrieved on a page load via a lookup variable that
  3369. * contains an associative array. The array key is the hash of the file names
  3370. * in $css while the value is the cache file name. The cache file is generated
  3371. * in two cases. First, if there is no file name value for the key, which will
  3372. * happen if a new file name has been added to $css or after the lookup
  3373. * variable is emptied to force a rebuild of the cache. Second, the cache file
  3374. * is generated if it is missing on disk. Old cache files are not deleted
  3375. * immediately when the lookup variable is emptied, but are deleted after a set
  3376. * period by drupal_delete_file_if_stale(). This ensures that files referenced
  3377. * by a cached page will still be available.
  3378. *
  3379. * @param $css
  3380. * An array of CSS files to aggregate and compress into one file.
  3381. *
  3382. * @return
  3383. * The URI of the CSS cache file, or FALSE if the file could not be saved.
  3384. */
  3385. function drupal_build_css_cache($css) {
  3386. $data = '';
  3387. $uri = '';
  3388. $map = variable_get('drupal_css_cache_files', array());
  3389. // Create a new array so that only the file names are used to create the hash.
  3390. // This prevents new aggregates from being created unnecessarily.
  3391. $css_data = array();
  3392. foreach ($css as $css_file) {
  3393. $css_data[] = $css_file['data'];
  3394. }
  3395. $key = hash('sha256', serialize($css_data));
  3396. if (isset($map[$key])) {
  3397. $uri = $map[$key];
  3398. }
  3399. if (empty($uri) || !file_exists($uri)) {
  3400. // Build aggregate CSS file.
  3401. foreach ($css as $stylesheet) {
  3402. // Only 'file' stylesheets can be aggregated.
  3403. if ($stylesheet['type'] == 'file') {
  3404. $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
  3405. // Build the base URL of this CSS file: start with the full URL.
  3406. $css_base_url = file_create_url($stylesheet['data']);
  3407. // Move to the parent.
  3408. $css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
  3409. // Simplify to a relative URL if the stylesheet URL starts with the
  3410. // base URL of the website.
  3411. if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
  3412. $css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
  3413. }
  3414. _drupal_build_css_path(NULL, $css_base_url . '/');
  3415. // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
  3416. $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
  3417. }
  3418. }
  3419. // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
  3420. // @import rules must proceed any other style, so we move those to the top.
  3421. $regexp = '/@import[^;]+;/i';
  3422. preg_match_all($regexp, $data, $matches);
  3423. $data = preg_replace($regexp, '', $data);
  3424. $data = implode('', $matches[0]) . $data;
  3425. // Prefix filename to prevent blocking by firewalls which reject files
  3426. // starting with "ad*".
  3427. $filename = 'css_' . drupal_hash_base64($data) . '.css';
  3428. // Create the css/ within the files folder.
  3429. $csspath = 'public://css';
  3430. $uri = $csspath . '/' . $filename;
  3431. // Create the CSS file.
  3432. file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
  3433. if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
  3434. return FALSE;
  3435. }
  3436. // If CSS gzip compression is enabled, clean URLs are enabled (which means
  3437. // that rewrite rules are working) and the zlib extension is available then
  3438. // create a gzipped version of this file. This file is served conditionally
  3439. // to browsers that accept gzip using .htaccess rules.
  3440. if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
  3441. if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
  3442. return FALSE;
  3443. }
  3444. }
  3445. // Save the updated map.
  3446. $map[$key] = $uri;
  3447. variable_set('drupal_css_cache_files', $map);
  3448. }
  3449. return $uri;
  3450. }
  3451. /**
  3452. * Prefixes all paths within a CSS file for drupal_build_css_cache().
  3453. */
  3454. function _drupal_build_css_path($matches, $base = NULL) {
  3455. $_base = &drupal_static(__FUNCTION__);
  3456. // Store base path for preg_replace_callback.
  3457. if (isset($base)) {
  3458. $_base = $base;
  3459. }
  3460. // Prefix with base and remove '../' segments where possible.
  3461. $path = $_base . $matches[1];
  3462. $last = '';
  3463. while ($path != $last) {
  3464. $last = $path;
  3465. $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
  3466. }
  3467. return 'url(' . $path . ')';
  3468. }
  3469. /**
  3470. * Loads the stylesheet and resolves all @import commands.
  3471. *
  3472. * Loads a stylesheet and replaces @import commands with the contents of the
  3473. * imported file. Use this instead of file_get_contents when processing
  3474. * stylesheets.
  3475. *
  3476. * The returned contents are compressed removing white space and comments only
  3477. * when CSS aggregation is enabled. This optimization will not apply for
  3478. * color.module enabled themes with CSS aggregation turned off.
  3479. *
  3480. * @param $file
  3481. * Name of the stylesheet to be processed.
  3482. * @param $optimize
  3483. * Defines if CSS contents should be compressed or not.
  3484. * @param $reset_basepath
  3485. * Used internally to facilitate recursive resolution of @import commands.
  3486. *
  3487. * @return
  3488. * Contents of the stylesheet, including any resolved @import commands.
  3489. */
  3490. function drupal_load_stylesheet($file, $optimize = NULL, $reset_basepath = TRUE) {
  3491. // These statics are not cache variables, so we don't use drupal_static().
  3492. static $_optimize, $basepath;
  3493. if ($reset_basepath) {
  3494. $basepath = '';
  3495. }
  3496. // Store the value of $optimize for preg_replace_callback with nested
  3497. // @import loops.
  3498. if (isset($optimize)) {
  3499. $_optimize = $optimize;
  3500. }
  3501. // Stylesheets are relative one to each other. Start by adding a base path
  3502. // prefix provided by the parent stylesheet (if necessary).
  3503. if ($basepath && !file_uri_scheme($file)) {
  3504. $file = $basepath . '/' . $file;
  3505. }
  3506. // Store the parent base path to restore it later.
  3507. $parent_base_path = $basepath;
  3508. // Set the current base path to process possible child imports.
  3509. $basepath = dirname($file);
  3510. // Load the CSS stylesheet. We suppress errors because themes may specify
  3511. // stylesheets in their .info file that don't exist in the theme's path,
  3512. // but are merely there to disable certain module CSS files.
  3513. $content = '';
  3514. if ($contents = @file_get_contents($file)) {
  3515. // Return the processed stylesheet.
  3516. $content = drupal_load_stylesheet_content($contents, $_optimize);
  3517. }
  3518. // Restore the parent base path as the file and its childen are processed.
  3519. $basepath = $parent_base_path;
  3520. return $content;
  3521. }
  3522. /**
  3523. * Processes the contents of a stylesheet for aggregation.
  3524. *
  3525. * @param $contents
  3526. * The contents of the stylesheet.
  3527. * @param $optimize
  3528. * (optional) Boolean whether CSS contents should be minified. Defaults to
  3529. * FALSE.
  3530. *
  3531. * @return
  3532. * Contents of the stylesheet including the imported stylesheets.
  3533. */
  3534. function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
  3535. // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
  3536. $contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
  3537. if ($optimize) {
  3538. // Perform some safe CSS optimizations.
  3539. // Regexp to match comment blocks.
  3540. $comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
  3541. // Regexp to match double quoted strings.
  3542. $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
  3543. // Regexp to match single quoted strings.
  3544. $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
  3545. // Strip all comment blocks, but keep double/single quoted strings.
  3546. $contents = preg_replace(
  3547. "<($double_quot|$single_quot)|$comment>Ss",
  3548. "$1",
  3549. $contents
  3550. );
  3551. // Remove certain whitespace.
  3552. // There are different conditions for removing leading and trailing
  3553. // whitespace.
  3554. // @see http://php.net/manual/regexp.reference.subpatterns.php
  3555. $contents = preg_replace('<
  3556. # Strip leading and trailing whitespace.
  3557. \s*([@{};,])\s*
  3558. # Strip only leading whitespace from:
  3559. # - Closing parenthesis: Retain "@media (bar) and foo".
  3560. | \s+([\)])
  3561. # Strip only trailing whitespace from:
  3562. # - Opening parenthesis: Retain "@media (bar) and foo".
  3563. # - Colon: Retain :pseudo-selectors.
  3564. | ([\(:])\s+
  3565. >xS',
  3566. // Only one of the three capturing groups will match, so its reference
  3567. // will contain the wanted value and the references for the
  3568. // two non-matching groups will be replaced with empty strings.
  3569. '$1$2$3',
  3570. $contents
  3571. );
  3572. // End the file with a new line.
  3573. $contents = trim($contents);
  3574. $contents .= "\n";
  3575. }
  3576. // Replaces @import commands with the actual stylesheet content.
  3577. // This happens recursively but omits external files.
  3578. $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)(?!\/\/)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
  3579. return $contents;
  3580. }
  3581. /**
  3582. * Loads stylesheets recursively and returns contents with corrected paths.
  3583. *
  3584. * This function is used for recursive loading of stylesheets and
  3585. * returns the stylesheet content with all url() paths corrected.
  3586. */
  3587. function _drupal_load_stylesheet($matches) {
  3588. $filename = $matches[1];
  3589. // Load the imported stylesheet and replace @import commands in there as well.
  3590. $file = drupal_load_stylesheet($filename, NULL, FALSE);
  3591. // Determine the file's directory.
  3592. $directory = dirname($filename);
  3593. // If the file is in the current directory, make sure '.' doesn't appear in
  3594. // the url() path.
  3595. $directory = $directory == '.' ? '' : $directory .'/';
  3596. // Alter all internal url() paths. Leave external paths alone. We don't need
  3597. // to normalize absolute paths here (i.e. remove folder/... segments) because
  3598. // that will be done later.
  3599. return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)([^\'")]+)([\'"]?)\s*\)/i', 'url(\1' . $directory . '\2\3)', $file);
  3600. }
  3601. /**
  3602. * Deletes old cached CSS files.
  3603. */
  3604. function drupal_clear_css_cache() {
  3605. variable_del('drupal_css_cache_files');
  3606. file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
  3607. }
  3608. /**
  3609. * Callback to delete files modified more than a set time ago.
  3610. */
  3611. function drupal_delete_file_if_stale($uri) {
  3612. // Default stale file threshold is 30 days.
  3613. if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
  3614. file_unmanaged_delete($uri);
  3615. }
  3616. }
  3617. /**
  3618. * Prepares a string for use as a CSS identifier (element, class, or ID name).
  3619. *
  3620. * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
  3621. * CSS identifiers (including element names, classes, and IDs in selectors.)
  3622. *
  3623. * @param $identifier
  3624. * The identifier to clean.
  3625. * @param $filter
  3626. * An array of string replacements to use on the identifier.
  3627. *
  3628. * @return
  3629. * The cleaned identifier.
  3630. */
  3631. function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
  3632. // Use the advanced drupal_static() pattern, since this is called very often.
  3633. static $drupal_static_fast;
  3634. if (!isset($drupal_static_fast)) {
  3635. $drupal_static_fast['allow_css_double_underscores'] = &drupal_static(__FUNCTION__ . ':allow_css_double_underscores');
  3636. }
  3637. $allow_css_double_underscores = &$drupal_static_fast['allow_css_double_underscores'];
  3638. if (!isset($allow_css_double_underscores)) {
  3639. $allow_css_double_underscores = variable_get('allow_css_double_underscores', FALSE);
  3640. }
  3641. // Preserve BEM-style double-underscores depending on custom setting.
  3642. if ($allow_css_double_underscores) {
  3643. $filter['__'] = '__';
  3644. }
  3645. // By default, we filter using Drupal's coding standards.
  3646. $identifier = strtr($identifier, $filter);
  3647. // Valid characters in a CSS identifier are:
  3648. // - the hyphen (U+002D)
  3649. // - a-z (U+0030 - U+0039)
  3650. // - A-Z (U+0041 - U+005A)
  3651. // - the underscore (U+005F)
  3652. // - 0-9 (U+0061 - U+007A)
  3653. // - ISO 10646 characters U+00A1 and higher
  3654. // We strip out any character not in the above list.
  3655. $identifier = preg_replace('/[^\x{002D}\x{0030}-\x{0039}\x{0041}-\x{005A}\x{005F}\x{0061}-\x{007A}\x{00A1}-\x{FFFF}]/u', '', $identifier);
  3656. return $identifier;
  3657. }
  3658. /**
  3659. * Prepares a string for use as a valid class name.
  3660. *
  3661. * Do not pass one string containing multiple classes as they will be
  3662. * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
  3663. *
  3664. * @param $class
  3665. * The class name to clean.
  3666. *
  3667. * @return
  3668. * The cleaned class name.
  3669. */
  3670. function drupal_html_class($class) {
  3671. // The output of this function will never change, so this uses a normal
  3672. // static instead of drupal_static().
  3673. static $classes = array();
  3674. if (!isset($classes[$class])) {
  3675. $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
  3676. }
  3677. return $classes[$class];
  3678. }
  3679. /**
  3680. * Prepares a string for use as a valid HTML ID and guarantees uniqueness.
  3681. *
  3682. * This function ensures that each passed HTML ID value only exists once on the
  3683. * page. By tracking the already returned ids, this function enables forms,
  3684. * blocks, and other content to be output multiple times on the same page,
  3685. * without breaking (X)HTML validation.
  3686. *
  3687. * For already existing IDs, a counter is appended to the ID string. Therefore,
  3688. * JavaScript and CSS code should not rely on any value that was generated by
  3689. * this function and instead should rely on manually added CSS classes or
  3690. * similarly reliable constructs.
  3691. *
  3692. * Two consecutive hyphens separate the counter from the original ID. To manage
  3693. * uniqueness across multiple Ajax requests on the same page, Ajax requests
  3694. * POST an array of all IDs currently present on the page, which are used to
  3695. * prime this function's cache upon first invocation.
  3696. *
  3697. * To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive
  3698. * hyphens in the originally passed $id are replaced with a single hyphen.
  3699. *
  3700. * @param $id
  3701. * The ID to clean.
  3702. *
  3703. * @return
  3704. * The cleaned ID.
  3705. */
  3706. function drupal_html_id($id) {
  3707. // If this is an Ajax request, then content returned by this page request will
  3708. // be merged with content already on the base page. The HTML IDs must be
  3709. // unique for the fully merged content. Therefore, initialize $seen_ids to
  3710. // take into account IDs that are already in use on the base page.
  3711. static $drupal_static_fast;
  3712. if (!isset($drupal_static_fast['seen_ids_init'])) {
  3713. $drupal_static_fast['seen_ids_init'] = &drupal_static(__FUNCTION__ . ':init');
  3714. }
  3715. $seen_ids_init = &$drupal_static_fast['seen_ids_init'];
  3716. if (!isset($seen_ids_init)) {
  3717. // Ideally, Drupal would provide an API to persist state information about
  3718. // prior page requests in the database, and we'd be able to add this
  3719. // function's $seen_ids static variable to that state information in order
  3720. // to have it properly initialized for this page request. However, no such
  3721. // page state API exists, so instead, ajax.js adds all of the in-use HTML
  3722. // IDs to the POST data of Ajax submissions. Direct use of $_POST is
  3723. // normally not recommended as it could open up security risks, but because
  3724. // the raw POST data is cast to a number before being returned by this
  3725. // function, this usage is safe.
  3726. if (empty($_POST['ajax_html_ids'])) {
  3727. $seen_ids_init = array();
  3728. }
  3729. else {
  3730. // This function ensures uniqueness by appending a counter to the base id
  3731. // requested by the calling function after the first occurrence of that
  3732. // requested id. $_POST['ajax_html_ids'] contains the ids as they were
  3733. // returned by this function, potentially with the appended counter, so
  3734. // we parse that to reconstruct the $seen_ids array.
  3735. if (isset($_POST['ajax_html_ids'][0]) && strpos($_POST['ajax_html_ids'][0], ',') === FALSE) {
  3736. $ajax_html_ids = $_POST['ajax_html_ids'];
  3737. }
  3738. else {
  3739. // jquery.form.js may send the server a comma-separated string as the
  3740. // first element of an array (see http://drupal.org/node/1575060), so
  3741. // we need to convert it to an array in that case.
  3742. $ajax_html_ids = explode(',', $_POST['ajax_html_ids'][0]);
  3743. }
  3744. foreach ($ajax_html_ids as $seen_id) {
  3745. // We rely on '--' being used solely for separating a base id from the
  3746. // counter, which this function ensures when returning an id.
  3747. $parts = explode('--', $seen_id, 2);
  3748. if (!empty($parts[1]) && is_numeric($parts[1])) {
  3749. list($seen_id, $i) = $parts;
  3750. }
  3751. else {
  3752. $i = 1;
  3753. }
  3754. if (!isset($seen_ids_init[$seen_id]) || ($i > $seen_ids_init[$seen_id])) {
  3755. $seen_ids_init[$seen_id] = $i;
  3756. }
  3757. }
  3758. }
  3759. }
  3760. if (!isset($drupal_static_fast['seen_ids'])) {
  3761. $drupal_static_fast['seen_ids'] = &drupal_static(__FUNCTION__, $seen_ids_init);
  3762. }
  3763. $seen_ids = &$drupal_static_fast['seen_ids'];
  3764. $id = strtr(drupal_strtolower($id), array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  3765. // As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
  3766. // only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
  3767. // colons (":"), and periods ("."). We strip out any character not in that
  3768. // list. Note that the CSS spec doesn't allow colons or periods in identifiers
  3769. // (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
  3770. // characters as well.
  3771. $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
  3772. // Removing multiple consecutive hyphens.
  3773. $id = preg_replace('/\-+/', '-', $id);
  3774. // Ensure IDs are unique by appending a counter after the first occurrence.
  3775. // The counter needs to be appended with a delimiter that does not exist in
  3776. // the base ID. Requiring a unique delimiter helps ensure that we really do
  3777. // return unique IDs and also helps us re-create the $seen_ids array during
  3778. // Ajax requests.
  3779. if (isset($seen_ids[$id])) {
  3780. $id = $id . '--' . ++$seen_ids[$id];
  3781. }
  3782. else {
  3783. $seen_ids[$id] = 1;
  3784. }
  3785. return $id;
  3786. }
  3787. /**
  3788. * Provides a standard HTML class name that identifies a page region.
  3789. *
  3790. * It is recommended that template preprocess functions apply this class to any
  3791. * page region that is output by the theme (Drupal core already handles this in
  3792. * the standard template preprocess implementation). Standardizing the class
  3793. * names in this way allows modules to implement certain features, such as
  3794. * drag-and-drop or dynamic Ajax loading, in a theme-independent way.
  3795. *
  3796. * @param $region
  3797. * The name of the page region (for example, 'page_top' or 'content').
  3798. *
  3799. * @return
  3800. * An HTML class that identifies the region (for example, 'region-page-top'
  3801. * or 'region-content').
  3802. *
  3803. * @see template_preprocess_region()
  3804. */
  3805. function drupal_region_class($region) {
  3806. return drupal_html_class("region-$region");
  3807. }
  3808. /**
  3809. * Adds a JavaScript file, setting, or inline code to the page.
  3810. *
  3811. * The behavior of this function depends on the parameters it is called with.
  3812. * Generally, it handles the addition of JavaScript to the page, either as
  3813. * reference to an existing file or as inline code. The following actions can be
  3814. * performed using this function:
  3815. * - Add a file ('file'): Adds a reference to a JavaScript file to the page.
  3816. * - Add inline JavaScript code ('inline'): Executes a piece of JavaScript code
  3817. * on the current page by placing the code directly in the page (for example,
  3818. * to tell the user that a new message arrived, by opening a pop up, alert
  3819. * box, etc.). This should only be used for JavaScript that cannot be executed
  3820. * from a file. When adding inline code, make sure that you are not relying on
  3821. * $() being the jQuery function. Wrap your code in
  3822. * @code (function ($) {... })(jQuery); @endcode
  3823. * or use jQuery() instead of $().
  3824. * - Add external JavaScript ('external'): Allows the inclusion of external
  3825. * JavaScript files that are not hosted on the local server. Note that these
  3826. * external JavaScript references do not get aggregated when preprocessing is
  3827. * on.
  3828. * - Add settings ('setting'): Adds settings to Drupal's global storage of
  3829. * JavaScript settings. Per-page settings are required by some modules to
  3830. * function properly. All settings will be accessible at Drupal.settings.
  3831. *
  3832. * Examples:
  3833. * @code
  3834. * drupal_add_js('misc/collapse.js');
  3835. * drupal_add_js('misc/collapse.js', 'file');
  3836. * drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  3837. * drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
  3838. * array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  3839. * );
  3840. * drupal_add_js('http://example.com/example.js', 'external');
  3841. * drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
  3842. * @endcode
  3843. *
  3844. * Calling drupal_static_reset('drupal_add_js') will clear all JavaScript added
  3845. * so far.
  3846. *
  3847. * If JavaScript aggregation is enabled, all JavaScript files added with
  3848. * $options['preprocess'] set to TRUE will be merged into one aggregate file.
  3849. * Preprocessed inline JavaScript will not be aggregated into this single file.
  3850. * Externally hosted JavaScripts are never aggregated.
  3851. *
  3852. * The reason for aggregating the files is outlined quite thoroughly here:
  3853. * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
  3854. * to request overhead, one bigger file just loads faster than two smaller ones
  3855. * half its size."
  3856. *
  3857. * $options['preprocess'] should be only set to TRUE when a file is required for
  3858. * all typical visitors and most pages of a site. It is critical that all
  3859. * preprocessed files are added unconditionally on every page, even if the
  3860. * files are not needed on a page. This is normally done by calling
  3861. * drupal_add_js() in a hook_init() implementation.
  3862. *
  3863. * Non-preprocessed files should only be added to the page when they are
  3864. * actually needed.
  3865. *
  3866. * @param $data
  3867. * (optional) If given, the value depends on the $options parameter, or
  3868. * $options['type'] if $options is passed as an associative array:
  3869. * - 'file': Path to the file relative to base_path().
  3870. * - 'inline': The JavaScript code that should be placed in the given scope.
  3871. * - 'external': The absolute path to an external JavaScript file that is not
  3872. * hosted on the local server. These files will not be aggregated if
  3873. * JavaScript aggregation is enabled.
  3874. * - 'setting': An associative array with configuration options. The array is
  3875. * merged directly into Drupal.settings. All modules should wrap their
  3876. * actual configuration settings in another variable to prevent conflicts in
  3877. * the Drupal.settings namespace. Items added with a string key will replace
  3878. * existing settings with that key; items with numeric array keys will be
  3879. * added to the existing settings array.
  3880. * @param $options
  3881. * (optional) A string defining the type of JavaScript that is being added in
  3882. * the $data parameter ('file'/'setting'/'inline'/'external'), or an
  3883. * associative array. JavaScript settings should always pass the string
  3884. * 'setting' only. Other types can have the following elements in the array:
  3885. * - type: The type of JavaScript that is to be added to the page. Allowed
  3886. * values are 'file', 'inline', 'external' or 'setting'. Defaults
  3887. * to 'file'.
  3888. * - scope: The location in which you want to place the script. Possible
  3889. * values are 'header' or 'footer'. If your theme implements different
  3890. * regions, you can also use these. Defaults to 'header'.
  3891. * - group: A number identifying the group in which to add the JavaScript.
  3892. * Available constants are:
  3893. * - JS_LIBRARY: Any libraries, settings, or jQuery plugins.
  3894. * - JS_DEFAULT: Any module-layer JavaScript.
  3895. * - JS_THEME: Any theme-layer JavaScript.
  3896. * The group number serves as a weight: JavaScript within a lower weight
  3897. * group is presented on the page before JavaScript within a higher weight
  3898. * group.
  3899. * - every_page: For optimal front-end performance when aggregation is
  3900. * enabled, this should be set to TRUE if the JavaScript is present on every
  3901. * page of the website for users for whom it is present at all. This
  3902. * defaults to FALSE. It is set to TRUE for JavaScript files that are added
  3903. * via module and theme .info files. Modules that add JavaScript within
  3904. * hook_init() implementations, or from other code that ensures that the
  3905. * JavaScript is added to all website pages, should also set this flag to
  3906. * TRUE. All JavaScript files within the same group and that have the
  3907. * 'every_page' flag set to TRUE and do not have 'preprocess' set to FALSE
  3908. * are aggregated together into a single aggregate file, and that aggregate
  3909. * file can be reused across a user's entire site visit, leading to faster
  3910. * navigation between pages. However, JavaScript that is only needed on
  3911. * pages less frequently visited, can be added by code that only runs for
  3912. * those particular pages, and that code should not set the 'every_page'
  3913. * flag. This minimizes the size of the aggregate file that the user needs
  3914. * to download when first visiting the website. JavaScript without the
  3915. * 'every_page' flag is aggregated into a separate aggregate file. This
  3916. * other aggregate file is likely to change from page to page, and each new
  3917. * aggregate file needs to be downloaded when first encountered, so it
  3918. * should be kept relatively small by ensuring that most commonly needed
  3919. * JavaScript is added to every page.
  3920. * - weight: A number defining the order in which the JavaScript is added to
  3921. * the page relative to other JavaScript with the same 'scope', 'group',
  3922. * and 'every_page' value. In some cases, the order in which the JavaScript
  3923. * is presented on the page is very important. jQuery, for example, must be
  3924. * added to the page before any jQuery code is run, so jquery.js uses the
  3925. * JS_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js
  3926. * depends on) uses the JS_LIBRARY group and a weight of -19, drupal.js uses
  3927. * the JS_LIBRARY group and a weight of -1, other libraries use the
  3928. * JS_LIBRARY group and a weight of 0 or higher, and all other scripts use
  3929. * one of the other group constants. The exact ordering of JavaScript is as
  3930. * follows:
  3931. * - First by scope, with 'header' first, 'footer' last, and any other
  3932. * scopes provided by a custom theme coming in between, as determined by
  3933. * the theme.
  3934. * - Then by group.
  3935. * - Then by the 'every_page' flag, with TRUE coming before FALSE.
  3936. * - Then by weight.
  3937. * - Then by the order in which the JavaScript was added. For example, all
  3938. * else being the same, JavaScript added by a call to drupal_add_js() that
  3939. * happened later in the page request gets added to the page after one for
  3940. * which drupal_add_js() happened earlier in the page request.
  3941. * - requires_jquery: Set this to FALSE if the JavaScript you are adding does
  3942. * not have a dependency on jQuery. Defaults to TRUE, except for JavaScript
  3943. * settings where it defaults to FALSE. This is used on sites that have the
  3944. * 'javascript_always_use_jquery' variable set to FALSE; on those sites, if
  3945. * all the JavaScript added to the page by drupal_add_js() does not have a
  3946. * dependency on jQuery, then for improved front-end performance Drupal
  3947. * will not add jQuery and related libraries and settings to the page.
  3948. * - defer: If set to TRUE, the defer attribute is set on the <script>
  3949. * tag. Defaults to FALSE.
  3950. * - cache: If set to FALSE, the JavaScript file is loaded anew on every page
  3951. * call; in other words, it is not cached. Used only when 'type' references
  3952. * a JavaScript file. Defaults to TRUE.
  3953. * - preprocess: If TRUE and JavaScript aggregation is enabled, the script
  3954. * file will be aggregated. Defaults to TRUE.
  3955. *
  3956. * @return
  3957. * The current array of JavaScript files, settings, and in-line code,
  3958. * including Drupal defaults, anything previously added with calls to
  3959. * drupal_add_js(), and this function call's additions.
  3960. *
  3961. * @see drupal_get_js()
  3962. */
  3963. function drupal_add_js($data = NULL, $options = NULL) {
  3964. $javascript = &drupal_static(__FUNCTION__, array());
  3965. $jquery_added = &drupal_static(__FUNCTION__ . ':jquery_added', FALSE);
  3966. // If the $javascript variable has been reset with drupal_static_reset(),
  3967. // jQuery and related files will have been removed from the list, so set the
  3968. // variable back to FALSE to indicate they have not yet been added.
  3969. if (empty($javascript)) {
  3970. $jquery_added = FALSE;
  3971. }
  3972. // Construct the options, taking the defaults into consideration.
  3973. if (isset($options)) {
  3974. if (!is_array($options)) {
  3975. $options = array('type' => $options);
  3976. }
  3977. }
  3978. else {
  3979. $options = array();
  3980. }
  3981. if (isset($options['type']) && $options['type'] == 'setting') {
  3982. $options += array('requires_jquery' => FALSE);
  3983. }
  3984. $options += drupal_js_defaults($data);
  3985. // Preprocess can only be set if caching is enabled.
  3986. $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
  3987. // Tweak the weight so that files of the same weight are included in the
  3988. // order of the calls to drupal_add_js().
  3989. $options['weight'] += count($javascript) / 1000;
  3990. if (isset($data)) {
  3991. // Add jquery.js, drupal.js, and related files and settings if they have
  3992. // not been added yet. However, if the 'javascript_always_use_jquery'
  3993. // variable is set to FALSE (indicating that the site does not want jQuery
  3994. // automatically added on all pages) then only add it if a file or setting
  3995. // that requires jQuery is being added also.
  3996. if (!$jquery_added && (variable_get('javascript_always_use_jquery', TRUE) || $options['requires_jquery'])) {
  3997. $jquery_added = TRUE;
  3998. // url() generates the prefix using hook_url_outbound_alter(). Instead of
  3999. // running the hook_url_outbound_alter() again here, extract the prefix
  4000. // from url().
  4001. url('', array('prefix' => &$prefix));
  4002. $default_javascript = array(
  4003. 'settings' => array(
  4004. 'data' => array(
  4005. array('basePath' => base_path()),
  4006. array('pathPrefix' => empty($prefix) ? '' : $prefix),
  4007. ),
  4008. 'type' => 'setting',
  4009. 'scope' => 'header',
  4010. 'group' => JS_LIBRARY,
  4011. 'every_page' => TRUE,
  4012. 'weight' => 0,
  4013. ),
  4014. 'misc/drupal.js' => array(
  4015. 'data' => 'misc/drupal.js',
  4016. 'type' => 'file',
  4017. 'scope' => 'header',
  4018. 'group' => JS_LIBRARY,
  4019. 'every_page' => TRUE,
  4020. 'weight' => -1,
  4021. 'requires_jquery' => TRUE,
  4022. 'preprocess' => TRUE,
  4023. 'cache' => TRUE,
  4024. 'defer' => FALSE,
  4025. ),
  4026. );
  4027. $javascript = drupal_array_merge_deep($javascript, $default_javascript);
  4028. // Register all required libraries.
  4029. drupal_add_library('system', 'jquery', TRUE);
  4030. drupal_add_library('system', 'jquery.once', TRUE);
  4031. }
  4032. switch ($options['type']) {
  4033. case 'setting':
  4034. // All JavaScript settings are placed in the header of the page with
  4035. // the library weight so that inline scripts appear afterwards.
  4036. $javascript['settings']['data'][] = $data;
  4037. break;
  4038. case 'inline':
  4039. $javascript[] = $options;
  4040. break;
  4041. default: // 'file' and 'external'
  4042. // Local and external files must keep their name as the associative key
  4043. // so the same JavaScript file is not added twice.
  4044. $javascript[$options['data']] = $options;
  4045. }
  4046. }
  4047. return $javascript;
  4048. }
  4049. /**
  4050. * Constructs an array of the defaults that are used for JavaScript items.
  4051. *
  4052. * @param $data
  4053. * (optional) The default data parameter for the JavaScript item array.
  4054. *
  4055. * @see drupal_get_js()
  4056. * @see drupal_add_js()
  4057. */
  4058. function drupal_js_defaults($data = NULL) {
  4059. return array(
  4060. 'type' => 'file',
  4061. 'group' => JS_DEFAULT,
  4062. 'every_page' => FALSE,
  4063. 'weight' => 0,
  4064. 'requires_jquery' => TRUE,
  4065. 'scope' => 'header',
  4066. 'cache' => TRUE,
  4067. 'defer' => FALSE,
  4068. 'preprocess' => TRUE,
  4069. 'version' => NULL,
  4070. 'data' => $data,
  4071. );
  4072. }
  4073. /**
  4074. * Returns a themed presentation of all JavaScript code for the current page.
  4075. *
  4076. * References to JavaScript files are placed in a certain order: first, all
  4077. * 'core' files, then all 'module' and finally all 'theme' JavaScript files
  4078. * are added to the page. Then, all settings are output, followed by 'inline'
  4079. * JavaScript code. If running update.php, all preprocessing is disabled.
  4080. *
  4081. * Note that hook_js_alter(&$javascript) is called during this function call
  4082. * to allow alterations of the JavaScript during its presentation. Calls to
  4083. * drupal_add_js() from hook_js_alter() will not be added to the output
  4084. * presentation. The correct way to add JavaScript during hook_js_alter()
  4085. * is to add another element to the $javascript array, deriving from
  4086. * drupal_js_defaults(). See locale_js_alter() for an example of this.
  4087. *
  4088. * @param $scope
  4089. * (optional) The scope for which the JavaScript rules should be returned.
  4090. * Defaults to 'header'.
  4091. * @param $javascript
  4092. * (optional) An array with all JavaScript code. Defaults to the default
  4093. * JavaScript array for the given scope.
  4094. * @param $skip_alter
  4095. * (optional) If set to TRUE, this function skips calling drupal_alter() on
  4096. * $javascript, useful when the calling function passes a $javascript array
  4097. * that has already been altered.
  4098. *
  4099. * @return
  4100. * All JavaScript code segments and includes for the scope as HTML tags.
  4101. *
  4102. * @see drupal_add_js()
  4103. * @see locale_js_alter()
  4104. * @see drupal_js_defaults()
  4105. */
  4106. function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
  4107. if (!isset($javascript)) {
  4108. $javascript = drupal_add_js();
  4109. }
  4110. // If no JavaScript items have been added, or if the only JavaScript items
  4111. // that have been added are JavaScript settings (which don't do anything
  4112. // without any JavaScript code to use them), then no JavaScript code should
  4113. // be added to the page.
  4114. if (empty($javascript) || (isset($javascript['settings']) && count($javascript) == 1)) {
  4115. return '';
  4116. }
  4117. // Allow modules to alter the JavaScript.
  4118. if (!$skip_alter) {
  4119. drupal_alter('js', $javascript);
  4120. }
  4121. // Filter out elements of the given scope.
  4122. $items = array();
  4123. foreach ($javascript as $key => $item) {
  4124. if ($item['scope'] == $scope) {
  4125. $items[$key] = $item;
  4126. }
  4127. }
  4128. // Sort the JavaScript so that it appears in the correct order.
  4129. uasort($items, 'drupal_sort_css_js');
  4130. // Provide the page with information about the individual JavaScript files
  4131. // used, information not otherwise available when aggregation is enabled.
  4132. $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
  4133. unset($setting['ajaxPageState']['js']['settings']);
  4134. drupal_add_js($setting, 'setting');
  4135. // If we're outputting the header scope, then this might be the final time
  4136. // that drupal_get_js() is running, so add the setting to this output as well
  4137. // as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
  4138. // because drupal_get_js() was intentionally passed a $javascript argument
  4139. // stripped off settings, potentially in order to override how settings get
  4140. // output, so in this case, do not add the setting to this output.
  4141. if ($scope == 'header' && isset($items['settings'])) {
  4142. $items['settings']['data'][] = $setting;
  4143. }
  4144. $elements = array(
  4145. '#type' => 'scripts',
  4146. '#items' => $items,
  4147. );
  4148. return drupal_render($elements);
  4149. }
  4150. /**
  4151. * The #pre_render callback for the "scripts" element.
  4152. *
  4153. * This callback adds elements needed for <script> tags to be rendered.
  4154. *
  4155. * @param array $elements
  4156. * A render array containing:
  4157. * - '#items': The JS items as returned by drupal_add_js() and altered by
  4158. * drupal_get_js().
  4159. *
  4160. * @return array
  4161. * The $elements variable passed as argument with two more children keys:
  4162. * - "scripts": contains the Javascript items
  4163. * - "settings": contains the Javascript settings items.
  4164. * If those keys are already existing, then the items will be appended and
  4165. * their keys will be preserved.
  4166. *
  4167. * @see drupal_get_js()
  4168. * @see drupal_add_js()
  4169. */
  4170. function drupal_pre_render_scripts(array $elements) {
  4171. $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  4172. // A dummy query-string is added to filenames, to gain control over
  4173. // browser-caching. The string changes on every update or full cache
  4174. // flush, forcing browsers to load a new copy of the files, as the
  4175. // URL changed. Files that should not be cached (see drupal_add_js())
  4176. // get REQUEST_TIME as query-string instead, to enforce reload on every
  4177. // page request.
  4178. $default_query_string = variable_get('css_js_query_string', '0');
  4179. // For inline JavaScript to validate as XHTML, all JavaScript containing
  4180. // XHTML needs to be wrapped in CDATA. To make that backwards compatible
  4181. // with HTML 4, we need to comment out the CDATA-tag.
  4182. $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
  4183. $embed_suffix = "\n//--><!]]>\n";
  4184. // Since JavaScript may look for arguments in the URL and act on them, some
  4185. // third-party code might require the use of a different query string.
  4186. $js_version_string = variable_get('drupal_js_version_query_string', 'v=');
  4187. $files = array();
  4188. $scripts = isset($elements['scripts']) ? $elements['scripts'] : array();
  4189. $scripts += array('#weight' => 0);
  4190. $settings = isset($elements['settings']) ? $elements['settings'] : array();
  4191. $settings += array('#weight' => $scripts['#weight'] + 10);
  4192. // The index counter is used to keep aggregated and non-aggregated files in
  4193. // order by weight. Use existing scripts count as a starting point.
  4194. $index = count(element_children($scripts)) + 1;
  4195. // Loop through the JavaScript to construct the rendered output.
  4196. $element = array(
  4197. '#type' => 'html_tag',
  4198. '#tag' => 'script',
  4199. '#value' => '',
  4200. '#attributes' => array(
  4201. 'type' => 'text/javascript',
  4202. ),
  4203. );
  4204. foreach ($elements['#items'] as $item) {
  4205. $query_string = empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
  4206. switch ($item['type']) {
  4207. case 'setting':
  4208. $js_element = $element;
  4209. $js_element['#value_prefix'] = $embed_prefix;
  4210. $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
  4211. $js_element['#value_suffix'] = $embed_suffix;
  4212. $settings[] = $js_element;
  4213. break;
  4214. case 'inline':
  4215. $js_element = $element;
  4216. if ($item['defer']) {
  4217. $js_element['#attributes']['defer'] = 'defer';
  4218. }
  4219. $js_element['#value_prefix'] = $embed_prefix;
  4220. $js_element['#value'] = $item['data'];
  4221. $js_element['#value_suffix'] = $embed_suffix;
  4222. $scripts[$index++] = $js_element;
  4223. break;
  4224. case 'file':
  4225. $js_element = $element;
  4226. if (!$item['preprocess'] || !$preprocess_js) {
  4227. if ($item['defer']) {
  4228. $js_element['#attributes']['defer'] = 'defer';
  4229. }
  4230. $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
  4231. $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
  4232. $scripts[$index++] = $js_element;
  4233. }
  4234. else {
  4235. // By increasing the index for each aggregated file, we maintain
  4236. // the relative ordering of JS by weight. We also set the key such
  4237. // that groups are split by items sharing the same 'group' value and
  4238. // 'every_page' flag. While this potentially results in more aggregate
  4239. // files, it helps make each one more reusable across a site visit,
  4240. // leading to better front-end performance of a website as a whole.
  4241. // See drupal_add_js() for details.
  4242. $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
  4243. $scripts[$key] = '';
  4244. $files[$key][$item['data']] = $item;
  4245. }
  4246. break;
  4247. case 'external':
  4248. $js_element = $element;
  4249. // Preprocessing for external JavaScript files is ignored.
  4250. if ($item['defer']) {
  4251. $js_element['#attributes']['defer'] = 'defer';
  4252. }
  4253. $js_element['#attributes']['src'] = $item['data'];
  4254. $scripts[$index++] = $js_element;
  4255. break;
  4256. }
  4257. }
  4258. // Aggregate any remaining JS files that haven't already been output.
  4259. if ($preprocess_js && count($files) > 0) {
  4260. foreach ($files as $key => $file_set) {
  4261. $uri = drupal_build_js_cache($file_set);
  4262. // Only include the file if was written successfully. Errors are logged
  4263. // using watchdog.
  4264. if ($uri) {
  4265. $preprocess_file = file_create_url($uri);
  4266. $js_element = $element;
  4267. $js_element['#attributes']['src'] = $preprocess_file;
  4268. $scripts[$key] = $js_element;
  4269. }
  4270. }
  4271. }
  4272. // Keep the order of JS files consistent as some are preprocessed and others
  4273. // are not. Make sure any inline or JS setting variables appear last after
  4274. // libraries have loaded.
  4275. $element['scripts'] = $scripts;
  4276. $element['settings'] = $settings;
  4277. return $element;
  4278. }
  4279. /**
  4280. * Adds attachments to a render() structure.
  4281. *
  4282. * Libraries, JavaScript, CSS and other types of custom structures are attached
  4283. * to elements using the #attached property. The #attached property is an
  4284. * associative array, where the keys are the attachment types and the values are
  4285. * the attached data. For example:
  4286. * @code
  4287. * $build['#attached'] = array(
  4288. * 'js' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.js'),
  4289. * 'css' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.css'),
  4290. * );
  4291. * @endcode
  4292. *
  4293. * 'js', 'css', and 'library' are types that get special handling. For any
  4294. * other kind of attached data, the array key must be the full name of the
  4295. * callback function and each value an array of arguments. For example:
  4296. * @code
  4297. * $build['#attached']['drupal_add_http_header'] = array(
  4298. * array('Content-Type', 'application/rss+xml; charset=utf-8'),
  4299. * );
  4300. * @endcode
  4301. *
  4302. * External 'js' and 'css' files can also be loaded. For example:
  4303. * @code
  4304. * $build['#attached']['js'] = array(
  4305. * 'http://code.jquery.com/jquery-1.4.2.min.js' => array(
  4306. * 'type' => 'external',
  4307. * ),
  4308. * );
  4309. * @endcode
  4310. *
  4311. * @param $elements
  4312. * The structured array describing the data being rendered.
  4313. * @param $group
  4314. * The default group of JavaScript and CSS being added. This is only applied
  4315. * to the stylesheets and JavaScript items that don't have an explicit group
  4316. * assigned to them.
  4317. * @param $dependency_check
  4318. * When TRUE, will exit if a given library's dependencies are missing. When
  4319. * set to FALSE, will continue to add the libraries, even though one or more
  4320. * dependencies are missing. Defaults to FALSE.
  4321. * @param $every_page
  4322. * Set to TRUE to indicate that the attachments are added to every page on the
  4323. * site. Only attachments with the every_page flag set to TRUE can participate
  4324. * in JavaScript/CSS aggregation.
  4325. *
  4326. * @return
  4327. * FALSE if there were any missing library dependencies; TRUE if all library
  4328. * dependencies were met.
  4329. *
  4330. * @see drupal_add_library()
  4331. * @see drupal_add_js()
  4332. * @see drupal_add_css()
  4333. * @see drupal_render()
  4334. */
  4335. function drupal_process_attached($elements, $group = JS_DEFAULT, $dependency_check = FALSE, $every_page = NULL) {
  4336. // Add defaults to the special attached structures that should be processed differently.
  4337. $elements['#attached'] += array(
  4338. 'library' => array(),
  4339. 'js' => array(),
  4340. 'css' => array(),
  4341. );
  4342. // Add the libraries first.
  4343. $success = TRUE;
  4344. foreach ($elements['#attached']['library'] as $library) {
  4345. if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
  4346. $success = FALSE;
  4347. // Exit if the dependency is missing.
  4348. if ($dependency_check) {
  4349. return $success;
  4350. }
  4351. }
  4352. }
  4353. unset($elements['#attached']['library']);
  4354. // Add both the JavaScript and the CSS.
  4355. // The parameters for drupal_add_js() and drupal_add_css() require special
  4356. // handling.
  4357. foreach (array('js', 'css') as $type) {
  4358. foreach ($elements['#attached'][$type] as $data => $options) {
  4359. // If the value is not an array, it's a filename and passed as first
  4360. // (and only) argument.
  4361. if (!is_array($options)) {
  4362. $data = $options;
  4363. $options = NULL;
  4364. }
  4365. // In some cases, the first parameter ($data) is an array. Arrays can't be
  4366. // passed as keys in PHP, so we have to get $data from the value array.
  4367. if (is_numeric($data)) {
  4368. $data = $options['data'];
  4369. unset($options['data']);
  4370. }
  4371. // Apply the default group if it isn't explicitly given.
  4372. if (!isset($options['group'])) {
  4373. $options['group'] = $group;
  4374. }
  4375. // Set the every_page flag if one was passed.
  4376. if (isset($every_page)) {
  4377. $options['every_page'] = $every_page;
  4378. }
  4379. call_user_func('drupal_add_' . $type, $data, $options);
  4380. }
  4381. unset($elements['#attached'][$type]);
  4382. }
  4383. // Add additional types of attachments specified in the render() structure.
  4384. // Libraries, JavaScript and CSS have been added already, as they require
  4385. // special handling.
  4386. foreach ($elements['#attached'] as $callback => $options) {
  4387. if (function_exists($callback)) {
  4388. foreach ($elements['#attached'][$callback] as $args) {
  4389. call_user_func_array($callback, $args);
  4390. }
  4391. }
  4392. }
  4393. return $success;
  4394. }
  4395. /**
  4396. * Adds JavaScript to change the state of an element based on another element.
  4397. *
  4398. * A "state" means a certain property on a DOM element, such as "visible" or
  4399. * "checked". A state can be applied to an element, depending on the state of
  4400. * another element on the page. In general, states depend on HTML attributes and
  4401. * DOM element properties, which change due to user interaction.
  4402. *
  4403. * Since states are driven by JavaScript only, it is important to understand
  4404. * that all states are applied on presentation only, none of the states force
  4405. * any server-side logic, and that they will not be applied for site visitors
  4406. * without JavaScript support. All modules implementing states have to make
  4407. * sure that the intended logic also works without JavaScript being enabled.
  4408. *
  4409. * #states is an associative array in the form of:
  4410. * @code
  4411. * array(
  4412. * STATE1 => CONDITIONS_ARRAY1,
  4413. * STATE2 => CONDITIONS_ARRAY2,
  4414. * ...
  4415. * )
  4416. * @endcode
  4417. * Each key is the name of a state to apply to the element, such as 'visible'.
  4418. * Each value is a list of conditions that denote when the state should be
  4419. * applied.
  4420. *
  4421. * Multiple different states may be specified to act on complex conditions:
  4422. * @code
  4423. * array(
  4424. * 'visible' => CONDITIONS,
  4425. * 'checked' => OTHER_CONDITIONS,
  4426. * )
  4427. * @endcode
  4428. *
  4429. * Every condition is a key/value pair, whose key is a jQuery selector that
  4430. * denotes another element on the page, and whose value is an array of
  4431. * conditions, which must bet met on that element:
  4432. * @code
  4433. * array(
  4434. * 'visible' => array(
  4435. * JQUERY_SELECTOR => REMOTE_CONDITIONS,
  4436. * JQUERY_SELECTOR => REMOTE_CONDITIONS,
  4437. * ...
  4438. * ),
  4439. * )
  4440. * @endcode
  4441. * All conditions must be met for the state to be applied.
  4442. *
  4443. * Each remote condition is a key/value pair specifying conditions on the other
  4444. * element that need to be met to apply the state to the element:
  4445. * @code
  4446. * array(
  4447. * 'visible' => array(
  4448. * ':input[name="remote_checkbox"]' => array('checked' => TRUE),
  4449. * ),
  4450. * )
  4451. * @endcode
  4452. *
  4453. * For example, to show a textfield only when a checkbox is checked:
  4454. * @code
  4455. * $form['toggle_me'] = array(
  4456. * '#type' => 'checkbox',
  4457. * '#title' => t('Tick this box to type'),
  4458. * );
  4459. * $form['settings'] = array(
  4460. * '#type' => 'textfield',
  4461. * '#states' => array(
  4462. * // Only show this field when the 'toggle_me' checkbox is enabled.
  4463. * 'visible' => array(
  4464. * ':input[name="toggle_me"]' => array('checked' => TRUE),
  4465. * ),
  4466. * ),
  4467. * );
  4468. * @endcode
  4469. *
  4470. * The following states may be applied to an element:
  4471. * - enabled
  4472. * - disabled
  4473. * - required
  4474. * - optional
  4475. * - visible
  4476. * - invisible
  4477. * - checked
  4478. * - unchecked
  4479. * - expanded
  4480. * - collapsed
  4481. *
  4482. * The following states may be used in remote conditions:
  4483. * - empty
  4484. * - filled
  4485. * - checked
  4486. * - unchecked
  4487. * - expanded
  4488. * - collapsed
  4489. * - value
  4490. *
  4491. * The following states exist for both elements and remote conditions, but are
  4492. * not fully implemented and may not change anything on the element:
  4493. * - relevant
  4494. * - irrelevant
  4495. * - valid
  4496. * - invalid
  4497. * - touched
  4498. * - untouched
  4499. * - readwrite
  4500. * - readonly
  4501. *
  4502. * When referencing select lists and radio buttons in remote conditions, a
  4503. * 'value' condition must be used:
  4504. * @code
  4505. * '#states' => array(
  4506. * // Show the settings if 'bar' has been selected for 'foo'.
  4507. * 'visible' => array(
  4508. * ':input[name="foo"]' => array('value' => 'bar'),
  4509. * ),
  4510. * ),
  4511. * @endcode
  4512. *
  4513. * @param $elements
  4514. * A renderable array element having a #states property as described above.
  4515. *
  4516. * @see form_example_states_form()
  4517. */
  4518. function drupal_process_states(&$elements) {
  4519. $elements['#attached']['library'][] = array('system', 'drupal.states');
  4520. $elements['#attached']['js'][] = array(
  4521. 'type' => 'setting',
  4522. 'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
  4523. );
  4524. }
  4525. /**
  4526. * Adds multiple JavaScript or CSS files at the same time.
  4527. *
  4528. * A library defines a set of JavaScript and/or CSS files, optionally using
  4529. * settings, and optionally requiring another library. For example, a library
  4530. * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
  4531. * function allows modules to load a library defined/shipped by itself or a
  4532. * depending module, without having to add all files of the library separately.
  4533. * Each library is only loaded once.
  4534. *
  4535. * @param $module
  4536. * The name of the module that registered the library.
  4537. * @param $name
  4538. * The name of the library to add.
  4539. * @param $every_page
  4540. * Set to TRUE if this library is added to every page on the site. Only items
  4541. * with the every_page flag set to TRUE can participate in aggregation.
  4542. *
  4543. * @return
  4544. * TRUE if the library was successfully added; FALSE if the library or one of
  4545. * its dependencies could not be added.
  4546. *
  4547. * @see drupal_get_library()
  4548. * @see hook_library()
  4549. * @see hook_library_alter()
  4550. */
  4551. function drupal_add_library($module, $name, $every_page = NULL) {
  4552. $added = &drupal_static(__FUNCTION__, array());
  4553. // Only process the library if it exists and it was not added already.
  4554. if (!isset($added[$module][$name])) {
  4555. if ($library = drupal_get_library($module, $name)) {
  4556. // Add all components within the library.
  4557. $elements['#attached'] = array(
  4558. 'library' => $library['dependencies'],
  4559. 'js' => $library['js'],
  4560. 'css' => $library['css'],
  4561. );
  4562. $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
  4563. }
  4564. else {
  4565. // Requested library does not exist.
  4566. $added[$module][$name] = FALSE;
  4567. }
  4568. }
  4569. return $added[$module][$name];
  4570. }
  4571. /**
  4572. * Retrieves information for a JavaScript/CSS library.
  4573. *
  4574. * Library information is statically cached. Libraries are keyed by module for
  4575. * several reasons:
  4576. * - Libraries are not unique. Multiple modules might ship with the same library
  4577. * in a different version or variant. This registry cannot (and does not
  4578. * attempt to) prevent library conflicts.
  4579. * - Modules implementing and thereby depending on a library that is registered
  4580. * by another module can only rely on that module's library.
  4581. * - Two (or more) modules can still register the same library and use it
  4582. * without conflicts in case the libraries are loaded on certain pages only.
  4583. *
  4584. * @param $module
  4585. * The name of a module that registered a library.
  4586. * @param $name
  4587. * (optional) The name of a registered library to retrieve. By default, all
  4588. * libraries registered by $module are returned.
  4589. *
  4590. * @return
  4591. * The definition of the requested library, if $name was passed and it exists,
  4592. * or FALSE if it does not exist. If no $name was passed, an associative array
  4593. * of libraries registered by $module is returned (which may be empty).
  4594. *
  4595. * @see drupal_add_library()
  4596. * @see hook_library()
  4597. * @see hook_library_alter()
  4598. *
  4599. * @todo The purpose of drupal_get_*() is completely different to other page
  4600. * requisite API functions; find and use a different name.
  4601. */
  4602. function drupal_get_library($module, $name = NULL) {
  4603. $libraries = &drupal_static(__FUNCTION__, array());
  4604. if (!isset($libraries[$module])) {
  4605. // Retrieve all libraries associated with the module.
  4606. $module_libraries = module_invoke($module, 'library');
  4607. if (empty($module_libraries)) {
  4608. $module_libraries = array();
  4609. }
  4610. // Allow modules to alter the module's registered libraries.
  4611. drupal_alter('library', $module_libraries, $module);
  4612. foreach ($module_libraries as $key => $data) {
  4613. if (is_array($data)) {
  4614. // Add default elements to allow for easier processing.
  4615. $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
  4616. foreach ($module_libraries[$key]['js'] as $file => $options) {
  4617. $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
  4618. }
  4619. }
  4620. }
  4621. $libraries[$module] = $module_libraries;
  4622. }
  4623. if (isset($name)) {
  4624. if (!isset($libraries[$module][$name])) {
  4625. $libraries[$module][$name] = FALSE;
  4626. }
  4627. return $libraries[$module][$name];
  4628. }
  4629. return $libraries[$module];
  4630. }
  4631. /**
  4632. * Assists in adding the tableDrag JavaScript behavior to a themed table.
  4633. *
  4634. * Draggable tables should be used wherever an outline or list of sortable items
  4635. * needs to be arranged by an end-user. Draggable tables are very flexible and
  4636. * can manipulate the value of form elements placed within individual columns.
  4637. *
  4638. * To set up a table to use drag and drop in place of weight select-lists or in
  4639. * place of a form that contains parent relationships, the form must be themed
  4640. * into a table. The table must have an ID attribute set. If using
  4641. * theme_table(), the ID may be set as follows:
  4642. * @code
  4643. * $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));
  4644. * return $output;
  4645. * @endcode
  4646. *
  4647. * In the theme function for the form, a special class must be added to each
  4648. * form element within the same column, "grouping" them together.
  4649. *
  4650. * In a situation where a single weight column is being sorted in the table, the
  4651. * classes could be added like this (in the theme function):
  4652. * @code
  4653. * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
  4654. * @endcode
  4655. *
  4656. * Each row of the table must also have a class of "draggable" in order to
  4657. * enable the drag handles:
  4658. * @code
  4659. * $row = array(...);
  4660. * $rows[] = array(
  4661. * 'data' => $row,
  4662. * 'class' => array('draggable'),
  4663. * );
  4664. * @endcode
  4665. *
  4666. * When tree relationships are present, the two additional classes
  4667. * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
  4668. * - Rows with the 'tabledrag-leaf' class cannot have child rows.
  4669. * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
  4670. *
  4671. * Calling drupal_add_tabledrag() would then be written as such:
  4672. * @code
  4673. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
  4674. * @endcode
  4675. *
  4676. * In a more complex case where there are several groups in one column (such as
  4677. * the block regions on the admin/structure/block page), a separate subgroup
  4678. * class must also be added to differentiate the groups.
  4679. * @code
  4680. * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
  4681. * @endcode
  4682. *
  4683. * $group is still 'my-element-weight', and the additional $subgroup variable
  4684. * will be passed in as 'my-elements-weight-' . $region. This also means that
  4685. * you'll need to call drupal_add_tabledrag() once for every region added.
  4686. *
  4687. * @code
  4688. * foreach ($regions as $region) {
  4689. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-' . $region);
  4690. * }
  4691. * @endcode
  4692. *
  4693. * In a situation where tree relationships are present, adding multiple
  4694. * subgroups is not necessary, because the table will contain indentations that
  4695. * provide enough information about the sibling and parent relationships. See
  4696. * theme_menu_overview_form() for an example creating a table containing parent
  4697. * relationships.
  4698. *
  4699. * Note that this function should be called from the theme layer, such as in a
  4700. * .tpl.php file, theme_ function, or in a template_preprocess function, not in
  4701. * a form declaration. Though the same JavaScript could be added to the page
  4702. * using drupal_add_js() directly, this function helps keep template files
  4703. * clean and readable. It also prevents tabledrag.js from being added twice
  4704. * accidentally.
  4705. *
  4706. * @param $table_id
  4707. * String containing the target table's id attribute. If the table does not
  4708. * have an id, one will need to be set, such as <table id="my-module-table">.
  4709. * @param $action
  4710. * String describing the action to be done on the form item. Either 'match'
  4711. * 'depth', or 'order'. Match is typically used for parent relationships.
  4712. * Order is typically used to set weights on other form elements with the same
  4713. * group. Depth updates the target element with the current indentation.
  4714. * @param $relationship
  4715. * String describing where the $action variable should be performed. Either
  4716. * 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
  4717. * up the tree. Sibling will look for fields in the same group in rows above
  4718. * and below it. Self affects the dragged row itself. Group affects the
  4719. * dragged row, plus any children below it (the entire dragged group).
  4720. * @param $group
  4721. * A class name applied on all related form elements for this action.
  4722. * @param $subgroup
  4723. * (optional) If the group has several subgroups within it, this string should
  4724. * contain the class name identifying fields in the same subgroup.
  4725. * @param $source
  4726. * (optional) If the $action is 'match', this string should contain the class
  4727. * name identifying what field will be used as the source value when matching
  4728. * the value in $subgroup.
  4729. * @param $hidden
  4730. * (optional) The column containing the field elements may be entirely hidden
  4731. * from view dynamically when the JavaScript is loaded. Set to FALSE if the
  4732. * column should not be hidden.
  4733. * @param $limit
  4734. * (optional) Limit the maximum amount of parenting in this table.
  4735. * @see block-admin-display-form.tpl.php
  4736. * @see theme_menu_overview_form()
  4737. */
  4738. function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
  4739. $js_added = &drupal_static(__FUNCTION__, FALSE);
  4740. if (!$js_added) {
  4741. // Add the table drag JavaScript to the page before the module JavaScript
  4742. // to ensure that table drag behaviors are registered before any module
  4743. // uses it.
  4744. drupal_add_library('system', 'jquery.cookie');
  4745. drupal_add_js('misc/tabledrag.js', array('weight' => -1));
  4746. $js_added = TRUE;
  4747. }
  4748. // If a subgroup or source isn't set, assume it is the same as the group.
  4749. $target = isset($subgroup) ? $subgroup : $group;
  4750. $source = isset($source) ? $source : $target;
  4751. $settings['tableDrag'][$table_id][$group][] = array(
  4752. 'target' => $target,
  4753. 'source' => $source,
  4754. 'relationship' => $relationship,
  4755. 'action' => $action,
  4756. 'hidden' => $hidden,
  4757. 'limit' => $limit,
  4758. );
  4759. drupal_add_js($settings, 'setting');
  4760. }
  4761. /**
  4762. * Aggregates JavaScript files into a cache file in the files directory.
  4763. *
  4764. * The file name for the JavaScript cache file is generated from the hash of
  4765. * the aggregated contents of the files in $files. This forces proxies and
  4766. * browsers to download new JavaScript when the JavaScript changes.
  4767. *
  4768. * The cache file name is retrieved on a page load via a lookup variable that
  4769. * contains an associative array. The array key is the hash of the names in
  4770. * $files while the value is the cache file name. The cache file is generated
  4771. * in two cases. First, if there is no file name value for the key, which will
  4772. * happen if a new file name has been added to $files or after the lookup
  4773. * variable is emptied to force a rebuild of the cache. Second, the cache file
  4774. * is generated if it is missing on disk. Old cache files are not deleted
  4775. * immediately when the lookup variable is emptied, but are deleted after a set
  4776. * period by drupal_delete_file_if_stale(). This ensures that files referenced
  4777. * by a cached page will still be available.
  4778. *
  4779. * @param $files
  4780. * An array of JavaScript files to aggregate and compress into one file.
  4781. *
  4782. * @return
  4783. * The URI of the cache file, or FALSE if the file could not be saved.
  4784. */
  4785. function drupal_build_js_cache($files) {
  4786. $contents = '';
  4787. $uri = '';
  4788. $map = variable_get('drupal_js_cache_files', array());
  4789. // Create a new array so that only the file names are used to create the hash.
  4790. // This prevents new aggregates from being created unnecessarily.
  4791. $js_data = array();
  4792. foreach ($files as $file) {
  4793. $js_data[] = $file['data'];
  4794. }
  4795. $key = hash('sha256', serialize($js_data));
  4796. if (isset($map[$key])) {
  4797. $uri = $map[$key];
  4798. }
  4799. if (empty($uri) || !file_exists($uri)) {
  4800. // Build aggregate JS file.
  4801. foreach ($files as $path => $info) {
  4802. if ($info['preprocess']) {
  4803. // Append a ';' and a newline after each JS file to prevent them from running together.
  4804. $contents .= file_get_contents($path) . ";\n";
  4805. }
  4806. }
  4807. // Prefix filename to prevent blocking by firewalls which reject files
  4808. // starting with "ad*".
  4809. $filename = 'js_' . drupal_hash_base64($contents) . '.js';
  4810. // Create the js/ within the files folder.
  4811. $jspath = 'public://js';
  4812. $uri = $jspath . '/' . $filename;
  4813. // Create the JS file.
  4814. file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
  4815. if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
  4816. return FALSE;
  4817. }
  4818. // If JS gzip compression is enabled, clean URLs are enabled (which means
  4819. // that rewrite rules are working) and the zlib extension is available then
  4820. // create a gzipped version of this file. This file is served conditionally
  4821. // to browsers that accept gzip using .htaccess rules.
  4822. if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
  4823. if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
  4824. return FALSE;
  4825. }
  4826. }
  4827. $map[$key] = $uri;
  4828. variable_set('drupal_js_cache_files', $map);
  4829. }
  4830. return $uri;
  4831. }
  4832. /**
  4833. * Deletes old cached JavaScript files and variables.
  4834. */
  4835. function drupal_clear_js_cache() {
  4836. variable_del('javascript_parsed');
  4837. variable_del('drupal_js_cache_files');
  4838. file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
  4839. }
  4840. /**
  4841. * Converts a PHP variable into its JavaScript equivalent.
  4842. *
  4843. * We use HTML-safe strings, with several characters escaped.
  4844. *
  4845. * @see drupal_json_decode()
  4846. * @see drupal_json_encode_helper()
  4847. * @ingroup php_wrappers
  4848. */
  4849. function drupal_json_encode($var) {
  4850. // The PHP version cannot change within a request.
  4851. static $php530;
  4852. if (!isset($php530)) {
  4853. $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
  4854. }
  4855. if ($php530) {
  4856. // Encode <, >, ', &, and " using the json_encode() options parameter.
  4857. return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  4858. }
  4859. // json_encode() escapes <, >, ', &, and " using its options parameter, but
  4860. // does not support this parameter prior to PHP 5.3.0. Use a helper instead.
  4861. include_once DRUPAL_ROOT . '/includes/json-encode.inc';
  4862. return drupal_json_encode_helper($var);
  4863. }
  4864. /**
  4865. * Converts an HTML-safe JSON string into its PHP equivalent.
  4866. *
  4867. * @see drupal_json_encode()
  4868. * @ingroup php_wrappers
  4869. */
  4870. function drupal_json_decode($var) {
  4871. return json_decode($var, TRUE);
  4872. }
  4873. /**
  4874. * Returns data in JSON format.
  4875. *
  4876. * This function should be used for JavaScript callback functions returning
  4877. * data in JSON format. It sets the header for JavaScript output.
  4878. *
  4879. * @param $var
  4880. * (optional) If set, the variable will be converted to JSON and output.
  4881. */
  4882. function drupal_json_output($var = NULL) {
  4883. // We are returning JSON, so tell the browser.
  4884. drupal_add_http_header('Content-Type', 'application/json');
  4885. if (isset($var)) {
  4886. echo drupal_json_encode($var);
  4887. }
  4888. }
  4889. /**
  4890. * Ensures the private key variable used to generate tokens is set.
  4891. *
  4892. * @return
  4893. * The private key.
  4894. */
  4895. function drupal_get_private_key() {
  4896. if (!($key = variable_get('drupal_private_key', 0))) {
  4897. $key = drupal_random_key();
  4898. variable_set('drupal_private_key', $key);
  4899. }
  4900. return $key;
  4901. }
  4902. /**
  4903. * Generates a token based on $value, the user session, and the private key.
  4904. *
  4905. * @param $value
  4906. * An additional value to base the token on.
  4907. *
  4908. * The generated token is based on the session ID of the current user. Normally,
  4909. * anonymous users do not have a session, so the generated token will be
  4910. * different on every page request. To generate a token for users without a
  4911. * session, manually start a session prior to calling this function.
  4912. *
  4913. * @return string
  4914. * A 43-character URL-safe token for validation, based on the user session ID,
  4915. * the hash salt provided from drupal_get_hash_salt(), and the
  4916. * 'drupal_private_key' configuration variable.
  4917. *
  4918. * @see drupal_get_hash_salt()
  4919. */
  4920. function drupal_get_token($value = '') {
  4921. return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
  4922. }
  4923. /**
  4924. * Validates a token based on $value, the user session, and the private key.
  4925. *
  4926. * @param $token
  4927. * The token to be validated.
  4928. * @param $value
  4929. * An additional value to base the token on.
  4930. * @param $skip_anonymous
  4931. * Set to true to skip token validation for anonymous users.
  4932. *
  4933. * @return
  4934. * True for a valid token, false for an invalid token. When $skip_anonymous
  4935. * is true, the return value will always be true for anonymous users.
  4936. */
  4937. function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
  4938. global $user;
  4939. return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
  4940. }
  4941. function _drupal_bootstrap_full() {
  4942. static $called = FALSE;
  4943. if ($called) {
  4944. return;
  4945. }
  4946. $called = TRUE;
  4947. require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
  4948. require_once DRUPAL_ROOT . '/includes/theme.inc';
  4949. require_once DRUPAL_ROOT . '/includes/pager.inc';
  4950. require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
  4951. require_once DRUPAL_ROOT . '/includes/tablesort.inc';
  4952. require_once DRUPAL_ROOT . '/includes/file.inc';
  4953. require_once DRUPAL_ROOT . '/includes/unicode.inc';
  4954. require_once DRUPAL_ROOT . '/includes/image.inc';
  4955. require_once DRUPAL_ROOT . '/includes/form.inc';
  4956. require_once DRUPAL_ROOT . '/includes/mail.inc';
  4957. require_once DRUPAL_ROOT . '/includes/actions.inc';
  4958. require_once DRUPAL_ROOT . '/includes/ajax.inc';
  4959. require_once DRUPAL_ROOT . '/includes/token.inc';
  4960. require_once DRUPAL_ROOT . '/includes/errors.inc';
  4961. // Detect string handling method
  4962. unicode_check();
  4963. // Undo magic quotes
  4964. fix_gpc_magic();
  4965. // Load all enabled modules
  4966. module_load_all();
  4967. // Reset drupal_alter() and module_implements() static caches as these
  4968. // include implementations for vital modules only when called early on
  4969. // in the bootstrap.
  4970. drupal_static_reset('drupal_alter');
  4971. drupal_static_reset('module_implements');
  4972. // Make sure all stream wrappers are registered.
  4973. file_get_stream_wrappers();
  4974. // Ensure mt_rand is reseeded, to prevent random values from one page load
  4975. // being exploited to predict random values in subsequent page loads.
  4976. $seed = unpack("L", drupal_random_bytes(4));
  4977. mt_srand($seed[1]);
  4978. $test_info = &$GLOBALS['drupal_test_info'];
  4979. if (!empty($test_info['in_child_site'])) {
  4980. // Running inside the simpletest child site, log fatal errors to test
  4981. // specific file directory.
  4982. ini_set('log_errors', 1);
  4983. ini_set('error_log', 'public://error.log');
  4984. }
  4985. // Initialize $_GET['q'] prior to invoking hook_init().
  4986. drupal_path_initialize();
  4987. // Let all modules take action before the menu system handles the request.
  4988. // We do not want this while running update.php.
  4989. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  4990. // Prior to invoking hook_init(), initialize the theme (potentially a custom
  4991. // one for this page), so that:
  4992. // - Modules with hook_init() implementations that call theme() or
  4993. // theme_get_registry() don't initialize the incorrect theme.
  4994. // - The theme can have hook_*_alter() implementations affect page building
  4995. // (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
  4996. // ahead of when rendering starts.
  4997. menu_set_custom_theme();
  4998. drupal_theme_initialize();
  4999. module_invoke_all('init');
  5000. }
  5001. }
  5002. /**
  5003. * Stores the current page in the cache.
  5004. *
  5005. * If page_compression is enabled, a gzipped version of the page is stored in
  5006. * the cache to avoid compressing the output on each request. The cache entry
  5007. * is unzipped in the relatively rare event that the page is requested by a
  5008. * client without gzip support.
  5009. *
  5010. * Page compression requires the PHP zlib extension
  5011. * (http://php.net/manual/ref.zlib.php).
  5012. *
  5013. * @see drupal_page_header()
  5014. */
  5015. function drupal_page_set_cache() {
  5016. global $base_root;
  5017. if (drupal_page_is_cacheable()) {
  5018. // Check whether the current page might be compressed.
  5019. $page_compressed = variable_get('page_compression', TRUE) && extension_loaded('zlib');
  5020. $cache = (object) array(
  5021. 'cid' => $base_root . request_uri(),
  5022. 'data' => array(
  5023. 'path' => $_GET['q'],
  5024. 'body' => ob_get_clean(),
  5025. 'title' => drupal_get_title(),
  5026. 'headers' => array(),
  5027. // We need to store whether page was compressed or not,
  5028. // because by the time it is read, the configuration might change.
  5029. 'page_compressed' => $page_compressed,
  5030. ),
  5031. 'expire' => CACHE_TEMPORARY,
  5032. 'created' => REQUEST_TIME,
  5033. );
  5034. // Restore preferred header names based on the lower-case names returned
  5035. // by drupal_get_http_header().
  5036. $header_names = _drupal_set_preferred_header_name();
  5037. foreach (drupal_get_http_header() as $name_lower => $value) {
  5038. $cache->data['headers'][$header_names[$name_lower]] = $value;
  5039. if ($name_lower == 'expires') {
  5040. // Use the actual timestamp from an Expires header if available.
  5041. $cache->expire = strtotime($value);
  5042. }
  5043. }
  5044. if ($cache->data['body']) {
  5045. if ($page_compressed) {
  5046. $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
  5047. }
  5048. cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
  5049. }
  5050. return $cache;
  5051. }
  5052. }
  5053. /**
  5054. * Executes a cron run when called.
  5055. *
  5056. * Do not call this function from a test. Use $this->cronRun() instead.
  5057. *
  5058. * @return bool
  5059. * TRUE if cron ran successfully and FALSE if cron is already running.
  5060. */
  5061. function drupal_cron_run() {
  5062. // Allow execution to continue even if the request gets canceled.
  5063. @ignore_user_abort(TRUE);
  5064. // Prevent session information from being saved while cron is running.
  5065. $original_session_saving = drupal_save_session();
  5066. drupal_save_session(FALSE);
  5067. // Force the current user to anonymous to ensure consistent permissions on
  5068. // cron runs.
  5069. $original_user = $GLOBALS['user'];
  5070. $GLOBALS['user'] = drupal_anonymous_user();
  5071. // Try to allocate enough time to run all the hook_cron implementations.
  5072. drupal_set_time_limit(240);
  5073. $return = FALSE;
  5074. // Grab the defined cron queues.
  5075. $queues = module_invoke_all('cron_queue_info');
  5076. drupal_alter('cron_queue_info', $queues);
  5077. // Try to acquire cron lock.
  5078. if (!lock_acquire('cron', 240.0)) {
  5079. // Cron is still running normally.
  5080. watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
  5081. }
  5082. else {
  5083. // Make sure every queue exists. There is no harm in trying to recreate an
  5084. // existing queue.
  5085. foreach ($queues as $queue_name => $info) {
  5086. DrupalQueue::get($queue_name)->createQueue();
  5087. }
  5088. // Iterate through the modules calling their cron handlers (if any):
  5089. foreach (module_implements('cron') as $module) {
  5090. // Do not let an exception thrown by one module disturb another.
  5091. try {
  5092. module_invoke($module, 'cron');
  5093. }
  5094. catch (Exception $e) {
  5095. watchdog_exception('cron', $e);
  5096. }
  5097. }
  5098. // Record cron time.
  5099. variable_set('cron_last', REQUEST_TIME);
  5100. watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
  5101. // Release cron lock.
  5102. lock_release('cron');
  5103. // Return TRUE so other functions can check if it did run successfully
  5104. $return = TRUE;
  5105. }
  5106. foreach ($queues as $queue_name => $info) {
  5107. if (!empty($info['skip on cron'])) {
  5108. // Do not run if queue wants to skip.
  5109. continue;
  5110. }
  5111. $callback = $info['worker callback'];
  5112. $end = time() + (isset($info['time']) ? $info['time'] : 15);
  5113. $queue = DrupalQueue::get($queue_name);
  5114. while (time() < $end && ($item = $queue->claimItem())) {
  5115. try {
  5116. call_user_func($callback, $item->data);
  5117. $queue->deleteItem($item);
  5118. }
  5119. catch (Exception $e) {
  5120. // In case of exception log it and leave the item in the queue
  5121. // to be processed again later.
  5122. watchdog_exception('cron', $e);
  5123. }
  5124. }
  5125. }
  5126. // Restore the user.
  5127. $GLOBALS['user'] = $original_user;
  5128. drupal_save_session($original_session_saving);
  5129. return $return;
  5130. }
  5131. /**
  5132. * DEPRECATED: Shutdown function: Performs cron cleanup.
  5133. *
  5134. * This function is deprecated because the 'cron_semaphore' variable it
  5135. * references no longer exists. It is therefore no longer used as a shutdown
  5136. * function by Drupal core.
  5137. *
  5138. * @deprecated
  5139. */
  5140. function drupal_cron_cleanup() {
  5141. // See if the semaphore is still locked.
  5142. if (variable_get('cron_semaphore', FALSE)) {
  5143. watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
  5144. // Release cron semaphore.
  5145. variable_del('cron_semaphore');
  5146. }
  5147. }
  5148. /**
  5149. * Returns information about system object files (modules, themes, etc.).
  5150. *
  5151. * This function is used to find all or some system object files (module files,
  5152. * theme files, etc.) that exist on the site. It searches in several locations,
  5153. * depending on what type of object you are looking for. For instance, if you
  5154. * are looking for modules and call:
  5155. * @code
  5156. * drupal_system_listing("/\.module$/", "modules", 'name', 0);
  5157. * @endcode
  5158. * this function will search the site-wide modules directory (i.e., /modules/),
  5159. * your installation profile's directory (i.e.,
  5160. * /profiles/your_site_profile/modules/), the all-sites directory (i.e.,
  5161. * /sites/all/modules/), and your site-specific directory (i.e.,
  5162. * /sites/your_site_dir/modules/), in that order, and return information about
  5163. * all of the files ending in .module in those directories.
  5164. *
  5165. * The information is returned in an associative array, which can be keyed on
  5166. * the file name ($key = 'filename'), the file name without the extension ($key
  5167. * = 'name'), or the full file stream URI ($key = 'uri'). If you use a key of
  5168. * 'filename' or 'name', files found later in the search will take precedence
  5169. * over files found earlier (unless they belong to a module or theme not
  5170. * compatible with Drupal core); if you choose a key of 'uri', you will get all
  5171. * files found.
  5172. *
  5173. * @param string $mask
  5174. * The preg_match() regular expression for the files to find.
  5175. * @param string $directory
  5176. * The subdirectory name in which the files are found. For example,
  5177. * 'modules' will search in sub-directories of the top-level /modules
  5178. * directory, sub-directories of /sites/all/modules/, etc.
  5179. * @param string $key
  5180. * The key to be used for the associative array returned. Possible values are
  5181. * 'uri', for the file's URI; 'filename', for the basename of the file; and
  5182. * 'name' for the name of the file without the extension. If you choose 'name'
  5183. * or 'filename', only the highest-precedence file will be returned.
  5184. * @param int $min_depth
  5185. * Minimum depth of directories to return files from, relative to each
  5186. * directory searched. For instance, a minimum depth of 2 would find modules
  5187. * inside /modules/node/tests, but not modules directly in /modules/node.
  5188. *
  5189. * @return array
  5190. * An associative array of file objects, keyed on the chosen key. Each element
  5191. * in the array is an object containing file information, with properties:
  5192. * - 'uri': Full URI of the file.
  5193. * - 'filename': File name.
  5194. * - 'name': Name of file without the extension.
  5195. */
  5196. function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
  5197. $config = conf_path();
  5198. $searchdir = array($directory);
  5199. $files = array();
  5200. // The 'profiles' directory contains pristine collections of modules and
  5201. // themes as organized by a distribution. It is pristine in the same way
  5202. // that /modules is pristine for core; users should avoid changing anything
  5203. // there in favor of sites/all or sites/<domain> directories.
  5204. $profiles = array();
  5205. $profile = drupal_get_profile();
  5206. // For SimpleTest to be able to test modules packaged together with a
  5207. // distribution we need to include the profile of the parent site (in which
  5208. // test runs are triggered).
  5209. if (drupal_valid_test_ua()) {
  5210. $testing_profile = variable_get('simpletest_parent_profile', FALSE);
  5211. if ($testing_profile && $testing_profile != $profile) {
  5212. $profiles[] = $testing_profile;
  5213. }
  5214. }
  5215. // In case both profile directories contain the same extension, the actual
  5216. // profile always has precedence.
  5217. $profiles[] = $profile;
  5218. foreach ($profiles as $profile) {
  5219. if (file_exists("profiles/$profile/$directory")) {
  5220. $searchdir[] = "profiles/$profile/$directory";
  5221. }
  5222. }
  5223. // Always search sites/all/* as well as the global directories.
  5224. $searchdir[] = 'sites/all/' . $directory;
  5225. if (file_exists("$config/$directory")) {
  5226. $searchdir[] = "$config/$directory";
  5227. }
  5228. // Get current list of items.
  5229. if (!function_exists('file_scan_directory')) {
  5230. require_once DRUPAL_ROOT . '/includes/file.inc';
  5231. }
  5232. foreach ($searchdir as $dir) {
  5233. $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
  5234. // Duplicate files found in later search directories take precedence over
  5235. // earlier ones, so we want them to overwrite keys in our resulting
  5236. // $files array.
  5237. // The exception to this is if the later file is from a module or theme not
  5238. // compatible with Drupal core. This may occur during upgrades of Drupal
  5239. // core when new modules exist in core while older contrib modules with the
  5240. // same name exist in a directory such as sites/all/modules/.
  5241. foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
  5242. // If it has no info file, then we just behave liberally and accept the
  5243. // new resource on the list for merging.
  5244. if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
  5245. // Get the .info file for the module or theme this file belongs to.
  5246. $info = drupal_parse_info_file($info_file);
  5247. // If the module or theme is incompatible with Drupal core, remove it
  5248. // from the array for the current search directory, so it is not
  5249. // overwritten when merged with the $files array.
  5250. if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
  5251. unset($files_to_add[$file_key]);
  5252. }
  5253. }
  5254. }
  5255. $files = array_merge($files, $files_to_add);
  5256. }
  5257. return $files;
  5258. }
  5259. /**
  5260. * Sets the main page content value for later use.
  5261. *
  5262. * Given the nature of the Drupal page handling, this will be called once with
  5263. * a string or array. We store that and return it later as the block is being
  5264. * displayed.
  5265. *
  5266. * @param $content
  5267. * A string or renderable array representing the body of the page.
  5268. *
  5269. * @return
  5270. * If called without $content, a renderable array representing the body of
  5271. * the page.
  5272. */
  5273. function drupal_set_page_content($content = NULL) {
  5274. $content_block = &drupal_static(__FUNCTION__, NULL);
  5275. $main_content_display = &drupal_static('system_main_content_added', FALSE);
  5276. if (!empty($content)) {
  5277. $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
  5278. }
  5279. else {
  5280. // Indicate that the main content has been requested. We assume that
  5281. // the module requesting the content will be adding it to the page.
  5282. // A module can indicate that it does not handle the content by setting
  5283. // the static variable back to FALSE after calling this function.
  5284. $main_content_display = TRUE;
  5285. return $content_block;
  5286. }
  5287. }
  5288. /**
  5289. * #pre_render callback to render #browsers into #prefix and #suffix.
  5290. *
  5291. * @param $elements
  5292. * A render array with a '#browsers' property. The '#browsers' property can
  5293. * contain any or all of the following keys:
  5294. * - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
  5295. * TRUE, the element is rendered by Internet Explorer. Can also be a string
  5296. * containing an expression for Internet Explorer to evaluate as part of a
  5297. * conditional comment. For example, this can be set to 'lt IE 7' for the
  5298. * element to be rendered in Internet Explorer 6, but not in Internet
  5299. * Explorer 7 or higher. Defaults to TRUE.
  5300. * - '!IE': If FALSE, the element is not rendered by browsers other than
  5301. * Internet Explorer. If TRUE, the element is rendered by those browsers.
  5302. * Defaults to TRUE.
  5303. * Examples:
  5304. * - To render an element in all browsers, '#browsers' can be left out or set
  5305. * to array('IE' => TRUE, '!IE' => TRUE).
  5306. * - To render an element in Internet Explorer only, '#browsers' can be set
  5307. * to array('!IE' => FALSE).
  5308. * - To render an element in Internet Explorer 6 only, '#browsers' can be set
  5309. * to array('IE' => 'lt IE 7', '!IE' => FALSE).
  5310. * - To render an element in Internet Explorer 8 and higher and in all other
  5311. * browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
  5312. *
  5313. * @return
  5314. * The passed-in element with markup for conditional comments potentially
  5315. * added to '#prefix' and '#suffix'.
  5316. */
  5317. function drupal_pre_render_conditional_comments($elements) {
  5318. $browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
  5319. $browsers += array(
  5320. 'IE' => TRUE,
  5321. '!IE' => TRUE,
  5322. );
  5323. // If rendering in all browsers, no need for conditional comments.
  5324. if ($browsers['IE'] === TRUE && $browsers['!IE']) {
  5325. return $elements;
  5326. }
  5327. // Determine the conditional comment expression for Internet Explorer to
  5328. // evaluate.
  5329. if ($browsers['IE'] === TRUE) {
  5330. $expression = 'IE';
  5331. }
  5332. elseif ($browsers['IE'] === FALSE) {
  5333. $expression = '!IE';
  5334. }
  5335. else {
  5336. $expression = $browsers['IE'];
  5337. }
  5338. // Wrap the element's potentially existing #prefix and #suffix properties with
  5339. // conditional comment markup. The conditional comment expression is evaluated
  5340. // by Internet Explorer only. To control the rendering by other browsers,
  5341. // either the "downlevel-hidden" or "downlevel-revealed" technique must be
  5342. // used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
  5343. $elements += array(
  5344. '#prefix' => '',
  5345. '#suffix' => '',
  5346. );
  5347. if (!$browsers['!IE']) {
  5348. // "downlevel-hidden".
  5349. $elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
  5350. $elements['#suffix'] .= "<![endif]-->\n";
  5351. }
  5352. else {
  5353. // "downlevel-revealed".
  5354. $elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
  5355. $elements['#suffix'] .= "<!--<![endif]-->\n";
  5356. }
  5357. return $elements;
  5358. }
  5359. /**
  5360. * #pre_render callback to render a link into #markup.
  5361. *
  5362. * Doing so during pre_render gives modules a chance to alter the link parts.
  5363. *
  5364. * @param $elements
  5365. * A structured array whose keys form the arguments to l():
  5366. * - #title: The link text to pass as argument to l().
  5367. * - #href: The URL path component to pass as argument to l().
  5368. * - #options: (optional) An array of options to pass to l().
  5369. *
  5370. * @return
  5371. * The passed-in elements containing a rendered link in '#markup'.
  5372. */
  5373. function drupal_pre_render_link($element) {
  5374. // By default, link options to pass to l() are normally set in #options.
  5375. $element += array('#options' => array());
  5376. // However, within the scope of renderable elements, #attributes is a valid
  5377. // way to specify attributes, too. Take them into account, but do not override
  5378. // attributes from #options.
  5379. if (isset($element['#attributes'])) {
  5380. $element['#options'] += array('attributes' => array());
  5381. $element['#options']['attributes'] += $element['#attributes'];
  5382. }
  5383. // This #pre_render callback can be invoked from inside or outside of a Form
  5384. // API context, and depending on that, a HTML ID may be already set in
  5385. // different locations. #options should have precedence over Form API's #id.
  5386. // #attributes have been taken over into #options above already.
  5387. if (isset($element['#options']['attributes']['id'])) {
  5388. $element['#id'] = $element['#options']['attributes']['id'];
  5389. }
  5390. elseif (isset($element['#id'])) {
  5391. $element['#options']['attributes']['id'] = $element['#id'];
  5392. }
  5393. // Conditionally invoke ajax_pre_render_element(), if #ajax is set.
  5394. if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
  5395. // If no HTML ID was found above, automatically create one.
  5396. if (!isset($element['#id'])) {
  5397. $element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
  5398. }
  5399. // If #ajax['path] was not specified, use the href as Ajax request URL.
  5400. if (!isset($element['#ajax']['path'])) {
  5401. $element['#ajax']['path'] = $element['#href'];
  5402. $element['#ajax']['options'] = $element['#options'];
  5403. }
  5404. $element = ajax_pre_render_element($element);
  5405. }
  5406. $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
  5407. return $element;
  5408. }
  5409. /**
  5410. * #pre_render callback that collects child links into a single array.
  5411. *
  5412. * This function can be added as a pre_render callback for a renderable array,
  5413. * usually one which will be themed by theme_links(). It iterates through all
  5414. * unrendered children of the element, collects any #links properties it finds,
  5415. * merges them into the parent element's #links array, and prevents those
  5416. * children from being rendered separately.
  5417. *
  5418. * The purpose of this is to allow links to be logically grouped into related
  5419. * categories, so that each child group can be rendered as its own list of
  5420. * links if drupal_render() is called on it, but calling drupal_render() on the
  5421. * parent element will still produce a single list containing all the remaining
  5422. * links, regardless of what group they were in.
  5423. *
  5424. * A typical example comes from node links, which are stored in a renderable
  5425. * array similar to this:
  5426. * @code
  5427. * $node->content['links'] = array(
  5428. * '#theme' => 'links__node',
  5429. * '#pre_render' => array('drupal_pre_render_links'),
  5430. * 'comment' => array(
  5431. * '#theme' => 'links__node__comment',
  5432. * '#links' => array(
  5433. * // An array of links associated with node comments, suitable for
  5434. * // passing in to theme_links().
  5435. * ),
  5436. * ),
  5437. * 'statistics' => array(
  5438. * '#theme' => 'links__node__statistics',
  5439. * '#links' => array(
  5440. * // An array of links associated with node statistics, suitable for
  5441. * // passing in to theme_links().
  5442. * ),
  5443. * ),
  5444. * 'translation' => array(
  5445. * '#theme' => 'links__node__translation',
  5446. * '#links' => array(
  5447. * // An array of links associated with node translation, suitable for
  5448. * // passing in to theme_links().
  5449. * ),
  5450. * ),
  5451. * );
  5452. * @endcode
  5453. *
  5454. * In this example, the links are grouped by functionality, which can be
  5455. * helpful to themers who want to display certain kinds of links independently.
  5456. * For example, adding this code to node.tpl.php will result in the comment
  5457. * links being rendered as a single list:
  5458. * @code
  5459. * print render($content['links']['comment']);
  5460. * @endcode
  5461. *
  5462. * (where $node->content has been transformed into $content before handing
  5463. * control to the node.tpl.php template).
  5464. *
  5465. * The pre_render function defined here allows the above flexibility, but also
  5466. * allows the following code to be used to render all remaining links into a
  5467. * single list, regardless of their group:
  5468. * @code
  5469. * print render($content['links']);
  5470. * @endcode
  5471. *
  5472. * In the above example, this will result in the statistics and translation
  5473. * links being rendered together in a single list (but not the comment links,
  5474. * which were rendered previously on their own).
  5475. *
  5476. * Because of the way this function works, the individual properties of each
  5477. * group (for example, a group-specific #theme property such as
  5478. * 'links__node__comment' in the example above, or any other property such as
  5479. * #attributes or #pre_render that is attached to it) are only used when that
  5480. * group is rendered on its own. When the group is rendered together with other
  5481. * children, these child-specific properties are ignored, and only the overall
  5482. * properties of the parent are used.
  5483. */
  5484. function drupal_pre_render_links($element) {
  5485. $element += array('#links' => array());
  5486. foreach (element_children($element) as $key) {
  5487. $child = &$element[$key];
  5488. // If the child has links which have not been printed yet and the user has
  5489. // access to it, merge its links in to the parent.
  5490. if (isset($child['#links']) && empty($child['#printed']) && (!isset($child['#access']) || $child['#access'])) {
  5491. $element['#links'] += $child['#links'];
  5492. // Mark the child as having been printed already (so that its links
  5493. // cannot be mistakenly rendered twice).
  5494. $child['#printed'] = TRUE;
  5495. }
  5496. }
  5497. return $element;
  5498. }
  5499. /**
  5500. * #pre_render callback to append contents in #markup to #children.
  5501. *
  5502. * This needs to be a #pre_render callback, because eventually assigned
  5503. * #theme_wrappers will expect the element's rendered content in #children.
  5504. * Note that if also a #theme is defined for the element, then the result of
  5505. * the theme callback will override #children.
  5506. *
  5507. * @param $elements
  5508. * A structured array using the #markup key.
  5509. *
  5510. * @return
  5511. * The passed-in elements, but #markup appended to #children.
  5512. *
  5513. * @see drupal_render()
  5514. */
  5515. function drupal_pre_render_markup($elements) {
  5516. $elements['#children'] = $elements['#markup'];
  5517. return $elements;
  5518. }
  5519. /**
  5520. * Renders the page, including all theming.
  5521. *
  5522. * @param $page
  5523. * A string or array representing the content of a page. The array consists of
  5524. * the following keys:
  5525. * - #type: Value is always 'page'. This pushes the theming through
  5526. * page.tpl.php (required).
  5527. * - #show_messages: Suppress drupal_get_message() items. Used by Batch
  5528. * API (optional).
  5529. *
  5530. * @see hook_page_alter()
  5531. * @see element_info()
  5532. */
  5533. function drupal_render_page($page) {
  5534. $main_content_display = &drupal_static('system_main_content_added', FALSE);
  5535. // Allow menu callbacks to return strings or arbitrary arrays to render.
  5536. // If the array returned is not of #type page directly, we need to fill
  5537. // in the page with defaults.
  5538. if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
  5539. drupal_set_page_content($page);
  5540. $page = element_info('page');
  5541. }
  5542. // Modules can add elements to $page as needed in hook_page_build().
  5543. foreach (module_implements('page_build') as $module) {
  5544. $function = $module . '_page_build';
  5545. $function($page);
  5546. }
  5547. // Modules alter the $page as needed. Blocks are populated into regions like
  5548. // 'sidebar_first', 'footer', etc.
  5549. drupal_alter('page', $page);
  5550. // If no module has taken care of the main content, add it to the page now.
  5551. // This allows the site to still be usable even if no modules that
  5552. // control page regions (for example, the Block module) are enabled.
  5553. if (!$main_content_display) {
  5554. $page['content']['system_main'] = drupal_set_page_content();
  5555. }
  5556. return drupal_render($page);
  5557. }
  5558. /**
  5559. * Renders HTML given a structured array tree.
  5560. *
  5561. * Recursively iterates over each of the array elements, generating HTML code.
  5562. *
  5563. * Renderable arrays have two kinds of key/value pairs: properties and
  5564. * children. Properties have keys starting with '#' and their values influence
  5565. * how the array will be rendered. Children are all elements whose keys do not
  5566. * start with a '#'. Their values should be renderable arrays themselves,
  5567. * which will be rendered during the rendering of the parent array. The markup
  5568. * provided by the children is typically inserted into the markup generated by
  5569. * the parent array.
  5570. *
  5571. * HTML generation for a renderable array, and the treatment of any children,
  5572. * is controlled by two properties containing theme functions, #theme and
  5573. * #theme_wrappers.
  5574. *
  5575. * #theme is the theme function called first. If it is set and the element has
  5576. * any children, it is the responsibility of the theme function to render
  5577. * these children. For elements that are not allowed to have any children,
  5578. * e.g. buttons or textfields, the theme function can be used to render the
  5579. * element itself. If #theme is not present and the element has children, each
  5580. * child is itself rendered by a call to drupal_render(), and the results are
  5581. * concatenated.
  5582. *
  5583. * The #theme_wrappers property contains an array of theme functions which will
  5584. * be called, in order, after #theme has run. These can be used to add further
  5585. * markup around the rendered children; e.g., fieldsets add the required markup
  5586. * for a fieldset around their rendered child elements. All wrapper theme
  5587. * functions have to include the element's #children property in their output,
  5588. * as it contains the output of the previous theme functions and the rendered
  5589. * children.
  5590. *
  5591. * For example, for the form element type, by default only the #theme_wrappers
  5592. * property is set, which adds the form markup around the rendered child
  5593. * elements of the form. This allows you to set the #theme property on a
  5594. * specific form to a custom theme function, giving you complete control over
  5595. * the placement of the form's children while not at all having to deal with
  5596. * the form markup itself.
  5597. *
  5598. * drupal_render() can optionally cache the rendered output of elements to
  5599. * improve performance. To use drupal_render() caching, set the element's #cache
  5600. * property to an associative array with one or several of the following keys:
  5601. * - 'keys': An array of one or more keys that identify the element. If 'keys'
  5602. * is set, the cache ID is created automatically from these keys. See
  5603. * drupal_render_cid_create().
  5604. * - 'granularity' (optional): Define the cache granularity using binary
  5605. * combinations of the cache granularity constants, e.g.
  5606. * DRUPAL_CACHE_PER_USER to cache for each user separately or
  5607. * DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE to cache separately for each
  5608. * page and role. If not specified the element is cached globally for each
  5609. * theme and language.
  5610. * - 'cid': Specify the cache ID directly. Either 'keys' or 'cid' is required.
  5611. * If 'cid' is set, 'keys' and 'granularity' are ignored. Use only if you
  5612. * have special requirements.
  5613. * - 'expire': Set to one of the cache lifetime constants.
  5614. * - 'bin': Specify a cache bin to cache the element in. Defaults to 'cache'.
  5615. *
  5616. * This function is usually called from within another function, like
  5617. * drupal_get_form() or a theme function. Elements are sorted internally
  5618. * using uasort(). Since this is expensive, when passing already sorted
  5619. * elements to drupal_render(), for example from a database query, set
  5620. * $elements['#sorted'] = TRUE to avoid sorting them a second time.
  5621. *
  5622. * drupal_render() flags each element with a '#printed' status to indicate that
  5623. * the element has been rendered, which allows individual elements of a given
  5624. * array to be rendered independently and prevents them from being rendered
  5625. * more than once on subsequent calls to drupal_render() (e.g., as part of a
  5626. * larger array). If the same array or array element is passed more than once
  5627. * to drupal_render(), it simply returns an empty string.
  5628. *
  5629. * @param array $elements
  5630. * The structured array describing the data to be rendered.
  5631. *
  5632. * @return string
  5633. * The rendered HTML.
  5634. */
  5635. function drupal_render(&$elements) {
  5636. // Early-return nothing if user does not have access.
  5637. if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
  5638. return '';
  5639. }
  5640. // Do not print elements twice.
  5641. if (!empty($elements['#printed'])) {
  5642. return '';
  5643. }
  5644. // Try to fetch the element's markup from cache and return.
  5645. if (isset($elements['#cache'])) {
  5646. $cached_output = drupal_render_cache_get($elements);
  5647. if ($cached_output !== FALSE) {
  5648. return $cached_output;
  5649. }
  5650. }
  5651. // If #markup is set, ensure #type is set. This allows to specify just #markup
  5652. // on an element without setting #type.
  5653. if (isset($elements['#markup']) && !isset($elements['#type'])) {
  5654. $elements['#type'] = 'markup';
  5655. }
  5656. // If the default values for this element have not been loaded yet, populate
  5657. // them.
  5658. if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  5659. $elements += element_info($elements['#type']);
  5660. }
  5661. // Make any final changes to the element before it is rendered. This means
  5662. // that the $element or the children can be altered or corrected before the
  5663. // element is rendered into the final text.
  5664. if (isset($elements['#pre_render'])) {
  5665. foreach ($elements['#pre_render'] as $function) {
  5666. if (function_exists($function)) {
  5667. $elements = $function($elements);
  5668. }
  5669. }
  5670. }
  5671. // Allow #pre_render to abort rendering.
  5672. if (!empty($elements['#printed'])) {
  5673. return '';
  5674. }
  5675. // Get the children of the element, sorted by weight.
  5676. $children = element_children($elements, TRUE);
  5677. // Initialize this element's #children, unless a #pre_render callback already
  5678. // preset #children.
  5679. if (!isset($elements['#children'])) {
  5680. $elements['#children'] = '';
  5681. }
  5682. // Call the element's #theme function if it is set. Then any children of the
  5683. // element have to be rendered there.
  5684. if (isset($elements['#theme'])) {
  5685. $elements['#children'] = theme($elements['#theme'], $elements);
  5686. }
  5687. // If #theme was not set and the element has children, render them now.
  5688. // This is the same process as drupal_render_children() but is inlined
  5689. // for speed.
  5690. if ($elements['#children'] == '') {
  5691. foreach ($children as $key) {
  5692. $elements['#children'] .= drupal_render($elements[$key]);
  5693. }
  5694. }
  5695. // Let the theme functions in #theme_wrappers add markup around the rendered
  5696. // children.
  5697. if (isset($elements['#theme_wrappers'])) {
  5698. foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
  5699. $elements['#children'] = theme($theme_wrapper, $elements);
  5700. }
  5701. }
  5702. // Filter the outputted content and make any last changes before the
  5703. // content is sent to the browser. The changes are made on $content
  5704. // which allows the output'ed text to be filtered.
  5705. if (isset($elements['#post_render'])) {
  5706. foreach ($elements['#post_render'] as $function) {
  5707. if (function_exists($function)) {
  5708. $elements['#children'] = $function($elements['#children'], $elements);
  5709. }
  5710. }
  5711. }
  5712. // Add any JavaScript state information associated with the element.
  5713. if (!empty($elements['#states'])) {
  5714. drupal_process_states($elements);
  5715. }
  5716. // Add additional libraries, CSS, JavaScript an other custom
  5717. // attached data associated with this element.
  5718. if (!empty($elements['#attached'])) {
  5719. drupal_process_attached($elements);
  5720. }
  5721. $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
  5722. $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
  5723. $output = $prefix . $elements['#children'] . $suffix;
  5724. // Cache the processed element if #cache is set.
  5725. if (isset($elements['#cache'])) {
  5726. drupal_render_cache_set($output, $elements);
  5727. }
  5728. $elements['#printed'] = TRUE;
  5729. return $output;
  5730. }
  5731. /**
  5732. * Renders children of an element and concatenates them.
  5733. *
  5734. * @param array $element
  5735. * The structured array whose children shall be rendered.
  5736. * @param array $children_keys
  5737. * (optional) If the keys of the element's children are already known, they
  5738. * can be passed in to save another run of element_children().
  5739. *
  5740. * @return string
  5741. * The rendered HTML of all children of the element.
  5742. * @see drupal_render()
  5743. */
  5744. function drupal_render_children(&$element, $children_keys = NULL) {
  5745. if ($children_keys === NULL) {
  5746. $children_keys = element_children($element);
  5747. }
  5748. $output = '';
  5749. foreach ($children_keys as $key) {
  5750. if (!empty($element[$key])) {
  5751. $output .= drupal_render($element[$key]);
  5752. }
  5753. }
  5754. return $output;
  5755. }
  5756. /**
  5757. * Renders an element.
  5758. *
  5759. * This function renders an element using drupal_render(). The top level
  5760. * element is shown with show() before rendering, so it will always be rendered
  5761. * even if hide() had been previously used on it.
  5762. *
  5763. * @param $element
  5764. * The element to be rendered.
  5765. *
  5766. * @return
  5767. * The rendered element.
  5768. *
  5769. * @see drupal_render()
  5770. * @see show()
  5771. * @see hide()
  5772. */
  5773. function render(&$element) {
  5774. if (is_array($element)) {
  5775. show($element);
  5776. return drupal_render($element);
  5777. }
  5778. else {
  5779. // Safe-guard for inappropriate use of render() on flat variables: return
  5780. // the variable as-is.
  5781. return $element;
  5782. }
  5783. }
  5784. /**
  5785. * Hides an element from later rendering.
  5786. *
  5787. * The first time render() or drupal_render() is called on an element tree,
  5788. * as each element in the tree is rendered, it is marked with a #printed flag
  5789. * and the rendered children of the element are cached. Subsequent calls to
  5790. * render() or drupal_render() will not traverse the child tree of this element
  5791. * again: they will just use the cached children. So if you want to hide an
  5792. * element, be sure to call hide() on the element before its parent tree is
  5793. * rendered for the first time, as it will have no effect on subsequent
  5794. * renderings of the parent tree.
  5795. *
  5796. * @param $element
  5797. * The element to be hidden.
  5798. *
  5799. * @return
  5800. * The element.
  5801. *
  5802. * @see render()
  5803. * @see show()
  5804. */
  5805. function hide(&$element) {
  5806. $element['#printed'] = TRUE;
  5807. return $element;
  5808. }
  5809. /**
  5810. * Shows a hidden element for later rendering.
  5811. *
  5812. * You can also use render($element), which shows the element while rendering
  5813. * it.
  5814. *
  5815. * The first time render() or drupal_render() is called on an element tree,
  5816. * as each element in the tree is rendered, it is marked with a #printed flag
  5817. * and the rendered children of the element are cached. Subsequent calls to
  5818. * render() or drupal_render() will not traverse the child tree of this element
  5819. * again: they will just use the cached children. So if you want to show an
  5820. * element, be sure to call show() on the element before its parent tree is
  5821. * rendered for the first time, as it will have no effect on subsequent
  5822. * renderings of the parent tree.
  5823. *
  5824. * @param $element
  5825. * The element to be shown.
  5826. *
  5827. * @return
  5828. * The element.
  5829. *
  5830. * @see render()
  5831. * @see hide()
  5832. */
  5833. function show(&$element) {
  5834. $element['#printed'] = FALSE;
  5835. return $element;
  5836. }
  5837. /**
  5838. * Gets the rendered output of a renderable element from the cache.
  5839. *
  5840. * @param $elements
  5841. * A renderable array.
  5842. *
  5843. * @return
  5844. * A markup string containing the rendered content of the element, or FALSE
  5845. * if no cached copy of the element is available.
  5846. *
  5847. * @see drupal_render()
  5848. * @see drupal_render_cache_set()
  5849. */
  5850. function drupal_render_cache_get($elements) {
  5851. if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
  5852. return FALSE;
  5853. }
  5854. $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
  5855. if (!empty($cid) && $cache = cache_get($cid, $bin)) {
  5856. // Add additional libraries, JavaScript, CSS and other data attached
  5857. // to this element.
  5858. if (isset($cache->data['#attached'])) {
  5859. drupal_process_attached($cache->data);
  5860. }
  5861. // Return the rendered output.
  5862. return $cache->data['#markup'];
  5863. }
  5864. return FALSE;
  5865. }
  5866. /**
  5867. * Caches the rendered output of a renderable element.
  5868. *
  5869. * This is called by drupal_render() if the #cache property is set on an
  5870. * element.
  5871. *
  5872. * @param $markup
  5873. * The rendered output string of $elements.
  5874. * @param $elements
  5875. * A renderable array.
  5876. *
  5877. * @see drupal_render_cache_get()
  5878. */
  5879. function drupal_render_cache_set(&$markup, $elements) {
  5880. // Create the cache ID for the element.
  5881. if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
  5882. return FALSE;
  5883. }
  5884. // Cache implementations are allowed to modify the markup, to support
  5885. // replacing markup with edge-side include commands. The supporting cache
  5886. // backend will store the markup in some other key (like
  5887. // $data['#real-value']) and return an include command instead. When the
  5888. // ESI command is executed by the content accelerator, the real value can
  5889. // be retrieved and used.
  5890. $data['#markup'] = &$markup;
  5891. // Persist attached data associated with this element.
  5892. $attached = drupal_render_collect_attached($elements, TRUE);
  5893. if ($attached) {
  5894. $data['#attached'] = $attached;
  5895. }
  5896. $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
  5897. $expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CACHE_PERMANENT;
  5898. cache_set($cid, $data, $bin, $expire);
  5899. }
  5900. /**
  5901. * Collects #attached for an element and its children into a single array.
  5902. *
  5903. * When caching elements, it is necessary to collect all libraries, JavaScript
  5904. * and CSS into a single array, from both the element itself and all child
  5905. * elements. This allows drupal_render() to add these back to the page when the
  5906. * element is returned from cache.
  5907. *
  5908. * @param $elements
  5909. * The element to collect #attached from.
  5910. * @param $return
  5911. * Whether to return the attached elements and reset the internal static.
  5912. *
  5913. * @return
  5914. * The #attached array for this element and its descendants.
  5915. */
  5916. function drupal_render_collect_attached($elements, $return = FALSE) {
  5917. $attached = &drupal_static(__FUNCTION__, array());
  5918. // Collect all #attached for this element.
  5919. if (isset($elements['#attached'])) {
  5920. foreach ($elements['#attached'] as $key => $value) {
  5921. if (!isset($attached[$key])) {
  5922. $attached[$key] = array();
  5923. }
  5924. $attached[$key] = array_merge($attached[$key], $value);
  5925. }
  5926. }
  5927. if ($children = element_children($elements)) {
  5928. foreach ($children as $child) {
  5929. drupal_render_collect_attached($elements[$child]);
  5930. }
  5931. }
  5932. // If this was the first call to the function, return all attached elements
  5933. // and reset the static cache.
  5934. if ($return) {
  5935. $return = $attached;
  5936. $attached = array();
  5937. return $return;
  5938. }
  5939. }
  5940. /**
  5941. * Prepares an element for caching based on a query.
  5942. *
  5943. * This smart caching strategy saves Drupal from querying and rendering to HTML
  5944. * when the underlying query is unchanged.
  5945. *
  5946. * Expensive queries should use the query builder to create the query and then
  5947. * call this function. Executing the query and formatting results should happen
  5948. * in a #pre_render callback.
  5949. *
  5950. * @param $query
  5951. * A select query object as returned by db_select().
  5952. * @param $function
  5953. * The name of the function doing this caching. A _pre_render suffix will be
  5954. * added to this string and is also part of the cache key in
  5955. * drupal_render_cache_set() and drupal_render_cache_get().
  5956. * @param $expire
  5957. * The cache expire time, passed eventually to cache_set().
  5958. * @param $granularity
  5959. * One or more granularity constants passed to drupal_render_cid_parts().
  5960. *
  5961. * @return
  5962. * A renderable array with the following keys and values:
  5963. * - #query: The passed-in $query.
  5964. * - #pre_render: $function with a _pre_render suffix.
  5965. * - #cache: An associative array prepared for drupal_render_cache_set().
  5966. */
  5967. function drupal_render_cache_by_query($query, $function, $expire = CACHE_TEMPORARY, $granularity = NULL) {
  5968. $cache_keys = array_merge(array($function), drupal_render_cid_parts($granularity));
  5969. $query->preExecute();
  5970. $cache_keys[] = hash('sha256', serialize(array((string) $query, $query->getArguments())));
  5971. return array(
  5972. '#query' => $query,
  5973. '#pre_render' => array($function . '_pre_render'),
  5974. '#cache' => array(
  5975. 'keys' => $cache_keys,
  5976. 'expire' => $expire,
  5977. ),
  5978. );
  5979. }
  5980. /**
  5981. * Returns cache ID parts for building a cache ID.
  5982. *
  5983. * @param $granularity
  5984. * One or more cache granularity constants. For example, to cache separately
  5985. * for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
  5986. * page and role, use the expression:
  5987. * @code
  5988. * DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
  5989. * @endcode
  5990. *
  5991. * @return
  5992. * An array of cache ID parts, always containing the active theme. If the
  5993. * locale module is enabled it also contains the active language. If
  5994. * $granularity was passed in, more parts are added.
  5995. */
  5996. function drupal_render_cid_parts($granularity = NULL) {
  5997. global $theme, $base_root, $user;
  5998. $cid_parts[] = $theme;
  5999. // If Locale is enabled but we have only one language we do not need it as cid
  6000. // part.
  6001. if (drupal_multilingual()) {
  6002. foreach (language_types_configurable() as $language_type) {
  6003. $cid_parts[] = $GLOBALS[$language_type]->language;
  6004. }
  6005. }
  6006. if (!empty($granularity)) {
  6007. $cache_per_role = $granularity & DRUPAL_CACHE_PER_ROLE;
  6008. $cache_per_user = $granularity & DRUPAL_CACHE_PER_USER;
  6009. // User 1 has special permissions outside of the role system, so when
  6010. // caching per role is requested, it should cache per user instead.
  6011. if ($user->uid == 1 && $cache_per_role) {
  6012. $cache_per_user = TRUE;
  6013. $cache_per_role = FALSE;
  6014. }
  6015. // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
  6016. // resource drag for sites with many users, so when a module is being
  6017. // equivocal, we favor the less expensive 'PER_ROLE' pattern.
  6018. if ($cache_per_role) {
  6019. $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
  6020. }
  6021. elseif ($cache_per_user) {
  6022. $cid_parts[] = "u.$user->uid";
  6023. }
  6024. if ($granularity & DRUPAL_CACHE_PER_PAGE) {
  6025. $cid_parts[] = $base_root . request_uri();
  6026. }
  6027. }
  6028. return $cid_parts;
  6029. }
  6030. /**
  6031. * Creates the cache ID for a renderable element.
  6032. *
  6033. * This creates the cache ID string, either by returning the #cache['cid']
  6034. * property if present or by building the cache ID out of the #cache['keys']
  6035. * and, optionally, the #cache['granularity'] properties.
  6036. *
  6037. * @param $elements
  6038. * A renderable array.
  6039. *
  6040. * @return
  6041. * The cache ID string, or FALSE if the element may not be cached.
  6042. */
  6043. function drupal_render_cid_create($elements) {
  6044. if (isset($elements['#cache']['cid'])) {
  6045. return $elements['#cache']['cid'];
  6046. }
  6047. elseif (isset($elements['#cache']['keys'])) {
  6048. $granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
  6049. // Merge in additional cache ID parts based provided by drupal_render_cid_parts().
  6050. $cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
  6051. return implode(':', $cid_parts);
  6052. }
  6053. return FALSE;
  6054. }
  6055. /**
  6056. * Function used by uasort to sort structured arrays by weight.
  6057. */
  6058. function element_sort($a, $b) {
  6059. $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
  6060. $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
  6061. if ($a_weight == $b_weight) {
  6062. return 0;
  6063. }
  6064. return ($a_weight < $b_weight) ? -1 : 1;
  6065. }
  6066. /**
  6067. * Array sorting callback; sorts elements by title.
  6068. */
  6069. function element_sort_by_title($a, $b) {
  6070. $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
  6071. $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
  6072. return strnatcasecmp($a_title, $b_title);
  6073. }
  6074. /**
  6075. * Retrieves the default properties for the defined element type.
  6076. *
  6077. * @param $type
  6078. * An element type as defined by hook_element_info().
  6079. */
  6080. function element_info($type) {
  6081. // Use the advanced drupal_static() pattern, since this is called very often.
  6082. static $drupal_static_fast;
  6083. if (!isset($drupal_static_fast)) {
  6084. $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
  6085. }
  6086. $cache = &$drupal_static_fast['cache'];
  6087. if (!isset($cache)) {
  6088. $cache = module_invoke_all('element_info');
  6089. foreach ($cache as $element_type => $info) {
  6090. $cache[$element_type]['#type'] = $element_type;
  6091. }
  6092. // Allow modules to alter the element type defaults.
  6093. drupal_alter('element_info', $cache);
  6094. }
  6095. return isset($cache[$type]) ? $cache[$type] : array();
  6096. }
  6097. /**
  6098. * Retrieves a single property for the defined element type.
  6099. *
  6100. * @param $type
  6101. * An element type as defined by hook_element_info().
  6102. * @param $property_name
  6103. * The property within the element type that should be returned.
  6104. * @param $default
  6105. * (Optional) The value to return if the element type does not specify a
  6106. * value for the property. Defaults to NULL.
  6107. */
  6108. function element_info_property($type, $property_name, $default = NULL) {
  6109. return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
  6110. }
  6111. /**
  6112. * Sorts a structured array by the 'weight' element.
  6113. *
  6114. * Note that the sorting is by the 'weight' array element, not by the render
  6115. * element property '#weight'.
  6116. *
  6117. * Callback for uasort() used in various functions.
  6118. *
  6119. * @param $a
  6120. * First item for comparison. The compared items should be associative arrays
  6121. * that optionally include a 'weight' element. For items without a 'weight'
  6122. * element, a default value of 0 will be used.
  6123. * @param $b
  6124. * Second item for comparison.
  6125. */
  6126. function drupal_sort_weight($a, $b) {
  6127. $a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
  6128. $b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
  6129. if ($a_weight == $b_weight) {
  6130. return 0;
  6131. }
  6132. return ($a_weight < $b_weight) ? -1 : 1;
  6133. }
  6134. /**
  6135. * Array sorting callback; sorts elements by 'title' key.
  6136. */
  6137. function drupal_sort_title($a, $b) {
  6138. if (!isset($b['title'])) {
  6139. return -1;
  6140. }
  6141. if (!isset($a['title'])) {
  6142. return 1;
  6143. }
  6144. return strcasecmp($a['title'], $b['title']);
  6145. }
  6146. /**
  6147. * Checks if the key is a property.
  6148. */
  6149. function element_property($key) {
  6150. return $key[0] == '#';
  6151. }
  6152. /**
  6153. * Gets properties of a structured array element (keys beginning with '#').
  6154. */
  6155. function element_properties($element) {
  6156. return array_filter(array_keys((array) $element), 'element_property');
  6157. }
  6158. /**
  6159. * Checks if the key is a child.
  6160. */
  6161. function element_child($key) {
  6162. return !isset($key[0]) || $key[0] != '#';
  6163. }
  6164. /**
  6165. * Identifies the children of an element array, optionally sorted by weight.
  6166. *
  6167. * The children of a element array are those key/value pairs whose key does
  6168. * not start with a '#'. See drupal_render() for details.
  6169. *
  6170. * @param $elements
  6171. * The element array whose children are to be identified.
  6172. * @param $sort
  6173. * Boolean to indicate whether the children should be sorted by weight.
  6174. *
  6175. * @return
  6176. * The array keys of the element's children.
  6177. */
  6178. function element_children(&$elements, $sort = FALSE) {
  6179. // Do not attempt to sort elements which have already been sorted.
  6180. $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
  6181. // Filter out properties from the element, leaving only children.
  6182. $children = array();
  6183. $sortable = FALSE;
  6184. foreach ($elements as $key => $value) {
  6185. if ($key === '' || $key[0] !== '#') {
  6186. $children[$key] = $value;
  6187. if (is_array($value) && isset($value['#weight'])) {
  6188. $sortable = TRUE;
  6189. }
  6190. }
  6191. }
  6192. // Sort the children if necessary.
  6193. if ($sort && $sortable) {
  6194. uasort($children, 'element_sort');
  6195. // Put the sorted children back into $elements in the correct order, to
  6196. // preserve sorting if the same element is passed through
  6197. // element_children() twice.
  6198. foreach ($children as $key => $child) {
  6199. unset($elements[$key]);
  6200. $elements[$key] = $child;
  6201. }
  6202. $elements['#sorted'] = TRUE;
  6203. }
  6204. return array_keys($children);
  6205. }
  6206. /**
  6207. * Returns the visible children of an element.
  6208. *
  6209. * @param $elements
  6210. * The parent element.
  6211. *
  6212. * @return
  6213. * The array keys of the element's visible children.
  6214. */
  6215. function element_get_visible_children(array $elements) {
  6216. $visible_children = array();
  6217. foreach (element_children($elements) as $key) {
  6218. $child = $elements[$key];
  6219. // Skip un-accessible children.
  6220. if (isset($child['#access']) && !$child['#access']) {
  6221. continue;
  6222. }
  6223. // Skip value and hidden elements, since they are not rendered.
  6224. if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
  6225. continue;
  6226. }
  6227. $visible_children[$key] = $child;
  6228. }
  6229. return array_keys($visible_children);
  6230. }
  6231. /**
  6232. * Sets HTML attributes based on element properties.
  6233. *
  6234. * @param $element
  6235. * The renderable element to process.
  6236. * @param $map
  6237. * An associative array whose keys are element property names and whose values
  6238. * are the HTML attribute names to set for corresponding the property; e.g.,
  6239. * array('#propertyname' => 'attributename'). If both names are identical
  6240. * except for the leading '#', then an attribute name value is sufficient and
  6241. * no property name needs to be specified.
  6242. */
  6243. function element_set_attributes(array &$element, array $map) {
  6244. foreach ($map as $property => $attribute) {
  6245. // If the key is numeric, the attribute name needs to be taken over.
  6246. if (is_int($property)) {
  6247. $property = '#' . $attribute;
  6248. }
  6249. // Do not overwrite already existing attributes.
  6250. if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
  6251. $element['#attributes'][$attribute] = $element[$property];
  6252. }
  6253. }
  6254. }
  6255. /**
  6256. * Recursively computes the difference of arrays with additional index check.
  6257. *
  6258. * This is a version of array_diff_assoc() that supports multidimensional
  6259. * arrays.
  6260. *
  6261. * @param array $array1
  6262. * The array to compare from.
  6263. * @param array $array2
  6264. * The array to compare to.
  6265. *
  6266. * @return array
  6267. * Returns an array containing all the values from array1 that are not present
  6268. * in array2.
  6269. */
  6270. function drupal_array_diff_assoc_recursive($array1, $array2) {
  6271. $difference = array();
  6272. foreach ($array1 as $key => $value) {
  6273. if (is_array($value)) {
  6274. if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
  6275. $difference[$key] = $value;
  6276. }
  6277. else {
  6278. $new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
  6279. if (!empty($new_diff)) {
  6280. $difference[$key] = $new_diff;
  6281. }
  6282. }
  6283. }
  6284. elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
  6285. $difference[$key] = $value;
  6286. }
  6287. }
  6288. return $difference;
  6289. }
  6290. /**
  6291. * Sets a value in a nested array with variable depth.
  6292. *
  6293. * This helper function should be used when the depth of the array element you
  6294. * are changing may vary (that is, the number of parent keys is variable). It
  6295. * is primarily used for form structures and renderable arrays.
  6296. *
  6297. * Example:
  6298. * @code
  6299. * // Assume you have a 'signature' element somewhere in a form. It might be:
  6300. * $form['signature_settings']['signature'] = array(
  6301. * '#type' => 'text_format',
  6302. * '#title' => t('Signature'),
  6303. * );
  6304. * // Or, it might be further nested:
  6305. * $form['signature_settings']['user']['signature'] = array(
  6306. * '#type' => 'text_format',
  6307. * '#title' => t('Signature'),
  6308. * );
  6309. * @endcode
  6310. *
  6311. * To deal with the situation, the code needs to figure out the route to the
  6312. * element, given an array of parents that is either
  6313. * @code array('signature_settings', 'signature') @endcode in the first case or
  6314. * @code array('signature_settings', 'user', 'signature') @endcode in the second
  6315. * case.
  6316. *
  6317. * Without this helper function the only way to set the signature element in one
  6318. * line would be using eval(), which should be avoided:
  6319. * @code
  6320. * // Do not do this! Avoid eval().
  6321. * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
  6322. * @endcode
  6323. *
  6324. * Instead, use this helper function:
  6325. * @code
  6326. * drupal_array_set_nested_value($form, $parents, $element);
  6327. * @endcode
  6328. *
  6329. * However if the number of array parent keys is static, the value should always
  6330. * be set directly rather than calling this function. For instance, for the
  6331. * first example we could just do:
  6332. * @code
  6333. * $form['signature_settings']['signature'] = $element;
  6334. * @endcode
  6335. *
  6336. * @param $array
  6337. * A reference to the array to modify.
  6338. * @param $parents
  6339. * An array of parent keys, starting with the outermost key.
  6340. * @param $value
  6341. * The value to set.
  6342. * @param $force
  6343. * (Optional) If TRUE, the value is forced into the structure even if it
  6344. * requires the deletion of an already existing non-array parent value. If
  6345. * FALSE, PHP throws an error if trying to add into a value that is not an
  6346. * array. Defaults to FALSE.
  6347. *
  6348. * @see drupal_array_get_nested_value()
  6349. */
  6350. function drupal_array_set_nested_value(array &$array, array $parents, $value, $force = FALSE) {
  6351. $ref = &$array;
  6352. foreach ($parents as $parent) {
  6353. // PHP auto-creates container arrays and NULL entries without error if $ref
  6354. // is NULL, but throws an error if $ref is set, but not an array.
  6355. if ($force && isset($ref) && !is_array($ref)) {
  6356. $ref = array();
  6357. }
  6358. $ref = &$ref[$parent];
  6359. }
  6360. $ref = $value;
  6361. }
  6362. /**
  6363. * Retrieves a value from a nested array with variable depth.
  6364. *
  6365. * This helper function should be used when the depth of the array element being
  6366. * retrieved may vary (that is, the number of parent keys is variable). It is
  6367. * primarily used for form structures and renderable arrays.
  6368. *
  6369. * Without this helper function the only way to get a nested array value with
  6370. * variable depth in one line would be using eval(), which should be avoided:
  6371. * @code
  6372. * // Do not do this! Avoid eval().
  6373. * // May also throw a PHP notice, if the variable array keys do not exist.
  6374. * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
  6375. * @endcode
  6376. *
  6377. * Instead, use this helper function:
  6378. * @code
  6379. * $value = drupal_array_get_nested_value($form, $parents);
  6380. * @endcode
  6381. *
  6382. * A return value of NULL is ambiguous, and can mean either that the requested
  6383. * key does not exist, or that the actual value is NULL. If it is required to
  6384. * know whether the nested array key actually exists, pass a third argument that
  6385. * is altered by reference:
  6386. * @code
  6387. * $key_exists = NULL;
  6388. * $value = drupal_array_get_nested_value($form, $parents, $key_exists);
  6389. * if ($key_exists) {
  6390. * // ... do something with $value ...
  6391. * }
  6392. * @endcode
  6393. *
  6394. * However if the number of array parent keys is static, the value should always
  6395. * be retrieved directly rather than calling this function. For instance:
  6396. * @code
  6397. * $value = $form['signature_settings']['signature'];
  6398. * @endcode
  6399. *
  6400. * @param $array
  6401. * The array from which to get the value.
  6402. * @param $parents
  6403. * An array of parent keys of the value, starting with the outermost key.
  6404. * @param $key_exists
  6405. * (optional) If given, an already defined variable that is altered by
  6406. * reference.
  6407. *
  6408. * @return
  6409. * The requested nested value. Possibly NULL if the value is NULL or not all
  6410. * nested parent keys exist. $key_exists is altered by reference and is a
  6411. * Boolean that indicates whether all nested parent keys exist (TRUE) or not
  6412. * (FALSE). This allows to distinguish between the two possibilities when NULL
  6413. * is returned.
  6414. *
  6415. * @see drupal_array_set_nested_value()
  6416. */
  6417. function &drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
  6418. $ref = &$array;
  6419. foreach ($parents as $parent) {
  6420. if (is_array($ref) && array_key_exists($parent, $ref)) {
  6421. $ref = &$ref[$parent];
  6422. }
  6423. else {
  6424. $key_exists = FALSE;
  6425. $null = NULL;
  6426. return $null;
  6427. }
  6428. }
  6429. $key_exists = TRUE;
  6430. return $ref;
  6431. }
  6432. /**
  6433. * Determines whether a nested array contains the requested keys.
  6434. *
  6435. * This helper function should be used when the depth of the array element to be
  6436. * checked may vary (that is, the number of parent keys is variable). See
  6437. * drupal_array_set_nested_value() for details. It is primarily used for form
  6438. * structures and renderable arrays.
  6439. *
  6440. * If it is required to also get the value of the checked nested key, use
  6441. * drupal_array_get_nested_value() instead.
  6442. *
  6443. * If the number of array parent keys is static, this helper function is
  6444. * unnecessary and the following code can be used instead:
  6445. * @code
  6446. * $value_exists = isset($form['signature_settings']['signature']);
  6447. * $key_exists = array_key_exists('signature', $form['signature_settings']);
  6448. * @endcode
  6449. *
  6450. * @param $array
  6451. * The array with the value to check for.
  6452. * @param $parents
  6453. * An array of parent keys of the value, starting with the outermost key.
  6454. *
  6455. * @return
  6456. * TRUE if all the parent keys exist, FALSE otherwise.
  6457. *
  6458. * @see drupal_array_get_nested_value()
  6459. */
  6460. function drupal_array_nested_key_exists(array $array, array $parents) {
  6461. // Although this function is similar to PHP's array_key_exists(), its
  6462. // arguments should be consistent with drupal_array_get_nested_value().
  6463. $key_exists = NULL;
  6464. drupal_array_get_nested_value($array, $parents, $key_exists);
  6465. return $key_exists;
  6466. }
  6467. /**
  6468. * Provides theme registration for themes across .inc files.
  6469. */
  6470. function drupal_common_theme() {
  6471. return array(
  6472. // From theme.inc.
  6473. 'html' => array(
  6474. 'render element' => 'page',
  6475. 'template' => 'html',
  6476. ),
  6477. 'page' => array(
  6478. 'render element' => 'page',
  6479. 'template' => 'page',
  6480. ),
  6481. 'region' => array(
  6482. 'render element' => 'elements',
  6483. 'template' => 'region',
  6484. ),
  6485. 'status_messages' => array(
  6486. 'variables' => array('display' => NULL),
  6487. ),
  6488. 'link' => array(
  6489. 'variables' => array('text' => NULL, 'path' => NULL, 'options' => array()),
  6490. ),
  6491. 'links' => array(
  6492. 'variables' => array('links' => NULL, 'attributes' => array('class' => array('links')), 'heading' => array()),
  6493. ),
  6494. 'image' => array(
  6495. // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
  6496. // allows the alt attribute to be omitted in some cases. Therefore,
  6497. // default the alt attribute to an empty string, but allow code calling
  6498. // theme('image') to pass explicit NULL for it to be omitted. Usually,
  6499. // neither omission nor an empty string satisfies accessibility
  6500. // requirements, so it is strongly encouraged for code calling
  6501. // theme('image') to pass a meaningful value for the alt variable.
  6502. // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
  6503. // - http://www.w3.org/TR/xhtml1/dtds.html
  6504. // - http://dev.w3.org/html5/spec/Overview.html#alt
  6505. // The title attribute is optional in all cases, so it is omitted by
  6506. // default.
  6507. 'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
  6508. ),
  6509. 'breadcrumb' => array(
  6510. 'variables' => array('breadcrumb' => NULL),
  6511. ),
  6512. 'help' => array(
  6513. 'variables' => array(),
  6514. ),
  6515. 'table' => array(
  6516. 'variables' => array(
  6517. 'header' => NULL,
  6518. 'footer' => NULL,
  6519. 'rows' => NULL,
  6520. 'attributes' => array(),
  6521. 'caption' => NULL,
  6522. 'colgroups' => array(),
  6523. 'sticky' => TRUE,
  6524. 'empty' => '',
  6525. ),
  6526. ),
  6527. 'tablesort_indicator' => array(
  6528. 'variables' => array('style' => NULL),
  6529. ),
  6530. 'mark' => array(
  6531. 'variables' => array('type' => MARK_NEW),
  6532. ),
  6533. 'item_list' => array(
  6534. 'variables' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => array()),
  6535. ),
  6536. 'more_help_link' => array(
  6537. 'variables' => array('url' => NULL),
  6538. ),
  6539. 'feed_icon' => array(
  6540. 'variables' => array('url' => NULL, 'title' => NULL),
  6541. ),
  6542. 'more_link' => array(
  6543. 'variables' => array('url' => NULL, 'title' => NULL)
  6544. ),
  6545. 'username' => array(
  6546. 'variables' => array('account' => NULL),
  6547. ),
  6548. 'progress_bar' => array(
  6549. 'variables' => array('percent' => NULL, 'message' => NULL),
  6550. ),
  6551. 'indentation' => array(
  6552. 'variables' => array('size' => 1),
  6553. ),
  6554. 'html_tag' => array(
  6555. 'render element' => 'element',
  6556. ),
  6557. // From theme.maintenance.inc.
  6558. 'maintenance_page' => array(
  6559. 'variables' => array('content' => NULL, 'show_messages' => TRUE),
  6560. 'template' => 'maintenance-page',
  6561. ),
  6562. 'update_page' => array(
  6563. 'variables' => array('content' => NULL, 'show_messages' => TRUE),
  6564. ),
  6565. 'install_page' => array(
  6566. 'variables' => array('content' => NULL),
  6567. ),
  6568. 'task_list' => array(
  6569. 'variables' => array('items' => NULL, 'active' => NULL),
  6570. ),
  6571. 'authorize_message' => array(
  6572. 'variables' => array('message' => NULL, 'success' => TRUE),
  6573. ),
  6574. 'authorize_report' => array(
  6575. 'variables' => array('messages' => array()),
  6576. ),
  6577. // From pager.inc.
  6578. 'pager' => array(
  6579. 'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array(), 'quantity' => 9),
  6580. ),
  6581. 'pager_first' => array(
  6582. 'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
  6583. ),
  6584. 'pager_previous' => array(
  6585. 'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  6586. ),
  6587. 'pager_next' => array(
  6588. 'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  6589. ),
  6590. 'pager_last' => array(
  6591. 'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
  6592. ),
  6593. 'pager_link' => array(
  6594. 'variables' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
  6595. ),
  6596. // From menu.inc.
  6597. 'menu_link' => array(
  6598. 'render element' => 'element',
  6599. ),
  6600. 'menu_tree' => array(
  6601. 'render element' => 'tree',
  6602. ),
  6603. 'menu_local_task' => array(
  6604. 'render element' => 'element',
  6605. ),
  6606. 'menu_local_action' => array(
  6607. 'render element' => 'element',
  6608. ),
  6609. 'menu_local_tasks' => array(
  6610. 'variables' => array('primary' => array(), 'secondary' => array()),
  6611. ),
  6612. // From form.inc.
  6613. 'select' => array(
  6614. 'render element' => 'element',
  6615. ),
  6616. 'fieldset' => array(
  6617. 'render element' => 'element',
  6618. ),
  6619. 'radio' => array(
  6620. 'render element' => 'element',
  6621. ),
  6622. 'radios' => array(
  6623. 'render element' => 'element',
  6624. ),
  6625. 'date' => array(
  6626. 'render element' => 'element',
  6627. ),
  6628. 'exposed_filters' => array(
  6629. 'render element' => 'form',
  6630. ),
  6631. 'checkbox' => array(
  6632. 'render element' => 'element',
  6633. ),
  6634. 'checkboxes' => array(
  6635. 'render element' => 'element',
  6636. ),
  6637. 'button' => array(
  6638. 'render element' => 'element',
  6639. ),
  6640. 'image_button' => array(
  6641. 'render element' => 'element',
  6642. ),
  6643. 'hidden' => array(
  6644. 'render element' => 'element',
  6645. ),
  6646. 'textfield' => array(
  6647. 'render element' => 'element',
  6648. ),
  6649. 'form' => array(
  6650. 'render element' => 'element',
  6651. ),
  6652. 'textarea' => array(
  6653. 'render element' => 'element',
  6654. ),
  6655. 'password' => array(
  6656. 'render element' => 'element',
  6657. ),
  6658. 'file' => array(
  6659. 'render element' => 'element',
  6660. ),
  6661. 'tableselect' => array(
  6662. 'render element' => 'element',
  6663. ),
  6664. 'form_element' => array(
  6665. 'render element' => 'element',
  6666. ),
  6667. 'form_required_marker' => array(
  6668. 'render element' => 'element',
  6669. ),
  6670. 'form_element_label' => array(
  6671. 'render element' => 'element',
  6672. ),
  6673. 'vertical_tabs' => array(
  6674. 'render element' => 'element',
  6675. ),
  6676. 'container' => array(
  6677. 'render element' => 'element',
  6678. ),
  6679. );
  6680. }
  6681. /**
  6682. * @addtogroup schemaapi
  6683. * @{
  6684. */
  6685. /**
  6686. * Creates all tables defined in a module's hook_schema().
  6687. *
  6688. * Note: This function does not pass the module's schema through
  6689. * hook_schema_alter(). The module's tables will be created exactly as the
  6690. * module defines them.
  6691. *
  6692. * @param $module
  6693. * The module for which the tables will be created.
  6694. */
  6695. function drupal_install_schema($module) {
  6696. $schema = drupal_get_schema_unprocessed($module);
  6697. _drupal_schema_initialize($schema, $module, FALSE);
  6698. foreach ($schema as $name => $table) {
  6699. db_create_table($name, $table);
  6700. }
  6701. }
  6702. /**
  6703. * Removes all tables defined in a module's hook_schema().
  6704. *
  6705. * Note: This function does not pass the module's schema through
  6706. * hook_schema_alter(). The module's tables will be created exactly as the
  6707. * module defines them.
  6708. *
  6709. * @param $module
  6710. * The module for which the tables will be removed.
  6711. *
  6712. * @return
  6713. * An array of arrays with the following key/value pairs:
  6714. * - success: a boolean indicating whether the query succeeded.
  6715. * - query: the SQL query(s) executed, passed through check_plain().
  6716. */
  6717. function drupal_uninstall_schema($module) {
  6718. $schema = drupal_get_schema_unprocessed($module);
  6719. _drupal_schema_initialize($schema, $module, FALSE);
  6720. foreach ($schema as $table) {
  6721. if (db_table_exists($table['name'])) {
  6722. db_drop_table($table['name']);
  6723. }
  6724. }
  6725. }
  6726. /**
  6727. * Returns the unprocessed and unaltered version of a module's schema.
  6728. *
  6729. * Use this function only if you explicitly need the original
  6730. * specification of a schema, as it was defined in a module's
  6731. * hook_schema(). No additional default values will be set,
  6732. * hook_schema_alter() is not invoked and these unprocessed
  6733. * definitions won't be cached. To retrieve the schema after
  6734. * hook_schema_alter() has been invoked use drupal_get_schema().
  6735. *
  6736. * This function can be used to retrieve a schema specification in
  6737. * hook_schema(), so it allows you to derive your tables from existing
  6738. * specifications.
  6739. *
  6740. * It is also used by drupal_install_schema() and
  6741. * drupal_uninstall_schema() to ensure that a module's tables are
  6742. * created exactly as specified without any changes introduced by a
  6743. * module that implements hook_schema_alter().
  6744. *
  6745. * @param $module
  6746. * The module to which the table belongs.
  6747. * @param $table
  6748. * The name of the table. If not given, the module's complete schema
  6749. * is returned.
  6750. */
  6751. function drupal_get_schema_unprocessed($module, $table = NULL) {
  6752. // Load the .install file to get hook_schema.
  6753. module_load_install($module);
  6754. $schema = module_invoke($module, 'schema');
  6755. if (isset($table) && isset($schema[$table])) {
  6756. return $schema[$table];
  6757. }
  6758. elseif (!empty($schema)) {
  6759. return $schema;
  6760. }
  6761. return array();
  6762. }
  6763. /**
  6764. * Fills in required default values for table definitions from hook_schema().
  6765. *
  6766. * @param $schema
  6767. * The schema definition array as it was returned by the module's
  6768. * hook_schema().
  6769. * @param $module
  6770. * The module for which hook_schema() was invoked.
  6771. * @param $remove_descriptions
  6772. * (optional) Whether to additionally remove 'description' keys of all tables
  6773. * and fields to improve performance of serialize() and unserialize().
  6774. * Defaults to TRUE.
  6775. */
  6776. function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
  6777. // Set the name and module key for all tables.
  6778. foreach ($schema as $name => &$table) {
  6779. if (empty($table['module'])) {
  6780. $table['module'] = $module;
  6781. }
  6782. if (!isset($table['name'])) {
  6783. $table['name'] = $name;
  6784. }
  6785. if ($remove_descriptions) {
  6786. unset($table['description']);
  6787. foreach ($table['fields'] as &$field) {
  6788. unset($field['description']);
  6789. }
  6790. }
  6791. }
  6792. }
  6793. /**
  6794. * Retrieves the type for every field in a table schema.
  6795. *
  6796. * @param $table
  6797. * The name of the table from which to retrieve type information.
  6798. *
  6799. * @return
  6800. * An array of types, keyed by field name.
  6801. */
  6802. function drupal_schema_field_types($table) {
  6803. $table_schema = drupal_get_schema($table);
  6804. $field_types = array();
  6805. foreach ($table_schema['fields'] as $field_name => $field_info) {
  6806. $field_types[$field_name] = isset($field_info['type']) ? $field_info['type'] : NULL;
  6807. }
  6808. return $field_types;
  6809. }
  6810. /**
  6811. * Retrieves a list of fields from a table schema.
  6812. *
  6813. * The returned list is suitable for use in an SQL query.
  6814. *
  6815. * @param $table
  6816. * The name of the table from which to retrieve fields.
  6817. * @param
  6818. * An optional prefix to to all fields.
  6819. *
  6820. * @return An array of fields.
  6821. */
  6822. function drupal_schema_fields_sql($table, $prefix = NULL) {
  6823. $schema = drupal_get_schema($table);
  6824. $fields = array_keys($schema['fields']);
  6825. if ($prefix) {
  6826. $columns = array();
  6827. foreach ($fields as $field) {
  6828. $columns[] = "$prefix.$field";
  6829. }
  6830. return $columns;
  6831. }
  6832. else {
  6833. return $fields;
  6834. }
  6835. }
  6836. /**
  6837. * Saves (inserts or updates) a record to the database based upon the schema.
  6838. *
  6839. * Do not use drupal_write_record() within hook_update_N() functions, since the
  6840. * database schema cannot be relied upon when a user is running a series of
  6841. * updates. Instead, use db_insert() or db_update() to save the record.
  6842. *
  6843. * @param $table
  6844. * The name of the table; this must be defined by a hook_schema()
  6845. * implementation.
  6846. * @param $record
  6847. * An object or array representing the record to write, passed in by
  6848. * reference. If inserting a new record, values not provided in $record will
  6849. * be populated in $record and in the database with the default values from
  6850. * the schema, as well as a single serial (auto-increment) field (if present).
  6851. * If updating an existing record, only provided values are updated in the
  6852. * database, and $record is not modified.
  6853. * @param $primary_keys
  6854. * To indicate that this is a new record to be inserted, omit this argument.
  6855. * If this is an update, this argument specifies the primary keys' field
  6856. * names. If there is only 1 field in the key, you may pass in a string; if
  6857. * there are multiple fields in the key, pass in an array.
  6858. *
  6859. * @return
  6860. * If the record insert or update failed, returns FALSE. If it succeeded,
  6861. * returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
  6862. */
  6863. function drupal_write_record($table, &$record, $primary_keys = array()) {
  6864. // Standardize $primary_keys to an array.
  6865. if (is_string($primary_keys)) {
  6866. $primary_keys = array($primary_keys);
  6867. }
  6868. $schema = drupal_get_schema($table);
  6869. if (empty($schema)) {
  6870. return FALSE;
  6871. }
  6872. $object = (object) $record;
  6873. $fields = array();
  6874. // Go through the schema to determine fields to write.
  6875. foreach ($schema['fields'] as $field => $info) {
  6876. if ($info['type'] == 'serial') {
  6877. // Skip serial types if we are updating.
  6878. if (!empty($primary_keys)) {
  6879. continue;
  6880. }
  6881. // Track serial field so we can helpfully populate them after the query.
  6882. // NOTE: Each table should come with one serial field only.
  6883. $serial = $field;
  6884. }
  6885. // Skip field if it is in $primary_keys as it is unnecessary to update a
  6886. // field to the value it is already set to.
  6887. if (in_array($field, $primary_keys)) {
  6888. continue;
  6889. }
  6890. if (!property_exists($object, $field)) {
  6891. // Skip fields that are not provided, default values are already known
  6892. // by the database.
  6893. continue;
  6894. }
  6895. // Build array of fields to update or insert.
  6896. if (empty($info['serialize'])) {
  6897. $fields[$field] = $object->$field;
  6898. }
  6899. else {
  6900. $fields[$field] = serialize($object->$field);
  6901. }
  6902. // Type cast to proper datatype, except when the value is NULL and the
  6903. // column allows this.
  6904. //
  6905. // MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
  6906. // into an integer column, but PostgreSQL PDO does not. Also type cast NULL
  6907. // when the column does not allow this.
  6908. if (isset($object->$field) || !empty($info['not null'])) {
  6909. if ($info['type'] == 'int' || $info['type'] == 'serial') {
  6910. $fields[$field] = (int) $fields[$field];
  6911. }
  6912. elseif ($info['type'] == 'float') {
  6913. $fields[$field] = (float) $fields[$field];
  6914. }
  6915. else {
  6916. $fields[$field] = (string) $fields[$field];
  6917. }
  6918. }
  6919. }
  6920. if (empty($fields)) {
  6921. return;
  6922. }
  6923. // Build the SQL.
  6924. if (empty($primary_keys)) {
  6925. // We are doing an insert.
  6926. $options = array('return' => Database::RETURN_INSERT_ID);
  6927. if (isset($serial) && isset($fields[$serial])) {
  6928. // If the serial column has been explicitly set with an ID, then we don't
  6929. // require the database to return the last insert id.
  6930. if ($fields[$serial]) {
  6931. $options['return'] = Database::RETURN_AFFECTED;
  6932. }
  6933. // If a serial column does exist with no value (i.e. 0) then remove it as
  6934. // the database will insert the correct value for us.
  6935. else {
  6936. unset($fields[$serial]);
  6937. }
  6938. }
  6939. $query = db_insert($table, $options)->fields($fields);
  6940. $return = SAVED_NEW;
  6941. }
  6942. else {
  6943. $query = db_update($table)->fields($fields);
  6944. foreach ($primary_keys as $key) {
  6945. $query->condition($key, $object->$key);
  6946. }
  6947. $return = SAVED_UPDATED;
  6948. }
  6949. // Execute the SQL.
  6950. if ($query_return = $query->execute()) {
  6951. if (isset($serial)) {
  6952. // If the database was not told to return the last insert id, it will be
  6953. // because we already know it.
  6954. if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
  6955. $object->$serial = $fields[$serial];
  6956. }
  6957. else {
  6958. $object->$serial = $query_return;
  6959. }
  6960. }
  6961. }
  6962. // If we have a single-field primary key but got no insert ID, the
  6963. // query failed. Note that we explicitly check for FALSE, because
  6964. // a valid update query which doesn't change any values will return
  6965. // zero (0) affected rows.
  6966. elseif ($query_return === FALSE && count($primary_keys) == 1) {
  6967. $return = FALSE;
  6968. }
  6969. // If we are inserting, populate empty fields with default values.
  6970. if (empty($primary_keys)) {
  6971. foreach ($schema['fields'] as $field => $info) {
  6972. if (isset($info['default']) && !property_exists($object, $field)) {
  6973. $object->$field = $info['default'];
  6974. }
  6975. }
  6976. }
  6977. // If we began with an array, convert back.
  6978. if (is_array($record)) {
  6979. $record = (array) $object;
  6980. }
  6981. return $return;
  6982. }
  6983. /**
  6984. * @} End of "addtogroup schemaapi".
  6985. */
  6986. /**
  6987. * Parses Drupal module and theme .info files.
  6988. *
  6989. * Info files are NOT for placing arbitrary theme and module-specific settings.
  6990. * Use variable_get() and variable_set() for that.
  6991. *
  6992. * Information stored in a module .info file:
  6993. * - name: The real name of the module for display purposes.
  6994. * - description: A brief description of the module.
  6995. * - dependencies: An array of dependency strings. Each is in the form
  6996. * 'project:module (versions)'; with the following meanings:
  6997. * - project: (optional) Project shortname, recommended to ensure uniqueness,
  6998. * if the module is part of a project hosted on drupal.org. If omitted,
  6999. * also omit the : that follows. The project name is currently ignored by
  7000. * Drupal core but is used for automated testing.
  7001. * - module: (required) Module shortname within the project.
  7002. * - (versions): Optional version information, consisting of one or more
  7003. * comma-separated operator/value pairs or simply version numbers, which
  7004. * can contain "x" as a wildcard. Examples: (>=7.22, <7.28), (7.x-3.x).
  7005. * - package: The name of the package of modules this module belongs to.
  7006. *
  7007. * See forum.info for an example of a module .info file.
  7008. *
  7009. * Information stored in a theme .info file:
  7010. * - name: The real name of the theme for display purposes.
  7011. * - description: Brief description.
  7012. * - screenshot: Path to screenshot relative to the theme's .info file.
  7013. * - engine: Theme engine; typically phptemplate.
  7014. * - base: Name of a base theme, if applicable; e.g., base = zen.
  7015. * - regions: Listed regions; e.g., region[left] = Left sidebar.
  7016. * - features: Features available; e.g., features[] = logo.
  7017. * - stylesheets: Theme stylesheets; e.g., stylesheets[all][] = my-style.css.
  7018. * - scripts: Theme scripts; e.g., scripts[] = my-script.js.
  7019. *
  7020. * See bartik.info for an example of a theme .info file.
  7021. *
  7022. * @param $filename
  7023. * The file we are parsing. Accepts file with relative or absolute path.
  7024. *
  7025. * @return
  7026. * The info array.
  7027. *
  7028. * @see drupal_parse_info_format()
  7029. */
  7030. function drupal_parse_info_file($filename) {
  7031. $info = &drupal_static(__FUNCTION__, array());
  7032. if (!isset($info[$filename])) {
  7033. if (!file_exists($filename)) {
  7034. $info[$filename] = array();
  7035. }
  7036. else {
  7037. $data = file_get_contents($filename);
  7038. $info[$filename] = drupal_parse_info_format($data);
  7039. }
  7040. }
  7041. return $info[$filename];
  7042. }
  7043. /**
  7044. * Parses data in Drupal's .info format.
  7045. *
  7046. * Data should be in an .ini-like format to specify values. White-space
  7047. * generally doesn't matter, except inside values:
  7048. * @code
  7049. * key = value
  7050. * key = "value"
  7051. * key = 'value'
  7052. * key = "multi-line
  7053. * value"
  7054. * key = 'multi-line
  7055. * value'
  7056. * key
  7057. * =
  7058. * 'value'
  7059. * @endcode
  7060. *
  7061. * Arrays are created using a HTTP GET alike syntax:
  7062. * @code
  7063. * key[] = "numeric array"
  7064. * key[index] = "associative array"
  7065. * key[index][] = "nested numeric array"
  7066. * key[index][index] = "nested associative array"
  7067. * @endcode
  7068. *
  7069. * PHP constants are substituted in, but only when used as the entire value.
  7070. * Comments should start with a semi-colon at the beginning of a line.
  7071. *
  7072. * @param $data
  7073. * A string to parse.
  7074. *
  7075. * @return
  7076. * The info array.
  7077. *
  7078. * @see drupal_parse_info_file()
  7079. */
  7080. function drupal_parse_info_format($data) {
  7081. $info = array();
  7082. if (preg_match_all('
  7083. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  7084. ((?:
  7085. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  7086. \[[^\[\]]*\] # unless they are balanced and not nested
  7087. )+?)
  7088. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  7089. (?:
  7090. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  7091. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  7092. ([^\r\n]*?) # Non-quoted string
  7093. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  7094. @msx', $data, $matches, PREG_SET_ORDER)) {
  7095. foreach ($matches as $match) {
  7096. // Fetch the key and value string.
  7097. $i = 0;
  7098. foreach (array('key', 'value1', 'value2', 'value3') as $var) {
  7099. $$var = isset($match[++$i]) ? $match[$i] : '';
  7100. }
  7101. $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
  7102. // Parse array syntax.
  7103. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  7104. $last = array_pop($keys);
  7105. $parent = &$info;
  7106. // Create nested arrays.
  7107. foreach ($keys as $key) {
  7108. if ($key == '') {
  7109. $key = count($parent);
  7110. }
  7111. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  7112. $parent[$key] = array();
  7113. }
  7114. $parent = &$parent[$key];
  7115. }
  7116. // Handle PHP constants.
  7117. if (preg_match('/^\w+$/i', $value) && defined($value)) {
  7118. $value = constant($value);
  7119. }
  7120. // Insert actual value.
  7121. if ($last == '') {
  7122. $last = count($parent);
  7123. }
  7124. $parent[$last] = $value;
  7125. }
  7126. }
  7127. return $info;
  7128. }
  7129. /**
  7130. * Returns a list of severity levels, as defined in RFC 3164.
  7131. *
  7132. * @return
  7133. * Array of the possible severity levels for log messages.
  7134. *
  7135. * @see http://www.ietf.org/rfc/rfc3164.txt
  7136. * @see watchdog()
  7137. * @ingroup logging_severity_levels
  7138. */
  7139. function watchdog_severity_levels() {
  7140. return array(
  7141. WATCHDOG_EMERGENCY => t('emergency'),
  7142. WATCHDOG_ALERT => t('alert'),
  7143. WATCHDOG_CRITICAL => t('critical'),
  7144. WATCHDOG_ERROR => t('error'),
  7145. WATCHDOG_WARNING => t('warning'),
  7146. WATCHDOG_NOTICE => t('notice'),
  7147. WATCHDOG_INFO => t('info'),
  7148. WATCHDOG_DEBUG => t('debug'),
  7149. );
  7150. }
  7151. /**
  7152. * Explodes a string of tags into an array.
  7153. *
  7154. * @see drupal_implode_tags()
  7155. */
  7156. function drupal_explode_tags($tags) {
  7157. // This regexp allows the following types of user input:
  7158. // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
  7159. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  7160. preg_match_all($regexp, $tags, $matches);
  7161. $typed_tags = array_unique($matches[1]);
  7162. $tags = array();
  7163. foreach ($typed_tags as $tag) {
  7164. // If a user has escaped a term (to demonstrate that it is a group,
  7165. // or includes a comma or quote character), we remove the escape
  7166. // formatting so to save the term into the database as the user intends.
  7167. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
  7168. if ($tag != "") {
  7169. $tags[] = $tag;
  7170. }
  7171. }
  7172. return $tags;
  7173. }
  7174. /**
  7175. * Implodes an array of tags into a string.
  7176. *
  7177. * @see drupal_explode_tags()
  7178. */
  7179. function drupal_implode_tags($tags) {
  7180. $encoded_tags = array();
  7181. foreach ($tags as $tag) {
  7182. // Commas and quotes in tag names are special cases, so encode them.
  7183. if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
  7184. $tag = '"' . str_replace('"', '""', $tag) . '"';
  7185. }
  7186. $encoded_tags[] = $tag;
  7187. }
  7188. return implode(', ', $encoded_tags);
  7189. }
  7190. /**
  7191. * Flushes all cached data on the site.
  7192. *
  7193. * Empties cache tables, rebuilds the menu cache and theme registries, and
  7194. * invokes a hook so that other modules' cache data can be cleared as well.
  7195. */
  7196. function drupal_flush_all_caches() {
  7197. // Change query-strings on css/js files to enforce reload for all users.
  7198. _drupal_flush_css_js();
  7199. registry_rebuild();
  7200. drupal_clear_css_cache();
  7201. drupal_clear_js_cache();
  7202. // Rebuild the theme data. Note that the module data is rebuilt above, as
  7203. // part of registry_rebuild().
  7204. system_rebuild_theme_data();
  7205. drupal_theme_rebuild();
  7206. entity_info_cache_clear();
  7207. node_types_rebuild();
  7208. // node_menu() defines menu items based on node types so it needs to come
  7209. // after node types are rebuilt.
  7210. menu_rebuild();
  7211. // Synchronize to catch any actions that were added or removed.
  7212. actions_synchronize();
  7213. // Don't clear cache_form - in-progress form submissions may break.
  7214. // Ordered so clearing the page cache will always be the last action.
  7215. $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
  7216. $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  7217. foreach ($cache_tables as $table) {
  7218. cache_clear_all('*', $table, TRUE);
  7219. }
  7220. // Rebuild the bootstrap module list. We do this here so that developers
  7221. // can get new hook_boot() implementations registered without having to
  7222. // write a hook_update_N() function.
  7223. _system_update_bootstrap_status();
  7224. }
  7225. /**
  7226. * Changes the dummy query string added to all CSS and JavaScript files.
  7227. *
  7228. * Changing the dummy query string appended to CSS and JavaScript files forces
  7229. * all browsers to reload fresh files.
  7230. */
  7231. function _drupal_flush_css_js() {
  7232. // The timestamp is converted to base 36 in order to make it more compact.
  7233. variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
  7234. }
  7235. /**
  7236. * Outputs debug information.
  7237. *
  7238. * The debug information is passed on to trigger_error() after being converted
  7239. * to a string using _drupal_debug_message().
  7240. *
  7241. * @param $data
  7242. * Data to be output.
  7243. * @param $label
  7244. * Label to prefix the data.
  7245. * @param $print_r
  7246. * Flag to switch between print_r() and var_export() for data conversion to
  7247. * string. Set $print_r to TRUE when dealing with a recursive data structure
  7248. * as var_export() will generate an error.
  7249. */
  7250. function debug($data, $label = NULL, $print_r = FALSE) {
  7251. // Print $data contents to string.
  7252. $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
  7253. // Display values with pre-formatting to increase readability.
  7254. $string = '<pre>' . $string . '</pre>';
  7255. trigger_error(trim($label ? "$label: $string" : $string));
  7256. }
  7257. /**
  7258. * Parses a dependency for comparison by drupal_check_incompatibility().
  7259. *
  7260. * @param $dependency
  7261. * A dependency string, which specifies a module dependency, and optionally
  7262. * the project it comes from and versions that are supported. Supported
  7263. * formats include:
  7264. * - 'module'
  7265. * - 'project:module'
  7266. * - 'project:module (>=version, version)'
  7267. *
  7268. * @return
  7269. * An associative array with three keys:
  7270. * - 'name' includes the name of the thing to depend on (e.g. 'foo').
  7271. * - 'original_version' contains the original version string (which can be
  7272. * used in the UI for reporting incompatibilities).
  7273. * - 'versions' is a list of associative arrays, each containing the keys
  7274. * 'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
  7275. * '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
  7276. * Callers should pass this structure to drupal_check_incompatibility().
  7277. *
  7278. * @see drupal_check_incompatibility()
  7279. */
  7280. function drupal_parse_dependency($dependency) {
  7281. $value = array();
  7282. // Split out the optional project name.
  7283. if (strpos($dependency, ':')) {
  7284. list($project_name, $dependency) = explode(':', $dependency);
  7285. $value['project'] = $project_name;
  7286. }
  7287. // We use named subpatterns and support every op that version_compare
  7288. // supports. Also, op is optional and defaults to equals.
  7289. $p_op = '(?P<operation>!=|==|=|<|<=|>|>=|<>)?';
  7290. // Core version is always optional: 7.x-2.x and 2.x is treated the same.
  7291. $p_core = '(?:' . preg_quote(DRUPAL_CORE_COMPATIBILITY) . '-)?';
  7292. $p_major = '(?P<major>\d+)';
  7293. // By setting the minor version to x, branches can be matched.
  7294. $p_minor = '(?P<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
  7295. $parts = explode('(', $dependency, 2);
  7296. $value['name'] = trim($parts[0]);
  7297. if (isset($parts[1])) {
  7298. $value['original_version'] = ' (' . $parts[1];
  7299. foreach (explode(',', $parts[1]) as $version) {
  7300. if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
  7301. $op = !empty($matches['operation']) ? $matches['operation'] : '=';
  7302. if ($matches['minor'] == 'x') {
  7303. // Drupal considers "2.x" to mean any version that begins with
  7304. // "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
  7305. // on the other hand, treats "x" as a string; so to
  7306. // version_compare(), "2.x" is considered less than 2.0. This
  7307. // means that >=2.x and <2.x are handled by version_compare()
  7308. // as we need, but > and <= are not.
  7309. if ($op == '>' || $op == '<=') {
  7310. $matches['major']++;
  7311. }
  7312. // Equivalence can be checked by adding two restrictions.
  7313. if ($op == '=' || $op == '==') {
  7314. $value['versions'][] = array('op' => '<', 'version' => ($matches['major'] + 1) . '.x');
  7315. $op = '>=';
  7316. }
  7317. }
  7318. $value['versions'][] = array('op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']);
  7319. }
  7320. }
  7321. }
  7322. return $value;
  7323. }
  7324. /**
  7325. * Checks whether a version is compatible with a given dependency.
  7326. *
  7327. * @param $v
  7328. * The parsed dependency structure from drupal_parse_dependency().
  7329. * @param $current_version
  7330. * The version to check against (like 4.2).
  7331. *
  7332. * @return
  7333. * NULL if compatible, otherwise the original dependency version string that
  7334. * caused the incompatibility.
  7335. *
  7336. * @see drupal_parse_dependency()
  7337. */
  7338. function drupal_check_incompatibility($v, $current_version) {
  7339. if (!empty($v['versions'])) {
  7340. foreach ($v['versions'] as $required_version) {
  7341. if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
  7342. return $v['original_version'];
  7343. }
  7344. }
  7345. }
  7346. }
  7347. /**
  7348. * Get the entity info array of an entity type.
  7349. *
  7350. * @param $entity_type
  7351. * The entity type, e.g. node, for which the info shall be returned, or NULL
  7352. * to return an array with info about all types.
  7353. *
  7354. * @see hook_entity_info()
  7355. * @see hook_entity_info_alter()
  7356. */
  7357. function entity_get_info($entity_type = NULL) {
  7358. global $language;
  7359. // Use the advanced drupal_static() pattern, since this is called very often.
  7360. static $drupal_static_fast;
  7361. if (!isset($drupal_static_fast)) {
  7362. $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
  7363. }
  7364. $entity_info = &$drupal_static_fast['entity_info'];
  7365. // hook_entity_info() includes translated strings, so each language is cached
  7366. // separately.
  7367. $langcode = $language->language;
  7368. if (empty($entity_info)) {
  7369. if ($cache = cache_get("entity_info:$langcode")) {
  7370. $entity_info = $cache->data;
  7371. }
  7372. else {
  7373. $entity_info = module_invoke_all('entity_info');
  7374. // Merge in default values.
  7375. foreach ($entity_info as $name => $data) {
  7376. $entity_info[$name] += array(
  7377. 'fieldable' => FALSE,
  7378. 'controller class' => 'DrupalDefaultEntityController',
  7379. 'static cache' => TRUE,
  7380. 'field cache' => TRUE,
  7381. 'load hook' => $name . '_load',
  7382. 'bundles' => array(),
  7383. 'view modes' => array(),
  7384. 'entity keys' => array(),
  7385. 'translation' => array(),
  7386. );
  7387. $entity_info[$name]['entity keys'] += array(
  7388. 'revision' => '',
  7389. 'bundle' => '',
  7390. );
  7391. foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
  7392. $entity_info[$name]['view modes'][$view_mode] += array(
  7393. 'custom settings' => FALSE,
  7394. );
  7395. }
  7396. // If no bundle key is provided, assume a single bundle, named after
  7397. // the entity type.
  7398. if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
  7399. $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
  7400. }
  7401. // Prepare entity schema fields SQL info for
  7402. // DrupalEntityControllerInterface::buildQuery().
  7403. if (isset($entity_info[$name]['base table'])) {
  7404. $entity_info[$name]['base table field types'] = drupal_schema_field_types($entity_info[$name]['base table']);
  7405. $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
  7406. if (isset($entity_info[$name]['revision table'])) {
  7407. $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
  7408. }
  7409. }
  7410. }
  7411. // Let other modules alter the entity info.
  7412. drupal_alter('entity_info', $entity_info);
  7413. cache_set("entity_info:$langcode", $entity_info);
  7414. }
  7415. }
  7416. if (empty($entity_type)) {
  7417. return $entity_info;
  7418. }
  7419. elseif (isset($entity_info[$entity_type])) {
  7420. return $entity_info[$entity_type];
  7421. }
  7422. }
  7423. /**
  7424. * Resets the cached information about entity types.
  7425. */
  7426. function entity_info_cache_clear() {
  7427. drupal_static_reset('entity_get_info');
  7428. // Clear all languages.
  7429. cache_clear_all('entity_info:', 'cache', TRUE);
  7430. }
  7431. /**
  7432. * Helper function to extract id, vid, and bundle name from an entity.
  7433. *
  7434. * @param $entity_type
  7435. * The entity type; e.g. 'node' or 'user'.
  7436. * @param $entity
  7437. * The entity from which to extract values.
  7438. *
  7439. * @return
  7440. * A numerically indexed array (not a hash table) containing these
  7441. * elements:
  7442. * - 0: Primary ID of the entity.
  7443. * - 1: Revision ID of the entity, or NULL if $entity_type is not versioned.
  7444. * - 2: Bundle name of the entity, or NULL if $entity_type has no bundles.
  7445. */
  7446. function entity_extract_ids($entity_type, $entity) {
  7447. $info = entity_get_info($entity_type);
  7448. // Objects being created might not have id/vid yet.
  7449. $id = isset($entity->{$info['entity keys']['id']}) ? $entity->{$info['entity keys']['id']} : NULL;
  7450. $vid = ($info['entity keys']['revision'] && isset($entity->{$info['entity keys']['revision']})) ? $entity->{$info['entity keys']['revision']} : NULL;
  7451. if (!empty($info['entity keys']['bundle'])) {
  7452. // Explicitly fail for malformed entities missing the bundle property.
  7453. if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  7454. throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
  7455. }
  7456. $bundle = $entity->{$info['entity keys']['bundle']};
  7457. }
  7458. else {
  7459. // The entity type provides no bundle key: assume a single bundle, named
  7460. // after the entity type.
  7461. $bundle = $entity_type;
  7462. }
  7463. return array($id, $vid, $bundle);
  7464. }
  7465. /**
  7466. * Helper function to assemble an object structure with initial ids.
  7467. *
  7468. * This function can be seen as reciprocal to entity_extract_ids().
  7469. *
  7470. * @param $entity_type
  7471. * The entity type; e.g. 'node' or 'user'.
  7472. * @param $ids
  7473. * A numerically indexed array, as returned by entity_extract_ids().
  7474. *
  7475. * @return
  7476. * An entity structure, initialized with the ids provided.
  7477. *
  7478. * @see entity_extract_ids()
  7479. */
  7480. function entity_create_stub_entity($entity_type, $ids) {
  7481. $entity = new stdClass();
  7482. $info = entity_get_info($entity_type);
  7483. $entity->{$info['entity keys']['id']} = $ids[0];
  7484. if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
  7485. $entity->{$info['entity keys']['revision']} = $ids[1];
  7486. }
  7487. if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
  7488. $entity->{$info['entity keys']['bundle']} = $ids[2];
  7489. }
  7490. return $entity;
  7491. }
  7492. /**
  7493. * Load entities from the database.
  7494. *
  7495. * The entities are stored in a static memory cache, and will not require
  7496. * database access if loaded again during the same page request.
  7497. *
  7498. * The actual loading is done through a class that has to implement the
  7499. * DrupalEntityControllerInterface interface. By default,
  7500. * DrupalDefaultEntityController is used. Entity types can specify that a
  7501. * different class should be used by setting the 'controller class' key in
  7502. * hook_entity_info(). These classes can either implement the
  7503. * DrupalEntityControllerInterface interface, or, most commonly, extend the
  7504. * DrupalDefaultEntityController class. See node_entity_info() and the
  7505. * NodeController in node.module as an example.
  7506. *
  7507. * @param $entity_type
  7508. * The entity type to load, e.g. node or user.
  7509. * @param $ids
  7510. * An array of entity IDs, or FALSE to load all entities.
  7511. * @param $conditions
  7512. * (deprecated) An associative array of conditions on the base table, where
  7513. * the keys are the database fields and the values are the values those
  7514. * fields must have. Instead, it is preferable to use EntityFieldQuery to
  7515. * retrieve a list of entity IDs loadable by this function.
  7516. * @param $reset
  7517. * Whether to reset the internal cache for the requested entity type.
  7518. *
  7519. * @return
  7520. * An array of entity objects indexed by their ids. When no results are
  7521. * found, an empty array is returned.
  7522. *
  7523. * @todo Remove $conditions in Drupal 8.
  7524. *
  7525. * @see hook_entity_info()
  7526. * @see DrupalEntityControllerInterface
  7527. * @see DrupalDefaultEntityController
  7528. * @see EntityFieldQuery
  7529. */
  7530. function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
  7531. if ($reset) {
  7532. entity_get_controller($entity_type)->resetCache();
  7533. }
  7534. return entity_get_controller($entity_type)->load($ids, $conditions);
  7535. }
  7536. /**
  7537. * Loads the unchanged, i.e. not modified, entity from the database.
  7538. *
  7539. * Unlike entity_load() this function ensures the entity is directly loaded from
  7540. * the database, thus bypassing any static cache. In particular, this function
  7541. * is useful to determine changes by comparing the entity being saved to the
  7542. * stored entity.
  7543. *
  7544. * @param $entity_type
  7545. * The entity type to load, e.g. node or user.
  7546. * @param $id
  7547. * The ID of the entity to load.
  7548. *
  7549. * @return
  7550. * The unchanged entity, or FALSE if the entity cannot be loaded.
  7551. */
  7552. function entity_load_unchanged($entity_type, $id) {
  7553. entity_get_controller($entity_type)->resetCache(array($id));
  7554. $result = entity_get_controller($entity_type)->load(array($id));
  7555. return reset($result);
  7556. }
  7557. /**
  7558. * Gets the entity controller for an entity type.
  7559. *
  7560. * @return DrupalEntityControllerInterface
  7561. * The entity controller object for the specified entity type.
  7562. */
  7563. function entity_get_controller($entity_type) {
  7564. $controllers = &drupal_static(__FUNCTION__, array());
  7565. if (!isset($controllers[$entity_type])) {
  7566. $type_info = entity_get_info($entity_type);
  7567. $class = $type_info['controller class'];
  7568. $controllers[$entity_type] = new $class($entity_type);
  7569. }
  7570. return $controllers[$entity_type];
  7571. }
  7572. /**
  7573. * Invoke hook_entity_prepare_view().
  7574. *
  7575. * If adding a new entity similar to nodes, comments or users, you should
  7576. * invoke this function during the ENTITY_build_content() or
  7577. * ENTITY_view_multiple() phases of rendering to allow other modules to alter
  7578. * the objects during this phase. This is needed for situations where
  7579. * information needs to be loaded outside of ENTITY_load() - particularly
  7580. * when loading entities into one another - i.e. a user object into a node, due
  7581. * to the potential for unwanted side-effects such as caching and infinite
  7582. * recursion. By convention, entity_prepare_view() is called after
  7583. * field_attach_prepare_view() to allow entity level hooks to act on content
  7584. * loaded by field API.
  7585. *
  7586. * @param $entity_type
  7587. * The type of entity, i.e. 'node', 'user'.
  7588. * @param $entities
  7589. * The entity objects which are being prepared for view, keyed by object ID.
  7590. * @param $langcode
  7591. * (optional) A language code to be used for rendering. Defaults to the global
  7592. * content language of the current request.
  7593. *
  7594. * @see hook_entity_prepare_view()
  7595. */
  7596. function entity_prepare_view($entity_type, $entities, $langcode = NULL) {
  7597. if (!isset($langcode)) {
  7598. $langcode = $GLOBALS['language_content']->language;
  7599. }
  7600. // To ensure hooks are only run once per entity, check for an
  7601. // entity_view_prepared flag and only process items without it.
  7602. // @todo: resolve this more generally for both entity and field level hooks.
  7603. $prepare = array();
  7604. foreach ($entities as $id => $entity) {
  7605. if (empty($entity->entity_view_prepared)) {
  7606. // Add this entity to the items to be prepared.
  7607. $prepare[$id] = $entity;
  7608. // Mark this item as prepared.
  7609. $entity->entity_view_prepared = TRUE;
  7610. }
  7611. }
  7612. if (!empty($prepare)) {
  7613. module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
  7614. }
  7615. }
  7616. /**
  7617. * Invoke hook_entity_view_mode_alter().
  7618. *
  7619. * If adding a new entity similar to nodes, comments or users, you should invoke
  7620. * this function during the ENTITY_build_content() or ENTITY_view_multiple()
  7621. * phases of rendering to allow other modules to alter the view mode during this
  7622. * phase. This function needs to be called before field_attach_prepare_view() to
  7623. * ensure that the correct content is loaded by field API.
  7624. *
  7625. * @param $entity_type
  7626. * The type of entity, i.e. 'node', 'user'.
  7627. * @param $entities
  7628. * The entity objects which are being prepared for view, keyed by object ID.
  7629. * @param $view_mode
  7630. * The original view mode e.g. 'full', 'teaser'...
  7631. * @param $langcode
  7632. * (optional) A language code to be used for rendering. Defaults to the global
  7633. * content language of the current request.
  7634. * @return
  7635. * An associative array with arrays of entities keyed by view mode.
  7636. *
  7637. * @see hook_entity_view_mode_alter()
  7638. */
  7639. function entity_view_mode_prepare($entity_type, $entities, $view_mode, $langcode = NULL) {
  7640. if (!isset($langcode)) {
  7641. $langcode = $GLOBALS['language_content']->language;
  7642. }
  7643. // To ensure hooks are never run after field_attach_prepare_view() only
  7644. // process items without the entity_view_prepared flag.
  7645. $entities_by_view_mode = array();
  7646. foreach ($entities as $id => $entity) {
  7647. $entity_view_mode = $view_mode;
  7648. if (empty($entity->entity_view_prepared)) {
  7649. // Allow modules to change the view mode.
  7650. $context = array(
  7651. 'entity_type' => $entity_type,
  7652. 'entity' => $entity,
  7653. 'langcode' => $langcode,
  7654. );
  7655. drupal_alter('entity_view_mode', $entity_view_mode, $context);
  7656. }
  7657. $entities_by_view_mode[$entity_view_mode][$id] = $entity;
  7658. }
  7659. return $entities_by_view_mode;
  7660. }
  7661. /**
  7662. * Returns the URI elements of an entity.
  7663. *
  7664. * @param $entity_type
  7665. * The entity type; e.g. 'node' or 'user'.
  7666. * @param $entity
  7667. * The entity for which to generate a path.
  7668. * @return
  7669. * An array containing the 'path' and 'options' keys used to build the URI of
  7670. * the entity, and matching the signature of url(). NULL if the entity has no
  7671. * URI of its own.
  7672. */
  7673. function entity_uri($entity_type, $entity) {
  7674. $info = entity_get_info($entity_type);
  7675. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  7676. // A bundle-specific callback takes precedence over the generic one for the
  7677. // entity type.
  7678. if (isset($info['bundles'][$bundle]['uri callback'])) {
  7679. $uri_callback = $info['bundles'][$bundle]['uri callback'];
  7680. }
  7681. elseif (isset($info['uri callback'])) {
  7682. $uri_callback = $info['uri callback'];
  7683. }
  7684. else {
  7685. return NULL;
  7686. }
  7687. // Invoke the callback to get the URI. If there is no callback, return NULL.
  7688. if (isset($uri_callback) && function_exists($uri_callback)) {
  7689. $uri = $uri_callback($entity);
  7690. // Pass the entity data to url() so that alter functions do not need to
  7691. // lookup this entity again.
  7692. $uri['options']['entity_type'] = $entity_type;
  7693. $uri['options']['entity'] = $entity;
  7694. return $uri;
  7695. }
  7696. }
  7697. /**
  7698. * Returns the label of an entity.
  7699. *
  7700. * See the 'label callback' component of the hook_entity_info() return value
  7701. * for more information.
  7702. *
  7703. * @param $entity_type
  7704. * The entity type; e.g., 'node' or 'user'.
  7705. * @param $entity
  7706. * The entity for which to generate the label.
  7707. *
  7708. * @return
  7709. * The entity label, or FALSE if not found.
  7710. */
  7711. function entity_label($entity_type, $entity) {
  7712. $label = FALSE;
  7713. $info = entity_get_info($entity_type);
  7714. if (isset($info['label callback']) && function_exists($info['label callback'])) {
  7715. $label = $info['label callback']($entity, $entity_type);
  7716. }
  7717. elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
  7718. $label = $entity->{$info['entity keys']['label']};
  7719. }
  7720. return $label;
  7721. }
  7722. /**
  7723. * Returns the language of an entity.
  7724. *
  7725. * @param $entity_type
  7726. * The entity type; e.g., 'node' or 'user'.
  7727. * @param $entity
  7728. * The entity for which to get the language.
  7729. *
  7730. * @return
  7731. * A valid language code or NULL if the entity has no language support.
  7732. */
  7733. function entity_language($entity_type, $entity) {
  7734. $info = entity_get_info($entity_type);
  7735. // Invoke the callback to get the language. If there is no callback, try to
  7736. // get it from a property of the entity, otherwise NULL.
  7737. if (isset($info['language callback']) && function_exists($info['language callback'])) {
  7738. $langcode = $info['language callback']($entity_type, $entity);
  7739. }
  7740. elseif (!empty($info['entity keys']['language']) && isset($entity->{$info['entity keys']['language']})) {
  7741. $langcode = $entity->{$info['entity keys']['language']};
  7742. }
  7743. else {
  7744. // The value returned in D8 would be LANGUAGE_NONE, we cannot use it here to
  7745. // preserve backward compatibility. In fact this function has been
  7746. // introduced very late in the D7 life cycle, mainly as the proper default
  7747. // for field_attach_form(). By returning LANGUAGE_NONE when no language
  7748. // information is available, we would introduce a potentially BC-breaking
  7749. // API change, since field_attach_form() defaults to the default language
  7750. // instead of LANGUAGE_NONE. Moreover this allows us to distinguish between
  7751. // entities that have no language specified from ones that do not have
  7752. // language support at all.
  7753. $langcode = NULL;
  7754. }
  7755. return $langcode;
  7756. }
  7757. /**
  7758. * Attaches field API validation to entity forms.
  7759. */
  7760. function entity_form_field_validate($entity_type, $form, &$form_state) {
  7761. // All field attach API functions act on an entity object, but during form
  7762. // validation, we don't have one. $form_state contains the entity as it was
  7763. // prior to processing the current form submission, and we must not update it
  7764. // until we have fully validated the submitted input. Therefore, for
  7765. // validation, act on a pseudo entity created out of the form values.
  7766. $pseudo_entity = (object) $form_state['values'];
  7767. field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
  7768. }
  7769. /**
  7770. * Copies submitted values to entity properties for simple entity forms.
  7771. *
  7772. * During the submission handling of an entity form's "Save", "Preview", and
  7773. * possibly other buttons, the form state's entity needs to be updated with the
  7774. * submitted form values. Each entity form implements its own builder function
  7775. * for doing this, appropriate for the particular entity and form, whereas
  7776. * modules may specify additional builder functions in $form['#entity_builders']
  7777. * for copying the form values of added form elements to entity properties.
  7778. * Many of the main entity builder functions can call this helper function to
  7779. * re-use its logic of copying $form_state['values'][PROPERTY] values to
  7780. * $entity->PROPERTY for all entries in $form_state['values'] that are not field
  7781. * data, and calling field_attach_submit() to copy field data. Apart from that
  7782. * this helper invokes any additional builder functions that have been specified
  7783. * in $form['#entity_builders'].
  7784. *
  7785. * For some entity forms (e.g., forms with complex non-field data and forms that
  7786. * simultaneously edit multiple entities), this behavior may be inappropriate,
  7787. * so the builder function for such forms needs to implement the required
  7788. * functionality instead of calling this function.
  7789. */
  7790. function entity_form_submit_build_entity($entity_type, $entity, $form, &$form_state) {
  7791. $info = entity_get_info($entity_type);
  7792. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  7793. // Copy top-level form values that are not for fields to entity properties,
  7794. // without changing existing entity properties that are not being edited by
  7795. // this form. Copying field values must be done using field_attach_submit().
  7796. $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
  7797. foreach ($values_excluding_fields as $key => $value) {
  7798. $entity->$key = $value;
  7799. }
  7800. // Invoke all specified builders for copying form values to entity properties.
  7801. if (isset($form['#entity_builders'])) {
  7802. foreach ($form['#entity_builders'] as $function) {
  7803. $function($entity_type, $entity, $form, $form_state);
  7804. }
  7805. }
  7806. // Copy field values to the entity.
  7807. if ($info['fieldable']) {
  7808. field_attach_submit($entity_type, $entity, $form, $form_state);
  7809. }
  7810. }
  7811. /**
  7812. * Performs one or more XML-RPC request(s).
  7813. *
  7814. * Usage example:
  7815. * @code
  7816. * $result = xmlrpc('http://example.com/xmlrpc.php', array(
  7817. * 'service.methodName' => array($parameter, $second, $third),
  7818. * ));
  7819. * @endcode
  7820. *
  7821. * @param $url
  7822. * An absolute URL of the XML-RPC endpoint.
  7823. * @param $args
  7824. * An associative array whose keys are the methods to call and whose values
  7825. * are the arguments to pass to the respective method. If multiple methods
  7826. * are specified, a system.multicall is performed.
  7827. * @param $options
  7828. * (optional) An array of options to pass along to drupal_http_request().
  7829. *
  7830. * @return
  7831. * For one request:
  7832. * Either the return value of the method on success, or FALSE.
  7833. * If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
  7834. * For multiple requests:
  7835. * An array of results. Each result will either be the result
  7836. * returned by the method called, or an xmlrpc_error object if the call
  7837. * failed. See xmlrpc_error().
  7838. */
  7839. function xmlrpc($url, $args, $options = array()) {
  7840. require_once DRUPAL_ROOT . '/includes/xmlrpc.inc';
  7841. return _xmlrpc($url, $args, $options);
  7842. }
  7843. /**
  7844. * Retrieves a list of all available archivers.
  7845. *
  7846. * @see hook_archiver_info()
  7847. * @see hook_archiver_info_alter()
  7848. */
  7849. function archiver_get_info() {
  7850. $archiver_info = &drupal_static(__FUNCTION__, array());
  7851. if (empty($archiver_info)) {
  7852. $cache = cache_get('archiver_info');
  7853. if ($cache === FALSE) {
  7854. // Rebuild the cache and save it.
  7855. $archiver_info = module_invoke_all('archiver_info');
  7856. drupal_alter('archiver_info', $archiver_info);
  7857. uasort($archiver_info, 'drupal_sort_weight');
  7858. cache_set('archiver_info', $archiver_info);
  7859. }
  7860. else {
  7861. $archiver_info = $cache->data;
  7862. }
  7863. }
  7864. return $archiver_info;
  7865. }
  7866. /**
  7867. * Returns a string of supported archive extensions.
  7868. *
  7869. * @return
  7870. * A space-separated string of extensions suitable for use by the file
  7871. * validation system.
  7872. */
  7873. function archiver_get_extensions() {
  7874. $valid_extensions = array();
  7875. foreach (archiver_get_info() as $archive) {
  7876. foreach ($archive['extensions'] as $extension) {
  7877. foreach (explode('.', $extension) as $part) {
  7878. if (!in_array($part, $valid_extensions)) {
  7879. $valid_extensions[] = $part;
  7880. }
  7881. }
  7882. }
  7883. }
  7884. return implode(' ', $valid_extensions);
  7885. }
  7886. /**
  7887. * Creates the appropriate archiver for the specified file.
  7888. *
  7889. * @param $file
  7890. * The full path of the archive file. Note that stream wrapper paths are
  7891. * supported, but not remote ones.
  7892. *
  7893. * @return
  7894. * A newly created instance of the archiver class appropriate
  7895. * for the specified file, already bound to that file.
  7896. * If no appropriate archiver class was found, will return FALSE.
  7897. */
  7898. function archiver_get_archiver($file) {
  7899. // Archivers can only work on local paths
  7900. $filepath = drupal_realpath($file);
  7901. if (!is_file($filepath)) {
  7902. throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
  7903. }
  7904. $archiver_info = archiver_get_info();
  7905. foreach ($archiver_info as $implementation) {
  7906. foreach ($implementation['extensions'] as $extension) {
  7907. // Because extensions may be multi-part, such as .tar.gz,
  7908. // we cannot use simpler approaches like substr() or pathinfo().
  7909. // This method isn't quite as clean but gets the job done.
  7910. // Also note that the file may not yet exist, so we cannot rely
  7911. // on fileinfo() or other disk-level utilities.
  7912. if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
  7913. return new $implementation['class']($filepath);
  7914. }
  7915. }
  7916. }
  7917. }
  7918. /**
  7919. * Assembles the Drupal Updater registry.
  7920. *
  7921. * An Updater is a class that knows how to update various parts of the Drupal
  7922. * file system, for example to update modules that have newer releases, or to
  7923. * install a new theme.
  7924. *
  7925. * @return
  7926. * The Drupal Updater class registry.
  7927. *
  7928. * @see hook_updater_info()
  7929. * @see hook_updater_info_alter()
  7930. */
  7931. function drupal_get_updaters() {
  7932. $updaters = &drupal_static(__FUNCTION__);
  7933. if (!isset($updaters)) {
  7934. $updaters = module_invoke_all('updater_info');
  7935. drupal_alter('updater_info', $updaters);
  7936. uasort($updaters, 'drupal_sort_weight');
  7937. }
  7938. return $updaters;
  7939. }
  7940. /**
  7941. * Assembles the Drupal FileTransfer registry.
  7942. *
  7943. * @return
  7944. * The Drupal FileTransfer class registry.
  7945. *
  7946. * @see FileTransfer
  7947. * @see hook_filetransfer_info()
  7948. * @see hook_filetransfer_info_alter()
  7949. */
  7950. function drupal_get_filetransfer_info() {
  7951. $info = &drupal_static(__FUNCTION__);
  7952. if (!isset($info)) {
  7953. // Since we have to manually set the 'file path' default for each
  7954. // module separately, we can't use module_invoke_all().
  7955. $info = array();
  7956. foreach (module_implements('filetransfer_info') as $module) {
  7957. $function = $module . '_filetransfer_info';
  7958. if (function_exists($function)) {
  7959. $result = $function();
  7960. if (isset($result) && is_array($result)) {
  7961. foreach ($result as &$values) {
  7962. if (empty($values['file path'])) {
  7963. $values['file path'] = drupal_get_path('module', $module);
  7964. }
  7965. }
  7966. $info = array_merge_recursive($info, $result);
  7967. }
  7968. }
  7969. }
  7970. drupal_alter('filetransfer_info', $info);
  7971. uasort($info, 'drupal_sort_weight');
  7972. }
  7973. return $info;
  7974. }