common.inc 308 KB

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