common.inc 315 KB

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