common.inc 297 KB

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