common.inc 295 KB

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