common.inc 300 KB

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