common.inc 308 KB

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