common.inc 308 KB

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