yiilite.php 304 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582
  1. <?php
  2. /**
  3. * Yii bootstrap file.
  4. *
  5. * This file is automatically generated using 'build lite' command.
  6. * It is the result of merging commonly used Yii class files with
  7. * comments and trace statements removed away.
  8. *
  9. * By using this file instead of yii.php, an Yii application may
  10. * improve performance due to the reduction of PHP parsing time.
  11. * The performance improvement is especially obvious when PHP APC extension
  12. * is enabled.
  13. *
  14. * DO NOT modify this file manually.
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @link http://www.yiiframework.com/
  18. * @copyright 2008-2013 Yii Software LLC
  19. * @license http://www.yiiframework.com/license/
  20. * @version $Id: $
  21. * @since 1.0
  22. */
  23. defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME',microtime(true));
  24. defined('YII_DEBUG') or define('YII_DEBUG',false);
  25. defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
  26. defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER',true);
  27. defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER',true);
  28. defined('YII_PATH') or define('YII_PATH',dirname(__FILE__));
  29. defined('YII_ZII_PATH') or define('YII_ZII_PATH',YII_PATH.DIRECTORY_SEPARATOR.'zii');
  30. class YiiBase
  31. {
  32. public static $classMap=array();
  33. public static $enableIncludePath=true;
  34. private static $_aliases=array('system'=>YII_PATH,'zii'=>YII_ZII_PATH); // alias => path
  35. private static $_imports=array(); // alias => class name or directory
  36. private static $_includePaths; // list of include paths
  37. private static $_app;
  38. private static $_logger;
  39. public static function getVersion()
  40. {
  41. return '1.1.16';
  42. }
  43. public static function createWebApplication($config=null)
  44. {
  45. return self::createApplication('CWebApplication',$config);
  46. }
  47. public static function createConsoleApplication($config=null)
  48. {
  49. return self::createApplication('CConsoleApplication',$config);
  50. }
  51. public static function createApplication($class,$config=null)
  52. {
  53. return new $class($config);
  54. }
  55. public static function app()
  56. {
  57. return self::$_app;
  58. }
  59. public static function setApplication($app)
  60. {
  61. if(self::$_app===null || $app===null)
  62. self::$_app=$app;
  63. else
  64. throw new CException(Yii::t('yii','Yii application can only be created once.'));
  65. }
  66. public static function getFrameworkPath()
  67. {
  68. return YII_PATH;
  69. }
  70. public static function createComponent($config)
  71. {
  72. if(is_string($config))
  73. {
  74. $type=$config;
  75. $config=array();
  76. }
  77. elseif(isset($config['class']))
  78. {
  79. $type=$config['class'];
  80. unset($config['class']);
  81. }
  82. else
  83. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  84. if(!class_exists($type,false))
  85. $type=Yii::import($type,true);
  86. if(($n=func_num_args())>1)
  87. {
  88. $args=func_get_args();
  89. if($n===2)
  90. $object=new $type($args[1]);
  91. elseif($n===3)
  92. $object=new $type($args[1],$args[2]);
  93. elseif($n===4)
  94. $object=new $type($args[1],$args[2],$args[3]);
  95. else
  96. {
  97. unset($args[0]);
  98. $class=new ReflectionClass($type);
  99. // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
  100. // $object=$class->newInstanceArgs($args);
  101. $object=call_user_func_array(array($class,'newInstance'),$args);
  102. }
  103. }
  104. else
  105. $object=new $type;
  106. foreach($config as $key=>$value)
  107. $object->$key=$value;
  108. return $object;
  109. }
  110. public static function import($alias,$forceInclude=false)
  111. {
  112. if(isset(self::$_imports[$alias])) // previously imported
  113. return self::$_imports[$alias];
  114. if(class_exists($alias,false) || interface_exists($alias,false))
  115. return self::$_imports[$alias]=$alias;
  116. if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
  117. {
  118. $namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
  119. if(($path=self::getPathOfAlias($namespace))!==false)
  120. {
  121. $classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
  122. if($forceInclude)
  123. {
  124. if(is_file($classFile))
  125. require($classFile);
  126. else
  127. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
  128. self::$_imports[$alias]=$alias;
  129. }
  130. else
  131. self::$classMap[$alias]=$classFile;
  132. return $alias;
  133. }
  134. else
  135. {
  136. // try to autoload the class with an autoloader
  137. if (class_exists($alias,true))
  138. return self::$_imports[$alias]=$alias;
  139. else
  140. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  141. array('{alias}'=>$namespace)));
  142. }
  143. }
  144. if(($pos=strrpos($alias,'.'))===false) // a simple class name
  145. {
  146. // try to autoload the class with an autoloader if $forceInclude is true
  147. if($forceInclude && (Yii::autoload($alias,true) || class_exists($alias,true)))
  148. self::$_imports[$alias]=$alias;
  149. return $alias;
  150. }
  151. $className=(string)substr($alias,$pos+1);
  152. $isClass=$className!=='*';
  153. if($isClass && (class_exists($className,false) || interface_exists($className,false)))
  154. return self::$_imports[$alias]=$className;
  155. if(($path=self::getPathOfAlias($alias))!==false)
  156. {
  157. if($isClass)
  158. {
  159. if($forceInclude)
  160. {
  161. if(is_file($path.'.php'))
  162. require($path.'.php');
  163. else
  164. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
  165. self::$_imports[$alias]=$className;
  166. }
  167. else
  168. self::$classMap[$className]=$path.'.php';
  169. return $className;
  170. }
  171. else // a directory
  172. {
  173. if(self::$_includePaths===null)
  174. {
  175. self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
  176. if(($pos=array_search('.',self::$_includePaths,true))!==false)
  177. unset(self::$_includePaths[$pos]);
  178. }
  179. array_unshift(self::$_includePaths,$path);
  180. if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
  181. self::$enableIncludePath=false;
  182. return self::$_imports[$alias]=$path;
  183. }
  184. }
  185. else
  186. throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
  187. array('{alias}'=>$alias)));
  188. }
  189. public static function getPathOfAlias($alias)
  190. {
  191. if(isset(self::$_aliases[$alias]))
  192. return self::$_aliases[$alias];
  193. elseif(($pos=strpos($alias,'.'))!==false)
  194. {
  195. $rootAlias=substr($alias,0,$pos);
  196. if(isset(self::$_aliases[$rootAlias]))
  197. return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
  198. elseif(self::$_app instanceof CWebApplication)
  199. {
  200. if(self::$_app->findModule($rootAlias)!==null)
  201. return self::getPathOfAlias($alias);
  202. }
  203. }
  204. return false;
  205. }
  206. public static function setPathOfAlias($alias,$path)
  207. {
  208. if(empty($path))
  209. unset(self::$_aliases[$alias]);
  210. else
  211. self::$_aliases[$alias]=rtrim($path,'\\/');
  212. }
  213. public static function autoload($className,$classMapOnly=false)
  214. {
  215. // use include so that the error PHP file may appear
  216. if(isset(self::$classMap[$className]))
  217. include(self::$classMap[$className]);
  218. elseif(isset(self::$_coreClasses[$className]))
  219. include(YII_PATH.self::$_coreClasses[$className]);
  220. elseif($classMapOnly)
  221. return false;
  222. else
  223. {
  224. // include class file relying on include_path
  225. if(strpos($className,'\\')===false) // class without namespace
  226. {
  227. if(self::$enableIncludePath===false)
  228. {
  229. foreach(self::$_includePaths as $path)
  230. {
  231. $classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
  232. if(is_file($classFile))
  233. {
  234. include($classFile);
  235. if(YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
  236. throw new CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
  237. '{class}'=>$className,
  238. '{file}'=>$classFile,
  239. )));
  240. break;
  241. }
  242. }
  243. }
  244. else
  245. include($className.'.php');
  246. }
  247. else // class name with namespace in PHP 5.3
  248. {
  249. $namespace=str_replace('\\','.',ltrim($className,'\\'));
  250. if(($path=self::getPathOfAlias($namespace))!==false)
  251. include($path.'.php');
  252. else
  253. return false;
  254. }
  255. return class_exists($className,false) || interface_exists($className,false);
  256. }
  257. return true;
  258. }
  259. public static function trace($msg,$category='application')
  260. {
  261. if(YII_DEBUG)
  262. self::log($msg,CLogger::LEVEL_TRACE,$category);
  263. }
  264. public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
  265. {
  266. if(self::$_logger===null)
  267. self::$_logger=new CLogger;
  268. if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
  269. {
  270. $traces=debug_backtrace();
  271. $count=0;
  272. foreach($traces as $trace)
  273. {
  274. if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
  275. {
  276. $msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
  277. if(++$count>=YII_TRACE_LEVEL)
  278. break;
  279. }
  280. }
  281. }
  282. self::$_logger->log($msg,$level,$category);
  283. }
  284. public static function beginProfile($token,$category='application')
  285. {
  286. self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
  287. }
  288. public static function endProfile($token,$category='application')
  289. {
  290. self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
  291. }
  292. public static function getLogger()
  293. {
  294. if(self::$_logger!==null)
  295. return self::$_logger;
  296. else
  297. return self::$_logger=new CLogger;
  298. }
  299. public static function setLogger($logger)
  300. {
  301. self::$_logger=$logger;
  302. }
  303. public static function powered()
  304. {
  305. return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
  306. }
  307. public static function t($category,$message,$params=array(),$source=null,$language=null)
  308. {
  309. if(self::$_app!==null)
  310. {
  311. if($source===null)
  312. $source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
  313. if(($source=self::$_app->getComponent($source))!==null)
  314. $message=$source->translate($category,$message,$language);
  315. }
  316. if($params===array())
  317. return $message;
  318. if(!is_array($params))
  319. $params=array($params);
  320. if(isset($params[0])) // number choice
  321. {
  322. if(strpos($message,'|')!==false)
  323. {
  324. if(strpos($message,'#')===false)
  325. {
  326. $chunks=explode('|',$message);
  327. $expressions=self::$_app->getLocale($language)->getPluralRules();
  328. if($n=min(count($chunks),count($expressions)))
  329. {
  330. for($i=0;$i<$n;$i++)
  331. $chunks[$i]=$expressions[$i].'#'.$chunks[$i];
  332. $message=implode('|',$chunks);
  333. }
  334. }
  335. $message=CChoiceFormat::format($message,$params[0]);
  336. }
  337. if(!isset($params['{n}']))
  338. $params['{n}']=$params[0];
  339. unset($params[0]);
  340. }
  341. return $params!==array() ? strtr($message,$params) : $message;
  342. }
  343. public static function registerAutoloader($callback, $append=false)
  344. {
  345. if($append)
  346. {
  347. self::$enableIncludePath=false;
  348. spl_autoload_register($callback);
  349. }
  350. else
  351. {
  352. spl_autoload_unregister(array('YiiBase','autoload'));
  353. spl_autoload_register($callback);
  354. spl_autoload_register(array('YiiBase','autoload'));
  355. }
  356. }
  357. private static $_coreClasses=array(
  358. 'CApplication' => '/base/CApplication.php',
  359. 'CApplicationComponent' => '/base/CApplicationComponent.php',
  360. 'CBehavior' => '/base/CBehavior.php',
  361. 'CComponent' => '/base/CComponent.php',
  362. 'CErrorEvent' => '/base/CErrorEvent.php',
  363. 'CErrorHandler' => '/base/CErrorHandler.php',
  364. 'CException' => '/base/CException.php',
  365. 'CExceptionEvent' => '/base/CExceptionEvent.php',
  366. 'CHttpException' => '/base/CHttpException.php',
  367. 'CModel' => '/base/CModel.php',
  368. 'CModelBehavior' => '/base/CModelBehavior.php',
  369. 'CModelEvent' => '/base/CModelEvent.php',
  370. 'CModule' => '/base/CModule.php',
  371. 'CSecurityManager' => '/base/CSecurityManager.php',
  372. 'CStatePersister' => '/base/CStatePersister.php',
  373. 'CApcCache' => '/caching/CApcCache.php',
  374. 'CCache' => '/caching/CCache.php',
  375. 'CDbCache' => '/caching/CDbCache.php',
  376. 'CDummyCache' => '/caching/CDummyCache.php',
  377. 'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
  378. 'CFileCache' => '/caching/CFileCache.php',
  379. 'CMemCache' => '/caching/CMemCache.php',
  380. 'CRedisCache' => '/caching/CRedisCache.php',
  381. 'CWinCache' => '/caching/CWinCache.php',
  382. 'CXCache' => '/caching/CXCache.php',
  383. 'CZendDataCache' => '/caching/CZendDataCache.php',
  384. 'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
  385. 'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
  386. 'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
  387. 'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
  388. 'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
  389. 'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
  390. 'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
  391. 'CAttributeCollection' => '/collections/CAttributeCollection.php',
  392. 'CConfiguration' => '/collections/CConfiguration.php',
  393. 'CList' => '/collections/CList.php',
  394. 'CListIterator' => '/collections/CListIterator.php',
  395. 'CMap' => '/collections/CMap.php',
  396. 'CMapIterator' => '/collections/CMapIterator.php',
  397. 'CQueue' => '/collections/CQueue.php',
  398. 'CQueueIterator' => '/collections/CQueueIterator.php',
  399. 'CStack' => '/collections/CStack.php',
  400. 'CStackIterator' => '/collections/CStackIterator.php',
  401. 'CTypedList' => '/collections/CTypedList.php',
  402. 'CTypedMap' => '/collections/CTypedMap.php',
  403. 'CConsoleApplication' => '/console/CConsoleApplication.php',
  404. 'CConsoleCommand' => '/console/CConsoleCommand.php',
  405. 'CConsoleCommandBehavior' => '/console/CConsoleCommandBehavior.php',
  406. 'CConsoleCommandEvent' => '/console/CConsoleCommandEvent.php',
  407. 'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
  408. 'CHelpCommand' => '/console/CHelpCommand.php',
  409. 'CDbCommand' => '/db/CDbCommand.php',
  410. 'CDbConnection' => '/db/CDbConnection.php',
  411. 'CDbDataReader' => '/db/CDbDataReader.php',
  412. 'CDbException' => '/db/CDbException.php',
  413. 'CDbMigration' => '/db/CDbMigration.php',
  414. 'CDbTransaction' => '/db/CDbTransaction.php',
  415. 'CActiveFinder' => '/db/ar/CActiveFinder.php',
  416. 'CActiveRecord' => '/db/ar/CActiveRecord.php',
  417. 'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
  418. 'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
  419. 'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
  420. 'CDbCriteria' => '/db/schema/CDbCriteria.php',
  421. 'CDbExpression' => '/db/schema/CDbExpression.php',
  422. 'CDbSchema' => '/db/schema/CDbSchema.php',
  423. 'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
  424. 'CCubridColumnSchema' => '/db/schema/cubrid/CCubridColumnSchema.php',
  425. 'CCubridSchema' => '/db/schema/cubrid/CCubridSchema.php',
  426. 'CCubridTableSchema' => '/db/schema/cubrid/CCubridTableSchema.php',
  427. 'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
  428. 'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
  429. 'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
  430. 'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
  431. 'CMssqlSqlsrvPdoAdapter' => '/db/schema/mssql/CMssqlSqlsrvPdoAdapter.php',
  432. 'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
  433. 'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
  434. 'CMysqlCommandBuilder' => '/db/schema/mysql/CMysqlCommandBuilder.php',
  435. 'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
  436. 'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
  437. 'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
  438. 'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
  439. 'COciSchema' => '/db/schema/oci/COciSchema.php',
  440. 'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
  441. 'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
  442. 'CPgsqlCommandBuilder' => '/db/schema/pgsql/CPgsqlCommandBuilder.php',
  443. 'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
  444. 'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
  445. 'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
  446. 'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
  447. 'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
  448. 'CChoiceFormat' => '/i18n/CChoiceFormat.php',
  449. 'CDateFormatter' => '/i18n/CDateFormatter.php',
  450. 'CDbMessageSource' => '/i18n/CDbMessageSource.php',
  451. 'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
  452. 'CLocale' => '/i18n/CLocale.php',
  453. 'CMessageSource' => '/i18n/CMessageSource.php',
  454. 'CNumberFormatter' => '/i18n/CNumberFormatter.php',
  455. 'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
  456. 'CGettextFile' => '/i18n/gettext/CGettextFile.php',
  457. 'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
  458. 'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
  459. 'CChainedLogFilter' => '/logging/CChainedLogFilter.php',
  460. 'CDbLogRoute' => '/logging/CDbLogRoute.php',
  461. 'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
  462. 'CNoteLogRoute' => '/logging/CNoteLogRoute.php',
  463. 'CFileLogRoute' => '/logging/CFileLogRoute.php',
  464. 'CLogFilter' => '/logging/CLogFilter.php',
  465. 'CLogRoute' => '/logging/CLogRoute.php',
  466. 'CLogRouter' => '/logging/CLogRouter.php',
  467. 'CLogger' => '/logging/CLogger.php',
  468. 'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
  469. 'CSysLogRoute' => '/logging/CSysLogRoute.php',
  470. 'CWebLogRoute' => '/logging/CWebLogRoute.php',
  471. 'CDateTimeParser' => '/utils/CDateTimeParser.php',
  472. 'CFileHelper' => '/utils/CFileHelper.php',
  473. 'CFormatter' => '/utils/CFormatter.php',
  474. 'CLocalizedFormatter' => '/utils/CLocalizedFormatter.php',
  475. 'CMarkdownParser' => '/utils/CMarkdownParser.php',
  476. 'CPasswordHelper' => '/utils/CPasswordHelper.php',
  477. 'CPropertyValue' => '/utils/CPropertyValue.php',
  478. 'CTimestamp' => '/utils/CTimestamp.php',
  479. 'CVarDumper' => '/utils/CVarDumper.php',
  480. 'CBooleanValidator' => '/validators/CBooleanValidator.php',
  481. 'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
  482. 'CCompareValidator' => '/validators/CCompareValidator.php',
  483. 'CDateValidator' => '/validators/CDateValidator.php',
  484. 'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
  485. 'CEmailValidator' => '/validators/CEmailValidator.php',
  486. 'CExistValidator' => '/validators/CExistValidator.php',
  487. 'CFileValidator' => '/validators/CFileValidator.php',
  488. 'CFilterValidator' => '/validators/CFilterValidator.php',
  489. 'CInlineValidator' => '/validators/CInlineValidator.php',
  490. 'CNumberValidator' => '/validators/CNumberValidator.php',
  491. 'CRangeValidator' => '/validators/CRangeValidator.php',
  492. 'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
  493. 'CRequiredValidator' => '/validators/CRequiredValidator.php',
  494. 'CSafeValidator' => '/validators/CSafeValidator.php',
  495. 'CStringValidator' => '/validators/CStringValidator.php',
  496. 'CTypeValidator' => '/validators/CTypeValidator.php',
  497. 'CUniqueValidator' => '/validators/CUniqueValidator.php',
  498. 'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
  499. 'CUrlValidator' => '/validators/CUrlValidator.php',
  500. 'CValidator' => '/validators/CValidator.php',
  501. 'CActiveDataProvider' => '/web/CActiveDataProvider.php',
  502. 'CArrayDataProvider' => '/web/CArrayDataProvider.php',
  503. 'CAssetManager' => '/web/CAssetManager.php',
  504. 'CBaseController' => '/web/CBaseController.php',
  505. 'CCacheHttpSession' => '/web/CCacheHttpSession.php',
  506. 'CClientScript' => '/web/CClientScript.php',
  507. 'CController' => '/web/CController.php',
  508. 'CDataProvider' => '/web/CDataProvider.php',
  509. 'CDataProviderIterator' => '/web/CDataProviderIterator.php',
  510. 'CDbHttpSession' => '/web/CDbHttpSession.php',
  511. 'CExtController' => '/web/CExtController.php',
  512. 'CFormModel' => '/web/CFormModel.php',
  513. 'CHttpCookie' => '/web/CHttpCookie.php',
  514. 'CHttpRequest' => '/web/CHttpRequest.php',
  515. 'CHttpSession' => '/web/CHttpSession.php',
  516. 'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
  517. 'COutputEvent' => '/web/COutputEvent.php',
  518. 'CPagination' => '/web/CPagination.php',
  519. 'CSort' => '/web/CSort.php',
  520. 'CSqlDataProvider' => '/web/CSqlDataProvider.php',
  521. 'CTheme' => '/web/CTheme.php',
  522. 'CThemeManager' => '/web/CThemeManager.php',
  523. 'CUploadedFile' => '/web/CUploadedFile.php',
  524. 'CUrlManager' => '/web/CUrlManager.php',
  525. 'CWebApplication' => '/web/CWebApplication.php',
  526. 'CWebModule' => '/web/CWebModule.php',
  527. 'CWidgetFactory' => '/web/CWidgetFactory.php',
  528. 'CAction' => '/web/actions/CAction.php',
  529. 'CInlineAction' => '/web/actions/CInlineAction.php',
  530. 'CViewAction' => '/web/actions/CViewAction.php',
  531. 'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
  532. 'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
  533. 'CAuthItem' => '/web/auth/CAuthItem.php',
  534. 'CAuthManager' => '/web/auth/CAuthManager.php',
  535. 'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
  536. 'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
  537. 'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
  538. 'CUserIdentity' => '/web/auth/CUserIdentity.php',
  539. 'CWebUser' => '/web/auth/CWebUser.php',
  540. 'CFilter' => '/web/filters/CFilter.php',
  541. 'CFilterChain' => '/web/filters/CFilterChain.php',
  542. 'CHttpCacheFilter' => '/web/filters/CHttpCacheFilter.php',
  543. 'CInlineFilter' => '/web/filters/CInlineFilter.php',
  544. 'CForm' => '/web/form/CForm.php',
  545. 'CFormButtonElement' => '/web/form/CFormButtonElement.php',
  546. 'CFormElement' => '/web/form/CFormElement.php',
  547. 'CFormElementCollection' => '/web/form/CFormElementCollection.php',
  548. 'CFormInputElement' => '/web/form/CFormInputElement.php',
  549. 'CFormStringElement' => '/web/form/CFormStringElement.php',
  550. 'CGoogleApi' => '/web/helpers/CGoogleApi.php',
  551. 'CHtml' => '/web/helpers/CHtml.php',
  552. 'CJSON' => '/web/helpers/CJSON.php',
  553. 'CJavaScript' => '/web/helpers/CJavaScript.php',
  554. 'CJavaScriptExpression' => '/web/helpers/CJavaScriptExpression.php',
  555. 'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
  556. 'CViewRenderer' => '/web/renderers/CViewRenderer.php',
  557. 'CWebService' => '/web/services/CWebService.php',
  558. 'CWebServiceAction' => '/web/services/CWebServiceAction.php',
  559. 'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
  560. 'CActiveForm' => '/web/widgets/CActiveForm.php',
  561. 'CAutoComplete' => '/web/widgets/CAutoComplete.php',
  562. 'CClipWidget' => '/web/widgets/CClipWidget.php',
  563. 'CContentDecorator' => '/web/widgets/CContentDecorator.php',
  564. 'CFilterWidget' => '/web/widgets/CFilterWidget.php',
  565. 'CFlexWidget' => '/web/widgets/CFlexWidget.php',
  566. 'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
  567. 'CInputWidget' => '/web/widgets/CInputWidget.php',
  568. 'CMarkdown' => '/web/widgets/CMarkdown.php',
  569. 'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
  570. 'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
  571. 'COutputCache' => '/web/widgets/COutputCache.php',
  572. 'COutputProcessor' => '/web/widgets/COutputProcessor.php',
  573. 'CStarRating' => '/web/widgets/CStarRating.php',
  574. 'CTabView' => '/web/widgets/CTabView.php',
  575. 'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
  576. 'CTreeView' => '/web/widgets/CTreeView.php',
  577. 'CWidget' => '/web/widgets/CWidget.php',
  578. 'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
  579. 'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
  580. 'CBasePager' => '/web/widgets/pagers/CBasePager.php',
  581. 'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
  582. 'CListPager' => '/web/widgets/pagers/CListPager.php',
  583. );
  584. }
  585. spl_autoload_register(array('YiiBase','autoload'));
  586. class Yii extends YiiBase
  587. {
  588. }
  589. class CComponent
  590. {
  591. private $_e;
  592. private $_m;
  593. public function __get($name)
  594. {
  595. $getter='get'.$name;
  596. if(method_exists($this,$getter))
  597. return $this->$getter();
  598. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  599. {
  600. // duplicating getEventHandlers() here for performance
  601. $name=strtolower($name);
  602. if(!isset($this->_e[$name]))
  603. $this->_e[$name]=new CList;
  604. return $this->_e[$name];
  605. }
  606. elseif(isset($this->_m[$name]))
  607. return $this->_m[$name];
  608. elseif(is_array($this->_m))
  609. {
  610. foreach($this->_m as $object)
  611. {
  612. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  613. return $object->$name;
  614. }
  615. }
  616. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  617. array('{class}'=>get_class($this), '{property}'=>$name)));
  618. }
  619. public function __set($name,$value)
  620. {
  621. $setter='set'.$name;
  622. if(method_exists($this,$setter))
  623. return $this->$setter($value);
  624. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  625. {
  626. // duplicating getEventHandlers() here for performance
  627. $name=strtolower($name);
  628. if(!isset($this->_e[$name]))
  629. $this->_e[$name]=new CList;
  630. return $this->_e[$name]->add($value);
  631. }
  632. elseif(is_array($this->_m))
  633. {
  634. foreach($this->_m as $object)
  635. {
  636. if($object->getEnabled() && (property_exists($object,$name) || $object->canSetProperty($name)))
  637. return $object->$name=$value;
  638. }
  639. }
  640. if(method_exists($this,'get'.$name))
  641. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  642. array('{class}'=>get_class($this), '{property}'=>$name)));
  643. else
  644. throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
  645. array('{class}'=>get_class($this), '{property}'=>$name)));
  646. }
  647. public function __isset($name)
  648. {
  649. $getter='get'.$name;
  650. if(method_exists($this,$getter))
  651. return $this->$getter()!==null;
  652. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  653. {
  654. $name=strtolower($name);
  655. return isset($this->_e[$name]) && $this->_e[$name]->getCount();
  656. }
  657. elseif(is_array($this->_m))
  658. {
  659. if(isset($this->_m[$name]))
  660. return true;
  661. foreach($this->_m as $object)
  662. {
  663. if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
  664. return $object->$name!==null;
  665. }
  666. }
  667. return false;
  668. }
  669. public function __unset($name)
  670. {
  671. $setter='set'.$name;
  672. if(method_exists($this,$setter))
  673. $this->$setter(null);
  674. elseif(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  675. unset($this->_e[strtolower($name)]);
  676. elseif(is_array($this->_m))
  677. {
  678. if(isset($this->_m[$name]))
  679. $this->detachBehavior($name);
  680. else
  681. {
  682. foreach($this->_m as $object)
  683. {
  684. if($object->getEnabled())
  685. {
  686. if(property_exists($object,$name))
  687. return $object->$name=null;
  688. elseif($object->canSetProperty($name))
  689. return $object->$setter(null);
  690. }
  691. }
  692. }
  693. }
  694. elseif(method_exists($this,'get'.$name))
  695. throw new CException(Yii::t('yii','Property "{class}.{property}" is read only.',
  696. array('{class}'=>get_class($this), '{property}'=>$name)));
  697. }
  698. public function __call($name,$parameters)
  699. {
  700. if($this->_m!==null)
  701. {
  702. foreach($this->_m as $object)
  703. {
  704. if($object->getEnabled() && method_exists($object,$name))
  705. return call_user_func_array(array($object,$name),$parameters);
  706. }
  707. }
  708. if(class_exists('Closure', false) && ($this->canGetProperty($name) || property_exists($this, $name)) && $this->$name instanceof Closure)
  709. return call_user_func_array($this->$name, $parameters);
  710. throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
  711. array('{class}'=>get_class($this), '{name}'=>$name)));
  712. }
  713. public function asa($behavior)
  714. {
  715. return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;
  716. }
  717. public function attachBehaviors($behaviors)
  718. {
  719. foreach($behaviors as $name=>$behavior)
  720. $this->attachBehavior($name,$behavior);
  721. }
  722. public function detachBehaviors()
  723. {
  724. if($this->_m!==null)
  725. {
  726. foreach($this->_m as $name=>$behavior)
  727. $this->detachBehavior($name);
  728. $this->_m=null;
  729. }
  730. }
  731. public function attachBehavior($name,$behavior)
  732. {
  733. if(!($behavior instanceof IBehavior))
  734. $behavior=Yii::createComponent($behavior);
  735. $behavior->setEnabled(true);
  736. $behavior->attach($this);
  737. return $this->_m[$name]=$behavior;
  738. }
  739. public function detachBehavior($name)
  740. {
  741. if(isset($this->_m[$name]))
  742. {
  743. $this->_m[$name]->detach($this);
  744. $behavior=$this->_m[$name];
  745. unset($this->_m[$name]);
  746. return $behavior;
  747. }
  748. }
  749. public function enableBehaviors()
  750. {
  751. if($this->_m!==null)
  752. {
  753. foreach($this->_m as $behavior)
  754. $behavior->setEnabled(true);
  755. }
  756. }
  757. public function disableBehaviors()
  758. {
  759. if($this->_m!==null)
  760. {
  761. foreach($this->_m as $behavior)
  762. $behavior->setEnabled(false);
  763. }
  764. }
  765. public function enableBehavior($name)
  766. {
  767. if(isset($this->_m[$name]))
  768. $this->_m[$name]->setEnabled(true);
  769. }
  770. public function disableBehavior($name)
  771. {
  772. if(isset($this->_m[$name]))
  773. $this->_m[$name]->setEnabled(false);
  774. }
  775. public function hasProperty($name)
  776. {
  777. return method_exists($this,'get'.$name) || method_exists($this,'set'.$name);
  778. }
  779. public function canGetProperty($name)
  780. {
  781. return method_exists($this,'get'.$name);
  782. }
  783. public function canSetProperty($name)
  784. {
  785. return method_exists($this,'set'.$name);
  786. }
  787. public function hasEvent($name)
  788. {
  789. return !strncasecmp($name,'on',2) && method_exists($this,$name);
  790. }
  791. public function hasEventHandler($name)
  792. {
  793. $name=strtolower($name);
  794. return isset($this->_e[$name]) && $this->_e[$name]->getCount()>0;
  795. }
  796. public function getEventHandlers($name)
  797. {
  798. if($this->hasEvent($name))
  799. {
  800. $name=strtolower($name);
  801. if(!isset($this->_e[$name]))
  802. $this->_e[$name]=new CList;
  803. return $this->_e[$name];
  804. }
  805. else
  806. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  807. array('{class}'=>get_class($this), '{event}'=>$name)));
  808. }
  809. public function attachEventHandler($name,$handler)
  810. {
  811. $this->getEventHandlers($name)->add($handler);
  812. }
  813. public function detachEventHandler($name,$handler)
  814. {
  815. if($this->hasEventHandler($name))
  816. return $this->getEventHandlers($name)->remove($handler)!==false;
  817. else
  818. return false;
  819. }
  820. public function raiseEvent($name,$event)
  821. {
  822. $name=strtolower($name);
  823. if(isset($this->_e[$name]))
  824. {
  825. foreach($this->_e[$name] as $handler)
  826. {
  827. if(is_string($handler))
  828. call_user_func($handler,$event);
  829. elseif(is_callable($handler,true))
  830. {
  831. if(is_array($handler))
  832. {
  833. // an array: 0 - object, 1 - method name
  834. list($object,$method)=$handler;
  835. if(is_string($object)) // static method call
  836. call_user_func($handler,$event);
  837. elseif(method_exists($object,$method))
  838. $object->$method($event);
  839. else
  840. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  841. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>$handler[1])));
  842. }
  843. else // PHP 5.3: anonymous function
  844. call_user_func($handler,$event);
  845. }
  846. else
  847. throw new CException(Yii::t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
  848. array('{class}'=>get_class($this), '{event}'=>$name, '{handler}'=>gettype($handler))));
  849. // stop further handling if param.handled is set true
  850. if(($event instanceof CEvent) && $event->handled)
  851. return;
  852. }
  853. }
  854. elseif(YII_DEBUG && !$this->hasEvent($name))
  855. throw new CException(Yii::t('yii','Event "{class}.{event}" is not defined.',
  856. array('{class}'=>get_class($this), '{event}'=>$name)));
  857. }
  858. public function evaluateExpression($_expression_,$_data_=array())
  859. {
  860. if(is_string($_expression_))
  861. {
  862. extract($_data_);
  863. return eval('return '.$_expression_.';');
  864. }
  865. else
  866. {
  867. $_data_[]=$this;
  868. return call_user_func_array($_expression_, $_data_);
  869. }
  870. }
  871. }
  872. class CEvent extends CComponent
  873. {
  874. public $sender;
  875. public $handled=false;
  876. public $params;
  877. public function __construct($sender=null,$params=null)
  878. {
  879. $this->sender=$sender;
  880. $this->params=$params;
  881. }
  882. }
  883. class CEnumerable
  884. {
  885. }
  886. abstract class CModule extends CComponent
  887. {
  888. public $preload=array();
  889. public $behaviors=array();
  890. private $_id;
  891. private $_parentModule;
  892. private $_basePath;
  893. private $_modulePath;
  894. private $_params;
  895. private $_modules=array();
  896. private $_moduleConfig=array();
  897. private $_components=array();
  898. private $_componentConfig=array();
  899. public function __construct($id,$parent,$config=null)
  900. {
  901. $this->_id=$id;
  902. $this->_parentModule=$parent;
  903. // set basePath at early as possible to avoid trouble
  904. if(is_string($config))
  905. $config=require($config);
  906. if(isset($config['basePath']))
  907. {
  908. $this->setBasePath($config['basePath']);
  909. unset($config['basePath']);
  910. }
  911. Yii::setPathOfAlias($id,$this->getBasePath());
  912. $this->preinit();
  913. $this->configure($config);
  914. $this->attachBehaviors($this->behaviors);
  915. $this->preloadComponents();
  916. $this->init();
  917. }
  918. public function __get($name)
  919. {
  920. if($this->hasComponent($name))
  921. return $this->getComponent($name);
  922. else
  923. return parent::__get($name);
  924. }
  925. public function __isset($name)
  926. {
  927. if($this->hasComponent($name))
  928. return $this->getComponent($name)!==null;
  929. else
  930. return parent::__isset($name);
  931. }
  932. public function getId()
  933. {
  934. return $this->_id;
  935. }
  936. public function setId($id)
  937. {
  938. $this->_id=$id;
  939. }
  940. public function getBasePath()
  941. {
  942. if($this->_basePath===null)
  943. {
  944. $class=new ReflectionClass(get_class($this));
  945. $this->_basePath=dirname($class->getFileName());
  946. }
  947. return $this->_basePath;
  948. }
  949. public function setBasePath($path)
  950. {
  951. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  952. throw new CException(Yii::t('yii','Base path "{path}" is not a valid directory.',
  953. array('{path}'=>$path)));
  954. }
  955. public function getParams()
  956. {
  957. if($this->_params!==null)
  958. return $this->_params;
  959. else
  960. {
  961. $this->_params=new CAttributeCollection;
  962. $this->_params->caseSensitive=true;
  963. return $this->_params;
  964. }
  965. }
  966. public function setParams($value)
  967. {
  968. $params=$this->getParams();
  969. foreach($value as $k=>$v)
  970. $params->add($k,$v);
  971. }
  972. public function getModulePath()
  973. {
  974. if($this->_modulePath!==null)
  975. return $this->_modulePath;
  976. else
  977. return $this->_modulePath=$this->getBasePath().DIRECTORY_SEPARATOR.'modules';
  978. }
  979. public function setModulePath($value)
  980. {
  981. if(($this->_modulePath=realpath($value))===false || !is_dir($this->_modulePath))
  982. throw new CException(Yii::t('yii','The module path "{path}" is not a valid directory.',
  983. array('{path}'=>$value)));
  984. }
  985. public function setImport($aliases)
  986. {
  987. foreach($aliases as $alias)
  988. Yii::import($alias);
  989. }
  990. public function setAliases($mappings)
  991. {
  992. foreach($mappings as $name=>$alias)
  993. {
  994. if(($path=Yii::getPathOfAlias($alias))!==false)
  995. Yii::setPathOfAlias($name,$path);
  996. else
  997. Yii::setPathOfAlias($name,$alias);
  998. }
  999. }
  1000. public function getParentModule()
  1001. {
  1002. return $this->_parentModule;
  1003. }
  1004. public function getModule($id)
  1005. {
  1006. if(isset($this->_modules[$id]) || array_key_exists($id,$this->_modules))
  1007. return $this->_modules[$id];
  1008. elseif(isset($this->_moduleConfig[$id]))
  1009. {
  1010. $config=$this->_moduleConfig[$id];
  1011. if(!isset($config['enabled']) || $config['enabled'])
  1012. {
  1013. $class=$config['class'];
  1014. unset($config['class'], $config['enabled']);
  1015. if($this===Yii::app())
  1016. $module=Yii::createComponent($class,$id,null,$config);
  1017. else
  1018. $module=Yii::createComponent($class,$this->getId().'/'.$id,$this,$config);
  1019. return $this->_modules[$id]=$module;
  1020. }
  1021. }
  1022. }
  1023. public function hasModule($id)
  1024. {
  1025. return isset($this->_moduleConfig[$id]) || isset($this->_modules[$id]);
  1026. }
  1027. public function getModules()
  1028. {
  1029. return $this->_moduleConfig;
  1030. }
  1031. public function setModules($modules,$merge=true)
  1032. {
  1033. foreach($modules as $id=>$module)
  1034. {
  1035. if(is_int($id))
  1036. {
  1037. $id=$module;
  1038. $module=array();
  1039. }
  1040. if(isset($this->_moduleConfig[$id]) && $merge)
  1041. $this->_moduleConfig[$id]=CMap::mergeArray($this->_moduleConfig[$id],$module);
  1042. else
  1043. {
  1044. if(!isset($module['class']))
  1045. {
  1046. if (Yii::getPathOfAlias($id)===false)
  1047. Yii::setPathOfAlias($id,$this->getModulePath().DIRECTORY_SEPARATOR.$id);
  1048. $module['class']=$id.'.'.ucfirst($id).'Module';
  1049. }
  1050. $this->_moduleConfig[$id]=$module;
  1051. }
  1052. }
  1053. }
  1054. public function hasComponent($id)
  1055. {
  1056. return isset($this->_components[$id]) || isset($this->_componentConfig[$id]);
  1057. }
  1058. public function getComponent($id,$createIfNull=true)
  1059. {
  1060. if(isset($this->_components[$id]))
  1061. return $this->_components[$id];
  1062. elseif(isset($this->_componentConfig[$id]) && $createIfNull)
  1063. {
  1064. $config=$this->_componentConfig[$id];
  1065. if(!isset($config['enabled']) || $config['enabled'])
  1066. {
  1067. unset($config['enabled']);
  1068. $component=Yii::createComponent($config);
  1069. $component->init();
  1070. return $this->_components[$id]=$component;
  1071. }
  1072. }
  1073. }
  1074. public function setComponent($id,$component,$merge=true)
  1075. {
  1076. if($component===null)
  1077. {
  1078. unset($this->_components[$id]);
  1079. return;
  1080. }
  1081. elseif($component instanceof IApplicationComponent)
  1082. {
  1083. $this->_components[$id]=$component;
  1084. if(!$component->getIsInitialized())
  1085. $component->init();
  1086. return;
  1087. }
  1088. elseif(isset($this->_components[$id]))
  1089. {
  1090. if(isset($component['class']) && get_class($this->_components[$id])!==$component['class'])
  1091. {
  1092. unset($this->_components[$id]);
  1093. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1094. return;
  1095. }
  1096. foreach($component as $key=>$value)
  1097. {
  1098. if($key!=='class')
  1099. $this->_components[$id]->$key=$value;
  1100. }
  1101. }
  1102. elseif(isset($this->_componentConfig[$id]['class'],$component['class'])
  1103. && $this->_componentConfig[$id]['class']!==$component['class'])
  1104. {
  1105. $this->_componentConfig[$id]=$component; //we should ignore merge here
  1106. return;
  1107. }
  1108. if(isset($this->_componentConfig[$id]) && $merge)
  1109. $this->_componentConfig[$id]=CMap::mergeArray($this->_componentConfig[$id],$component);
  1110. else
  1111. $this->_componentConfig[$id]=$component;
  1112. }
  1113. public function getComponents($loadedOnly=true)
  1114. {
  1115. if($loadedOnly)
  1116. return $this->_components;
  1117. else
  1118. return array_merge($this->_componentConfig, $this->_components);
  1119. }
  1120. public function setComponents($components,$merge=true)
  1121. {
  1122. foreach($components as $id=>$component)
  1123. $this->setComponent($id,$component,$merge);
  1124. }
  1125. public function configure($config)
  1126. {
  1127. if(is_array($config))
  1128. {
  1129. foreach($config as $key=>$value)
  1130. $this->$key=$value;
  1131. }
  1132. }
  1133. protected function preloadComponents()
  1134. {
  1135. foreach($this->preload as $id)
  1136. $this->getComponent($id);
  1137. }
  1138. protected function preinit()
  1139. {
  1140. }
  1141. protected function init()
  1142. {
  1143. }
  1144. }
  1145. abstract class CApplication extends CModule
  1146. {
  1147. public $name='My Application';
  1148. public $charset='UTF-8';
  1149. public $sourceLanguage='en_us';
  1150. public $localeClass='CLocale';
  1151. private $_id;
  1152. private $_basePath;
  1153. private $_runtimePath;
  1154. private $_extensionPath;
  1155. private $_globalState;
  1156. private $_stateChanged;
  1157. private $_ended=false;
  1158. private $_language;
  1159. private $_homeUrl;
  1160. abstract public function processRequest();
  1161. public function __construct($config=null)
  1162. {
  1163. Yii::setApplication($this);
  1164. // set basePath at early as possible to avoid trouble
  1165. if(is_string($config))
  1166. $config=require($config);
  1167. if(isset($config['basePath']))
  1168. {
  1169. $this->setBasePath($config['basePath']);
  1170. unset($config['basePath']);
  1171. }
  1172. else
  1173. $this->setBasePath('protected');
  1174. Yii::setPathOfAlias('application',$this->getBasePath());
  1175. Yii::setPathOfAlias('webroot',dirname($_SERVER['SCRIPT_FILENAME']));
  1176. if(isset($config['extensionPath']))
  1177. {
  1178. $this->setExtensionPath($config['extensionPath']);
  1179. unset($config['extensionPath']);
  1180. }
  1181. else
  1182. Yii::setPathOfAlias('ext',$this->getBasePath().DIRECTORY_SEPARATOR.'extensions');
  1183. if(isset($config['aliases']))
  1184. {
  1185. $this->setAliases($config['aliases']);
  1186. unset($config['aliases']);
  1187. }
  1188. $this->preinit();
  1189. $this->initSystemHandlers();
  1190. $this->registerCoreComponents();
  1191. $this->configure($config);
  1192. $this->attachBehaviors($this->behaviors);
  1193. $this->preloadComponents();
  1194. $this->init();
  1195. }
  1196. public function run()
  1197. {
  1198. if($this->hasEventHandler('onBeginRequest'))
  1199. $this->onBeginRequest(new CEvent($this));
  1200. register_shutdown_function(array($this,'end'),0,false);
  1201. $this->processRequest();
  1202. if($this->hasEventHandler('onEndRequest'))
  1203. $this->onEndRequest(new CEvent($this));
  1204. }
  1205. public function end($status=0,$exit=true)
  1206. {
  1207. if($this->hasEventHandler('onEndRequest'))
  1208. $this->onEndRequest(new CEvent($this));
  1209. if($exit)
  1210. exit($status);
  1211. }
  1212. public function onBeginRequest($event)
  1213. {
  1214. $this->raiseEvent('onBeginRequest',$event);
  1215. }
  1216. public function onEndRequest($event)
  1217. {
  1218. if(!$this->_ended)
  1219. {
  1220. $this->_ended=true;
  1221. $this->raiseEvent('onEndRequest',$event);
  1222. }
  1223. }
  1224. public function getId()
  1225. {
  1226. if($this->_id!==null)
  1227. return $this->_id;
  1228. else
  1229. return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
  1230. }
  1231. public function setId($id)
  1232. {
  1233. $this->_id=$id;
  1234. }
  1235. public function getBasePath()
  1236. {
  1237. return $this->_basePath;
  1238. }
  1239. public function setBasePath($path)
  1240. {
  1241. if(($this->_basePath=realpath($path))===false || !is_dir($this->_basePath))
  1242. throw new CException(Yii::t('yii','Application base path "{path}" is not a valid directory.',
  1243. array('{path}'=>$path)));
  1244. }
  1245. public function getRuntimePath()
  1246. {
  1247. if($this->_runtimePath!==null)
  1248. return $this->_runtimePath;
  1249. else
  1250. {
  1251. $this->setRuntimePath($this->getBasePath().DIRECTORY_SEPARATOR.'runtime');
  1252. return $this->_runtimePath;
  1253. }
  1254. }
  1255. public function setRuntimePath($path)
  1256. {
  1257. if(($runtimePath=realpath($path))===false || !is_dir($runtimePath) || !is_writable($runtimePath))
  1258. throw new CException(Yii::t('yii','Application runtime path "{path}" is not valid. Please make sure it is a directory writable by the Web server process.',
  1259. array('{path}'=>$path)));
  1260. $this->_runtimePath=$runtimePath;
  1261. }
  1262. public function getExtensionPath()
  1263. {
  1264. return Yii::getPathOfAlias('ext');
  1265. }
  1266. public function setExtensionPath($path)
  1267. {
  1268. if(($extensionPath=realpath($path))===false || !is_dir($extensionPath))
  1269. throw new CException(Yii::t('yii','Extension path "{path}" does not exist.',
  1270. array('{path}'=>$path)));
  1271. Yii::setPathOfAlias('ext',$extensionPath);
  1272. }
  1273. public function getLanguage()
  1274. {
  1275. return $this->_language===null ? $this->sourceLanguage : $this->_language;
  1276. }
  1277. public function setLanguage($language)
  1278. {
  1279. $this->_language=$language;
  1280. }
  1281. public function getTimeZone()
  1282. {
  1283. return date_default_timezone_get();
  1284. }
  1285. public function setTimeZone($value)
  1286. {
  1287. date_default_timezone_set($value);
  1288. }
  1289. public function findLocalizedFile($srcFile,$srcLanguage=null,$language=null)
  1290. {
  1291. if($srcLanguage===null)
  1292. $srcLanguage=$this->sourceLanguage;
  1293. if($language===null)
  1294. $language=$this->getLanguage();
  1295. if($language===$srcLanguage)
  1296. return $srcFile;
  1297. $desiredFile=dirname($srcFile).DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.basename($srcFile);
  1298. return is_file($desiredFile) ? $desiredFile : $srcFile;
  1299. }
  1300. public function getLocale($localeID=null)
  1301. {
  1302. return call_user_func_array(array($this->localeClass, 'getInstance'),array($localeID===null?$this->getLanguage():$localeID));
  1303. }
  1304. public function getLocaleDataPath()
  1305. {
  1306. $vars=get_class_vars($this->localeClass);
  1307. if(empty($vars['dataPath']))
  1308. return Yii::getPathOfAlias('system.i18n.data');
  1309. return $vars['dataPath'];
  1310. }
  1311. public function setLocaleDataPath($value)
  1312. {
  1313. $property=new ReflectionProperty($this->localeClass,'dataPath');
  1314. $property->setValue($value);
  1315. }
  1316. public function getNumberFormatter()
  1317. {
  1318. return $this->getLocale()->getNumberFormatter();
  1319. }
  1320. public function getDateFormatter()
  1321. {
  1322. return $this->getLocale()->getDateFormatter();
  1323. }
  1324. public function getDb()
  1325. {
  1326. return $this->getComponent('db');
  1327. }
  1328. public function getErrorHandler()
  1329. {
  1330. return $this->getComponent('errorHandler');
  1331. }
  1332. public function getSecurityManager()
  1333. {
  1334. return $this->getComponent('securityManager');
  1335. }
  1336. public function getStatePersister()
  1337. {
  1338. return $this->getComponent('statePersister');
  1339. }
  1340. public function getCache()
  1341. {
  1342. return $this->getComponent('cache');
  1343. }
  1344. public function getCoreMessages()
  1345. {
  1346. return $this->getComponent('coreMessages');
  1347. }
  1348. public function getMessages()
  1349. {
  1350. return $this->getComponent('messages');
  1351. }
  1352. public function getRequest()
  1353. {
  1354. return $this->getComponent('request');
  1355. }
  1356. public function getUrlManager()
  1357. {
  1358. return $this->getComponent('urlManager');
  1359. }
  1360. public function getController()
  1361. {
  1362. return null;
  1363. }
  1364. public function createUrl($route,$params=array(),$ampersand='&')
  1365. {
  1366. return $this->getUrlManager()->createUrl($route,$params,$ampersand);
  1367. }
  1368. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  1369. {
  1370. $url=$this->createUrl($route,$params,$ampersand);
  1371. if(strpos($url,'http')===0)
  1372. return $url;
  1373. else
  1374. return $this->getRequest()->getHostInfo($schema).$url;
  1375. }
  1376. public function getBaseUrl($absolute=false)
  1377. {
  1378. return $this->getRequest()->getBaseUrl($absolute);
  1379. }
  1380. public function getHomeUrl()
  1381. {
  1382. if($this->_homeUrl===null)
  1383. {
  1384. if($this->getUrlManager()->showScriptName)
  1385. return $this->getRequest()->getScriptUrl();
  1386. else
  1387. return $this->getRequest()->getBaseUrl().'/';
  1388. }
  1389. else
  1390. return $this->_homeUrl;
  1391. }
  1392. public function setHomeUrl($value)
  1393. {
  1394. $this->_homeUrl=$value;
  1395. }
  1396. public function getGlobalState($key,$defaultValue=null)
  1397. {
  1398. if($this->_globalState===null)
  1399. $this->loadGlobalState();
  1400. if(isset($this->_globalState[$key]))
  1401. return $this->_globalState[$key];
  1402. else
  1403. return $defaultValue;
  1404. }
  1405. public function setGlobalState($key,$value,$defaultValue=null)
  1406. {
  1407. if($this->_globalState===null)
  1408. $this->loadGlobalState();
  1409. $changed=$this->_stateChanged;
  1410. if($value===$defaultValue)
  1411. {
  1412. if(isset($this->_globalState[$key]))
  1413. {
  1414. unset($this->_globalState[$key]);
  1415. $this->_stateChanged=true;
  1416. }
  1417. }
  1418. elseif(!isset($this->_globalState[$key]) || $this->_globalState[$key]!==$value)
  1419. {
  1420. $this->_globalState[$key]=$value;
  1421. $this->_stateChanged=true;
  1422. }
  1423. if($this->_stateChanged!==$changed)
  1424. $this->attachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1425. }
  1426. public function clearGlobalState($key)
  1427. {
  1428. $this->setGlobalState($key,true,true);
  1429. }
  1430. public function loadGlobalState()
  1431. {
  1432. $persister=$this->getStatePersister();
  1433. if(($this->_globalState=$persister->load())===null)
  1434. $this->_globalState=array();
  1435. $this->_stateChanged=false;
  1436. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1437. }
  1438. public function saveGlobalState()
  1439. {
  1440. if($this->_stateChanged)
  1441. {
  1442. $this->_stateChanged=false;
  1443. $this->detachEventHandler('onEndRequest',array($this,'saveGlobalState'));
  1444. $this->getStatePersister()->save($this->_globalState);
  1445. }
  1446. }
  1447. public function handleException($exception)
  1448. {
  1449. // disable error capturing to avoid recursive errors
  1450. restore_error_handler();
  1451. restore_exception_handler();
  1452. $category='exception.'.get_class($exception);
  1453. if($exception instanceof CHttpException)
  1454. $category.='.'.$exception->statusCode;
  1455. // php <5.2 doesn't support string conversion auto-magically
  1456. $message=$exception->__toString();
  1457. if(isset($_SERVER['REQUEST_URI']))
  1458. $message.="\nREQUEST_URI=".$_SERVER['REQUEST_URI'];
  1459. if(isset($_SERVER['HTTP_REFERER']))
  1460. $message.="\nHTTP_REFERER=".$_SERVER['HTTP_REFERER'];
  1461. $message.="\n---";
  1462. Yii::log($message,CLogger::LEVEL_ERROR,$category);
  1463. try
  1464. {
  1465. $event=new CExceptionEvent($this,$exception);
  1466. $this->onException($event);
  1467. if(!$event->handled)
  1468. {
  1469. // try an error handler
  1470. if(($handler=$this->getErrorHandler())!==null)
  1471. $handler->handle($event);
  1472. else
  1473. $this->displayException($exception);
  1474. }
  1475. }
  1476. catch(Exception $e)
  1477. {
  1478. $this->displayException($e);
  1479. }
  1480. try
  1481. {
  1482. $this->end(1);
  1483. }
  1484. catch(Exception $e)
  1485. {
  1486. // use the most primitive way to log error
  1487. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1488. $msg .= $e->getTraceAsString()."\n";
  1489. $msg .= "Previous exception:\n";
  1490. $msg .= get_class($exception).': '.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().")\n";
  1491. $msg .= $exception->getTraceAsString()."\n";
  1492. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1493. error_log($msg);
  1494. exit(1);
  1495. }
  1496. }
  1497. public function handleError($code,$message,$file,$line)
  1498. {
  1499. if($code & error_reporting())
  1500. {
  1501. // disable error capturing to avoid recursive errors
  1502. restore_error_handler();
  1503. restore_exception_handler();
  1504. $log="$message ($file:$line)\nStack trace:\n";
  1505. $trace=debug_backtrace();
  1506. // skip the first 3 stacks as they do not tell the error position
  1507. if(count($trace)>3)
  1508. $trace=array_slice($trace,3);
  1509. foreach($trace as $i=>$t)
  1510. {
  1511. if(!isset($t['file']))
  1512. $t['file']='unknown';
  1513. if(!isset($t['line']))
  1514. $t['line']=0;
  1515. if(!isset($t['function']))
  1516. $t['function']='unknown';
  1517. $log.="#$i {$t['file']}({$t['line']}): ";
  1518. if(isset($t['object']) && is_object($t['object']))
  1519. $log.=get_class($t['object']).'->';
  1520. $log.="{$t['function']}()\n";
  1521. }
  1522. if(isset($_SERVER['REQUEST_URI']))
  1523. $log.='REQUEST_URI='.$_SERVER['REQUEST_URI'];
  1524. Yii::log($log,CLogger::LEVEL_ERROR,'php');
  1525. try
  1526. {
  1527. Yii::import('CErrorEvent',true);
  1528. $event=new CErrorEvent($this,$code,$message,$file,$line);
  1529. $this->onError($event);
  1530. if(!$event->handled)
  1531. {
  1532. // try an error handler
  1533. if(($handler=$this->getErrorHandler())!==null)
  1534. $handler->handle($event);
  1535. else
  1536. $this->displayError($code,$message,$file,$line);
  1537. }
  1538. }
  1539. catch(Exception $e)
  1540. {
  1541. $this->displayException($e);
  1542. }
  1543. try
  1544. {
  1545. $this->end(1);
  1546. }
  1547. catch(Exception $e)
  1548. {
  1549. // use the most primitive way to log error
  1550. $msg = get_class($e).': '.$e->getMessage().' ('.$e->getFile().':'.$e->getLine().")\n";
  1551. $msg .= $e->getTraceAsString()."\n";
  1552. $msg .= "Previous error:\n";
  1553. $msg .= $log."\n";
  1554. $msg .= '$_SERVER='.var_export($_SERVER,true);
  1555. error_log($msg);
  1556. exit(1);
  1557. }
  1558. }
  1559. }
  1560. public function onException($event)
  1561. {
  1562. $this->raiseEvent('onException',$event);
  1563. }
  1564. public function onError($event)
  1565. {
  1566. $this->raiseEvent('onError',$event);
  1567. }
  1568. public function displayError($code,$message,$file,$line)
  1569. {
  1570. if(YII_DEBUG)
  1571. {
  1572. echo "<h1>PHP Error [$code]</h1>\n";
  1573. echo "<p>$message ($file:$line)</p>\n";
  1574. echo '<pre>';
  1575. $trace=debug_backtrace();
  1576. // skip the first 3 stacks as they do not tell the error position
  1577. if(count($trace)>3)
  1578. $trace=array_slice($trace,3);
  1579. foreach($trace as $i=>$t)
  1580. {
  1581. if(!isset($t['file']))
  1582. $t['file']='unknown';
  1583. if(!isset($t['line']))
  1584. $t['line']=0;
  1585. if(!isset($t['function']))
  1586. $t['function']='unknown';
  1587. echo "#$i {$t['file']}({$t['line']}): ";
  1588. if(isset($t['object']) && is_object($t['object']))
  1589. echo get_class($t['object']).'->';
  1590. echo "{$t['function']}()\n";
  1591. }
  1592. echo '</pre>';
  1593. }
  1594. else
  1595. {
  1596. echo "<h1>PHP Error [$code]</h1>\n";
  1597. echo "<p>$message</p>\n";
  1598. }
  1599. }
  1600. public function displayException($exception)
  1601. {
  1602. if(YII_DEBUG)
  1603. {
  1604. echo '<h1>'.get_class($exception)."</h1>\n";
  1605. echo '<p>'.$exception->getMessage().' ('.$exception->getFile().':'.$exception->getLine().')</p>';
  1606. echo '<pre>'.$exception->getTraceAsString().'</pre>';
  1607. }
  1608. else
  1609. {
  1610. echo '<h1>'.get_class($exception)."</h1>\n";
  1611. echo '<p>'.$exception->getMessage().'</p>';
  1612. }
  1613. }
  1614. protected function initSystemHandlers()
  1615. {
  1616. if(YII_ENABLE_EXCEPTION_HANDLER)
  1617. set_exception_handler(array($this,'handleException'));
  1618. if(YII_ENABLE_ERROR_HANDLER)
  1619. set_error_handler(array($this,'handleError'),error_reporting());
  1620. }
  1621. protected function registerCoreComponents()
  1622. {
  1623. $components=array(
  1624. 'coreMessages'=>array(
  1625. 'class'=>'CPhpMessageSource',
  1626. 'language'=>'en_us',
  1627. 'basePath'=>YII_PATH.DIRECTORY_SEPARATOR.'messages',
  1628. ),
  1629. 'db'=>array(
  1630. 'class'=>'CDbConnection',
  1631. ),
  1632. 'messages'=>array(
  1633. 'class'=>'CPhpMessageSource',
  1634. ),
  1635. 'errorHandler'=>array(
  1636. 'class'=>'CErrorHandler',
  1637. ),
  1638. 'securityManager'=>array(
  1639. 'class'=>'CSecurityManager',
  1640. ),
  1641. 'statePersister'=>array(
  1642. 'class'=>'CStatePersister',
  1643. ),
  1644. 'urlManager'=>array(
  1645. 'class'=>'CUrlManager',
  1646. ),
  1647. 'request'=>array(
  1648. 'class'=>'CHttpRequest',
  1649. ),
  1650. 'format'=>array(
  1651. 'class'=>'CFormatter',
  1652. ),
  1653. );
  1654. $this->setComponents($components);
  1655. }
  1656. }
  1657. class CWebApplication extends CApplication
  1658. {
  1659. public $defaultController='site';
  1660. public $layout='main';
  1661. public $controllerMap=array();
  1662. public $catchAllRequest;
  1663. public $controllerNamespace;
  1664. private $_controllerPath;
  1665. private $_viewPath;
  1666. private $_systemViewPath;
  1667. private $_layoutPath;
  1668. private $_controller;
  1669. private $_theme;
  1670. public function processRequest()
  1671. {
  1672. if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
  1673. {
  1674. $route=$this->catchAllRequest[0];
  1675. foreach(array_splice($this->catchAllRequest,1) as $name=>$value)
  1676. $_GET[$name]=$value;
  1677. }
  1678. else
  1679. $route=$this->getUrlManager()->parseUrl($this->getRequest());
  1680. $this->runController($route);
  1681. }
  1682. protected function registerCoreComponents()
  1683. {
  1684. parent::registerCoreComponents();
  1685. $components=array(
  1686. 'session'=>array(
  1687. 'class'=>'CHttpSession',
  1688. ),
  1689. 'assetManager'=>array(
  1690. 'class'=>'CAssetManager',
  1691. ),
  1692. 'user'=>array(
  1693. 'class'=>'CWebUser',
  1694. ),
  1695. 'themeManager'=>array(
  1696. 'class'=>'CThemeManager',
  1697. ),
  1698. 'authManager'=>array(
  1699. 'class'=>'CPhpAuthManager',
  1700. ),
  1701. 'clientScript'=>array(
  1702. 'class'=>'CClientScript',
  1703. ),
  1704. 'widgetFactory'=>array(
  1705. 'class'=>'CWidgetFactory',
  1706. ),
  1707. );
  1708. $this->setComponents($components);
  1709. }
  1710. public function getAuthManager()
  1711. {
  1712. return $this->getComponent('authManager');
  1713. }
  1714. public function getAssetManager()
  1715. {
  1716. return $this->getComponent('assetManager');
  1717. }
  1718. public function getSession()
  1719. {
  1720. return $this->getComponent('session');
  1721. }
  1722. public function getUser()
  1723. {
  1724. return $this->getComponent('user');
  1725. }
  1726. public function getViewRenderer()
  1727. {
  1728. return $this->getComponent('viewRenderer');
  1729. }
  1730. public function getClientScript()
  1731. {
  1732. return $this->getComponent('clientScript');
  1733. }
  1734. public function getWidgetFactory()
  1735. {
  1736. return $this->getComponent('widgetFactory');
  1737. }
  1738. public function getThemeManager()
  1739. {
  1740. return $this->getComponent('themeManager');
  1741. }
  1742. public function getTheme()
  1743. {
  1744. if(is_string($this->_theme))
  1745. $this->_theme=$this->getThemeManager()->getTheme($this->_theme);
  1746. return $this->_theme;
  1747. }
  1748. public function setTheme($value)
  1749. {
  1750. $this->_theme=$value;
  1751. }
  1752. public function runController($route)
  1753. {
  1754. if(($ca=$this->createController($route))!==null)
  1755. {
  1756. list($controller,$actionID)=$ca;
  1757. $oldController=$this->_controller;
  1758. $this->_controller=$controller;
  1759. $controller->init();
  1760. $controller->run($actionID);
  1761. $this->_controller=$oldController;
  1762. }
  1763. else
  1764. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  1765. array('{route}'=>$route===''?$this->defaultController:$route)));
  1766. }
  1767. public function createController($route,$owner=null)
  1768. {
  1769. if($owner===null)
  1770. $owner=$this;
  1771. if(($route=trim($route,'/'))==='')
  1772. $route=$owner->defaultController;
  1773. $caseSensitive=$this->getUrlManager()->caseSensitive;
  1774. $route.='/';
  1775. while(($pos=strpos($route,'/'))!==false)
  1776. {
  1777. $id=substr($route,0,$pos);
  1778. if(!preg_match('/^\w+$/',$id))
  1779. return null;
  1780. if(!$caseSensitive)
  1781. $id=strtolower($id);
  1782. $route=(string)substr($route,$pos+1);
  1783. if(!isset($basePath)) // first segment
  1784. {
  1785. if(isset($owner->controllerMap[$id]))
  1786. {
  1787. return array(
  1788. Yii::createComponent($owner->controllerMap[$id],$id,$owner===$this?null:$owner),
  1789. $this->parseActionParams($route),
  1790. );
  1791. }
  1792. if(($module=$owner->getModule($id))!==null)
  1793. return $this->createController($route,$module);
  1794. $basePath=$owner->getControllerPath();
  1795. $controllerID='';
  1796. }
  1797. else
  1798. $controllerID.='/';
  1799. $className=ucfirst($id).'Controller';
  1800. $classFile=$basePath.DIRECTORY_SEPARATOR.$className.'.php';
  1801. if($owner->controllerNamespace!==null)
  1802. $className=$owner->controllerNamespace.'\\'.str_replace('/','\\',$controllerID).$className;
  1803. if(is_file($classFile))
  1804. {
  1805. if(!class_exists($className,false))
  1806. require($classFile);
  1807. if(class_exists($className,false) && is_subclass_of($className,'CController'))
  1808. {
  1809. $id[0]=strtolower($id[0]);
  1810. return array(
  1811. new $className($controllerID.$id,$owner===$this?null:$owner),
  1812. $this->parseActionParams($route),
  1813. );
  1814. }
  1815. return null;
  1816. }
  1817. $controllerID.=$id;
  1818. $basePath.=DIRECTORY_SEPARATOR.$id;
  1819. }
  1820. }
  1821. protected function parseActionParams($pathInfo)
  1822. {
  1823. if(($pos=strpos($pathInfo,'/'))!==false)
  1824. {
  1825. $manager=$this->getUrlManager();
  1826. $manager->parsePathInfo((string)substr($pathInfo,$pos+1));
  1827. $actionID=substr($pathInfo,0,$pos);
  1828. return $manager->caseSensitive ? $actionID : strtolower($actionID);
  1829. }
  1830. else
  1831. return $pathInfo;
  1832. }
  1833. public function getController()
  1834. {
  1835. return $this->_controller;
  1836. }
  1837. public function setController($value)
  1838. {
  1839. $this->_controller=$value;
  1840. }
  1841. public function getControllerPath()
  1842. {
  1843. if($this->_controllerPath!==null)
  1844. return $this->_controllerPath;
  1845. else
  1846. return $this->_controllerPath=$this->getBasePath().DIRECTORY_SEPARATOR.'controllers';
  1847. }
  1848. public function setControllerPath($value)
  1849. {
  1850. if(($this->_controllerPath=realpath($value))===false || !is_dir($this->_controllerPath))
  1851. throw new CException(Yii::t('yii','The controller path "{path}" is not a valid directory.',
  1852. array('{path}'=>$value)));
  1853. }
  1854. public function getViewPath()
  1855. {
  1856. if($this->_viewPath!==null)
  1857. return $this->_viewPath;
  1858. else
  1859. return $this->_viewPath=$this->getBasePath().DIRECTORY_SEPARATOR.'views';
  1860. }
  1861. public function setViewPath($path)
  1862. {
  1863. if(($this->_viewPath=realpath($path))===false || !is_dir($this->_viewPath))
  1864. throw new CException(Yii::t('yii','The view path "{path}" is not a valid directory.',
  1865. array('{path}'=>$path)));
  1866. }
  1867. public function getSystemViewPath()
  1868. {
  1869. if($this->_systemViewPath!==null)
  1870. return $this->_systemViewPath;
  1871. else
  1872. return $this->_systemViewPath=$this->getViewPath().DIRECTORY_SEPARATOR.'system';
  1873. }
  1874. public function setSystemViewPath($path)
  1875. {
  1876. if(($this->_systemViewPath=realpath($path))===false || !is_dir($this->_systemViewPath))
  1877. throw new CException(Yii::t('yii','The system view path "{path}" is not a valid directory.',
  1878. array('{path}'=>$path)));
  1879. }
  1880. public function getLayoutPath()
  1881. {
  1882. if($this->_layoutPath!==null)
  1883. return $this->_layoutPath;
  1884. else
  1885. return $this->_layoutPath=$this->getViewPath().DIRECTORY_SEPARATOR.'layouts';
  1886. }
  1887. public function setLayoutPath($path)
  1888. {
  1889. if(($this->_layoutPath=realpath($path))===false || !is_dir($this->_layoutPath))
  1890. throw new CException(Yii::t('yii','The layout path "{path}" is not a valid directory.',
  1891. array('{path}'=>$path)));
  1892. }
  1893. public function beforeControllerAction($controller,$action)
  1894. {
  1895. return true;
  1896. }
  1897. public function afterControllerAction($controller,$action)
  1898. {
  1899. }
  1900. public function findModule($id)
  1901. {
  1902. if(($controller=$this->getController())!==null && ($module=$controller->getModule())!==null)
  1903. {
  1904. do
  1905. {
  1906. if(($m=$module->getModule($id))!==null)
  1907. return $m;
  1908. } while(($module=$module->getParentModule())!==null);
  1909. }
  1910. if(($m=$this->getModule($id))!==null)
  1911. return $m;
  1912. }
  1913. protected function init()
  1914. {
  1915. parent::init();
  1916. // preload 'request' so that it has chance to respond to onBeginRequest event.
  1917. $this->getRequest();
  1918. }
  1919. }
  1920. class CMap extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  1921. {
  1922. private $_d=array();
  1923. private $_r=false;
  1924. public function __construct($data=null,$readOnly=false)
  1925. {
  1926. if($data!==null)
  1927. $this->copyFrom($data);
  1928. $this->setReadOnly($readOnly);
  1929. }
  1930. public function getReadOnly()
  1931. {
  1932. return $this->_r;
  1933. }
  1934. protected function setReadOnly($value)
  1935. {
  1936. $this->_r=$value;
  1937. }
  1938. public function getIterator()
  1939. {
  1940. return new CMapIterator($this->_d);
  1941. }
  1942. public function count()
  1943. {
  1944. return $this->getCount();
  1945. }
  1946. public function getCount()
  1947. {
  1948. return count($this->_d);
  1949. }
  1950. public function getKeys()
  1951. {
  1952. return array_keys($this->_d);
  1953. }
  1954. public function itemAt($key)
  1955. {
  1956. if(isset($this->_d[$key]))
  1957. return $this->_d[$key];
  1958. else
  1959. return null;
  1960. }
  1961. public function add($key,$value)
  1962. {
  1963. if(!$this->_r)
  1964. {
  1965. if($key===null)
  1966. $this->_d[]=$value;
  1967. else
  1968. $this->_d[$key]=$value;
  1969. }
  1970. else
  1971. throw new CException(Yii::t('yii','The map is read only.'));
  1972. }
  1973. public function remove($key)
  1974. {
  1975. if(!$this->_r)
  1976. {
  1977. if(isset($this->_d[$key]))
  1978. {
  1979. $value=$this->_d[$key];
  1980. unset($this->_d[$key]);
  1981. return $value;
  1982. }
  1983. else
  1984. {
  1985. // it is possible the value is null, which is not detected by isset
  1986. unset($this->_d[$key]);
  1987. return null;
  1988. }
  1989. }
  1990. else
  1991. throw new CException(Yii::t('yii','The map is read only.'));
  1992. }
  1993. public function clear()
  1994. {
  1995. foreach(array_keys($this->_d) as $key)
  1996. $this->remove($key);
  1997. }
  1998. public function contains($key)
  1999. {
  2000. return isset($this->_d[$key]) || array_key_exists($key,$this->_d);
  2001. }
  2002. public function toArray()
  2003. {
  2004. return $this->_d;
  2005. }
  2006. public function copyFrom($data)
  2007. {
  2008. if(is_array($data) || $data instanceof Traversable)
  2009. {
  2010. if($this->getCount()>0)
  2011. $this->clear();
  2012. if($data instanceof CMap)
  2013. $data=$data->_d;
  2014. foreach($data as $key=>$value)
  2015. $this->add($key,$value);
  2016. }
  2017. elseif($data!==null)
  2018. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2019. }
  2020. public function mergeWith($data,$recursive=true)
  2021. {
  2022. if(is_array($data) || $data instanceof Traversable)
  2023. {
  2024. if($data instanceof CMap)
  2025. $data=$data->_d;
  2026. if($recursive)
  2027. {
  2028. if($data instanceof Traversable)
  2029. {
  2030. $d=array();
  2031. foreach($data as $key=>$value)
  2032. $d[$key]=$value;
  2033. $this->_d=self::mergeArray($this->_d,$d);
  2034. }
  2035. else
  2036. $this->_d=self::mergeArray($this->_d,$data);
  2037. }
  2038. else
  2039. {
  2040. foreach($data as $key=>$value)
  2041. $this->add($key,$value);
  2042. }
  2043. }
  2044. elseif($data!==null)
  2045. throw new CException(Yii::t('yii','Map data must be an array or an object implementing Traversable.'));
  2046. }
  2047. public static function mergeArray($a,$b)
  2048. {
  2049. $args=func_get_args();
  2050. $res=array_shift($args);
  2051. while(!empty($args))
  2052. {
  2053. $next=array_shift($args);
  2054. foreach($next as $k => $v)
  2055. {
  2056. if(is_integer($k))
  2057. isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
  2058. elseif(is_array($v) && isset($res[$k]) && is_array($res[$k]))
  2059. $res[$k]=self::mergeArray($res[$k],$v);
  2060. else
  2061. $res[$k]=$v;
  2062. }
  2063. }
  2064. return $res;
  2065. }
  2066. public function offsetExists($offset)
  2067. {
  2068. return $this->contains($offset);
  2069. }
  2070. public function offsetGet($offset)
  2071. {
  2072. return $this->itemAt($offset);
  2073. }
  2074. public function offsetSet($offset,$item)
  2075. {
  2076. $this->add($offset,$item);
  2077. }
  2078. public function offsetUnset($offset)
  2079. {
  2080. $this->remove($offset);
  2081. }
  2082. }
  2083. class CLogger extends CComponent
  2084. {
  2085. const LEVEL_TRACE='trace';
  2086. const LEVEL_WARNING='warning';
  2087. const LEVEL_ERROR='error';
  2088. const LEVEL_INFO='info';
  2089. const LEVEL_PROFILE='profile';
  2090. public $autoFlush=10000;
  2091. public $autoDump=false;
  2092. private $_logs=array();
  2093. private $_logCount=0;
  2094. private $_levels;
  2095. private $_categories;
  2096. private $_except=array();
  2097. private $_timings;
  2098. private $_processing=false;
  2099. public function log($message,$level='info',$category='application')
  2100. {
  2101. $this->_logs[]=array($message,$level,$category,microtime(true));
  2102. $this->_logCount++;
  2103. if($this->autoFlush>0 && $this->_logCount>=$this->autoFlush && !$this->_processing)
  2104. {
  2105. $this->_processing=true;
  2106. $this->flush($this->autoDump);
  2107. $this->_processing=false;
  2108. }
  2109. }
  2110. public function getLogs($levels='',$categories=array(), $except=array())
  2111. {
  2112. $this->_levels=preg_split('/[\s,]+/',strtolower($levels),-1,PREG_SPLIT_NO_EMPTY);
  2113. if (is_string($categories))
  2114. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2115. else
  2116. $this->_categories=array_filter(array_map('strtolower',$categories));
  2117. if (is_string($except))
  2118. $this->_except=preg_split('/[\s,]+/',strtolower($except),-1,PREG_SPLIT_NO_EMPTY);
  2119. else
  2120. $this->_except=array_filter(array_map('strtolower',$except));
  2121. $ret=$this->_logs;
  2122. if(!empty($levels))
  2123. $ret=array_values(array_filter($ret,array($this,'filterByLevel')));
  2124. if(!empty($this->_categories) || !empty($this->_except))
  2125. $ret=array_values(array_filter($ret,array($this,'filterByCategory')));
  2126. return $ret;
  2127. }
  2128. private function filterByCategory($value)
  2129. {
  2130. return $this->filterAllCategories($value, 2);
  2131. }
  2132. private function filterTimingByCategory($value)
  2133. {
  2134. return $this->filterAllCategories($value, 1);
  2135. }
  2136. private function filterAllCategories($value, $index)
  2137. {
  2138. $cat=strtolower($value[$index]);
  2139. $ret=empty($this->_categories);
  2140. foreach($this->_categories as $category)
  2141. {
  2142. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2143. $ret=true;
  2144. }
  2145. if($ret)
  2146. {
  2147. foreach($this->_except as $category)
  2148. {
  2149. if($cat===$category || (($c=rtrim($category,'.*'))!==$category && strpos($cat,$c)===0))
  2150. $ret=false;
  2151. }
  2152. }
  2153. return $ret;
  2154. }
  2155. private function filterByLevel($value)
  2156. {
  2157. return in_array(strtolower($value[1]),$this->_levels);
  2158. }
  2159. public function getExecutionTime()
  2160. {
  2161. return microtime(true)-YII_BEGIN_TIME;
  2162. }
  2163. public function getMemoryUsage()
  2164. {
  2165. if(function_exists('memory_get_usage'))
  2166. return memory_get_usage();
  2167. else
  2168. {
  2169. $output=array();
  2170. if(strncmp(PHP_OS,'WIN',3)===0)
  2171. {
  2172. exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST',$output);
  2173. return isset($output[5])?preg_replace('/[\D]/','',$output[5])*1024 : 0;
  2174. }
  2175. else
  2176. {
  2177. $pid=getmypid();
  2178. exec("ps -eo%mem,rss,pid | grep $pid", $output);
  2179. $output=explode(" ",$output[0]);
  2180. return isset($output[1]) ? $output[1]*1024 : 0;
  2181. }
  2182. }
  2183. }
  2184. public function getProfilingResults($token=null,$categories=null,$refresh=false)
  2185. {
  2186. if($this->_timings===null || $refresh)
  2187. $this->calculateTimings();
  2188. if($token===null && $categories===null)
  2189. return $this->_timings;
  2190. $timings = $this->_timings;
  2191. if($categories!==null) {
  2192. $this->_categories=preg_split('/[\s,]+/',strtolower($categories),-1,PREG_SPLIT_NO_EMPTY);
  2193. $timings=array_filter($timings,array($this,'filterTimingByCategory'));
  2194. }
  2195. $results=array();
  2196. foreach($timings as $timing)
  2197. {
  2198. if($token===null || $timing[0]===$token)
  2199. $results[]=$timing[2];
  2200. }
  2201. return $results;
  2202. }
  2203. private function calculateTimings()
  2204. {
  2205. $this->_timings=array();
  2206. $stack=array();
  2207. foreach($this->_logs as $log)
  2208. {
  2209. if($log[1]!==CLogger::LEVEL_PROFILE)
  2210. continue;
  2211. list($message,$level,$category,$timestamp)=$log;
  2212. if(!strncasecmp($message,'begin:',6))
  2213. {
  2214. $log[0]=substr($message,6);
  2215. $stack[]=$log;
  2216. }
  2217. elseif(!strncasecmp($message,'end:',4))
  2218. {
  2219. $token=substr($message,4);
  2220. if(($last=array_pop($stack))!==null && $last[0]===$token)
  2221. {
  2222. $delta=$log[3]-$last[3];
  2223. $this->_timings[]=array($message,$category,$delta);
  2224. }
  2225. else
  2226. throw new CException(Yii::t('yii','CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
  2227. array('{token}'=>$token)));
  2228. }
  2229. }
  2230. $now=microtime(true);
  2231. while(($last=array_pop($stack))!==null)
  2232. {
  2233. $delta=$now-$last[3];
  2234. $this->_timings[]=array($last[0],$last[2],$delta);
  2235. }
  2236. }
  2237. public function flush($dumpLogs=false)
  2238. {
  2239. $this->onFlush(new CEvent($this, array('dumpLogs'=>$dumpLogs)));
  2240. $this->_logs=array();
  2241. $this->_logCount=0;
  2242. }
  2243. public function onFlush($event)
  2244. {
  2245. $this->raiseEvent('onFlush', $event);
  2246. }
  2247. }
  2248. abstract class CApplicationComponent extends CComponent implements IApplicationComponent
  2249. {
  2250. public $behaviors=array();
  2251. private $_initialized=false;
  2252. public function init()
  2253. {
  2254. $this->attachBehaviors($this->behaviors);
  2255. $this->_initialized=true;
  2256. }
  2257. public function getIsInitialized()
  2258. {
  2259. return $this->_initialized;
  2260. }
  2261. }
  2262. class CHttpRequest extends CApplicationComponent
  2263. {
  2264. public $enableCookieValidation=false;
  2265. public $enableCsrfValidation=false;
  2266. public $csrfTokenName='YII_CSRF_TOKEN';
  2267. public $csrfCookie;
  2268. private $_requestUri;
  2269. private $_pathInfo;
  2270. private $_scriptFile;
  2271. private $_scriptUrl;
  2272. private $_hostInfo;
  2273. private $_baseUrl;
  2274. private $_cookies;
  2275. private $_preferredAcceptTypes;
  2276. private $_preferredLanguages;
  2277. private $_csrfToken;
  2278. private $_restParams;
  2279. private $_httpVersion;
  2280. public function init()
  2281. {
  2282. parent::init();
  2283. $this->normalizeRequest();
  2284. }
  2285. protected function normalizeRequest()
  2286. {
  2287. // normalize request
  2288. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  2289. {
  2290. if(isset($_GET))
  2291. $_GET=$this->stripSlashes($_GET);
  2292. if(isset($_POST))
  2293. $_POST=$this->stripSlashes($_POST);
  2294. if(isset($_REQUEST))
  2295. $_REQUEST=$this->stripSlashes($_REQUEST);
  2296. if(isset($_COOKIE))
  2297. $_COOKIE=$this->stripSlashes($_COOKIE);
  2298. }
  2299. if($this->enableCsrfValidation)
  2300. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  2301. }
  2302. public function stripSlashes(&$data)
  2303. {
  2304. if(is_array($data))
  2305. {
  2306. if(count($data) == 0)
  2307. return $data;
  2308. $keys=array_map('stripslashes',array_keys($data));
  2309. $data=array_combine($keys,array_values($data));
  2310. return array_map(array($this,'stripSlashes'),$data);
  2311. }
  2312. else
  2313. return stripslashes($data);
  2314. }
  2315. public function getParam($name,$defaultValue=null)
  2316. {
  2317. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  2318. }
  2319. public function getQuery($name,$defaultValue=null)
  2320. {
  2321. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  2322. }
  2323. public function getPost($name,$defaultValue=null)
  2324. {
  2325. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  2326. }
  2327. public function getDelete($name,$defaultValue=null)
  2328. {
  2329. if($this->getIsDeleteViaPostRequest())
  2330. return $this->getPost($name, $defaultValue);
  2331. if($this->getIsDeleteRequest())
  2332. {
  2333. $restParams=$this->getRestParams();
  2334. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2335. }
  2336. else
  2337. return $defaultValue;
  2338. }
  2339. public function getPut($name,$defaultValue=null)
  2340. {
  2341. if($this->getIsPutViaPostRequest())
  2342. return $this->getPost($name, $defaultValue);
  2343. if($this->getIsPutRequest())
  2344. {
  2345. $restParams=$this->getRestParams();
  2346. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2347. }
  2348. else
  2349. return $defaultValue;
  2350. }
  2351. public function getPatch($name,$defaultValue=null)
  2352. {
  2353. if($this->getIsPatchViaPostRequest())
  2354. return $this->getPost($name, $defaultValue);
  2355. if($this->getIsPatchRequest())
  2356. {
  2357. $restParams=$this->getRestParams();
  2358. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  2359. }
  2360. else
  2361. return $defaultValue;
  2362. }
  2363. public function getRestParams()
  2364. {
  2365. if($this->_restParams===null)
  2366. {
  2367. $result=array();
  2368. if(function_exists('mb_parse_str'))
  2369. mb_parse_str($this->getRawBody(), $result);
  2370. else
  2371. parse_str($this->getRawBody(), $result);
  2372. $this->_restParams=$result;
  2373. }
  2374. return $this->_restParams;
  2375. }
  2376. public function getRawBody()
  2377. {
  2378. static $rawBody;
  2379. if($rawBody===null)
  2380. $rawBody=file_get_contents('php://input');
  2381. return $rawBody;
  2382. }
  2383. public function getUrl()
  2384. {
  2385. return $this->getRequestUri();
  2386. }
  2387. public function getHostInfo($schema='')
  2388. {
  2389. if($this->_hostInfo===null)
  2390. {
  2391. if($secure=$this->getIsSecureConnection())
  2392. $http='https';
  2393. else
  2394. $http='http';
  2395. if(isset($_SERVER['HTTP_HOST']))
  2396. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  2397. else
  2398. {
  2399. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  2400. $port=$secure ? $this->getSecurePort() : $this->getPort();
  2401. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  2402. $this->_hostInfo.=':'.$port;
  2403. }
  2404. }
  2405. if($schema!=='')
  2406. {
  2407. $secure=$this->getIsSecureConnection();
  2408. if($secure && $schema==='https' || !$secure && $schema==='http')
  2409. return $this->_hostInfo;
  2410. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  2411. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  2412. $port=':'.$port;
  2413. else
  2414. $port='';
  2415. $pos=strpos($this->_hostInfo,':');
  2416. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  2417. }
  2418. else
  2419. return $this->_hostInfo;
  2420. }
  2421. public function setHostInfo($value)
  2422. {
  2423. $this->_hostInfo=rtrim($value,'/');
  2424. }
  2425. public function getBaseUrl($absolute=false)
  2426. {
  2427. if($this->_baseUrl===null)
  2428. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  2429. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  2430. }
  2431. public function setBaseUrl($value)
  2432. {
  2433. $this->_baseUrl=$value;
  2434. }
  2435. public function getScriptUrl()
  2436. {
  2437. if($this->_scriptUrl===null)
  2438. {
  2439. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  2440. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  2441. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  2442. elseif(basename($_SERVER['PHP_SELF'])===$scriptName)
  2443. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  2444. elseif(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  2445. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  2446. elseif(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  2447. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  2448. elseif(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  2449. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  2450. else
  2451. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  2452. }
  2453. return $this->_scriptUrl;
  2454. }
  2455. public function setScriptUrl($value)
  2456. {
  2457. $this->_scriptUrl='/'.trim($value,'/');
  2458. }
  2459. public function getPathInfo()
  2460. {
  2461. if($this->_pathInfo===null)
  2462. {
  2463. $pathInfo=$this->getRequestUri();
  2464. if(($pos=strpos($pathInfo,'?'))!==false)
  2465. $pathInfo=substr($pathInfo,0,$pos);
  2466. $pathInfo=$this->decodePathInfo($pathInfo);
  2467. $scriptUrl=$this->getScriptUrl();
  2468. $baseUrl=$this->getBaseUrl();
  2469. if(strpos($pathInfo,$scriptUrl)===0)
  2470. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  2471. elseif($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  2472. $pathInfo=substr($pathInfo,strlen($baseUrl));
  2473. elseif(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  2474. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  2475. else
  2476. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  2477. if($pathInfo==='/')
  2478. $pathInfo='';
  2479. elseif($pathInfo[0]==='/')
  2480. $pathInfo=substr($pathInfo,1);
  2481. if(($posEnd=strlen($pathInfo)-1)>0 && $pathInfo[$posEnd]==='/')
  2482. $pathInfo=substr($pathInfo,0,$posEnd);
  2483. $this->_pathInfo=$pathInfo;
  2484. }
  2485. return $this->_pathInfo;
  2486. }
  2487. protected function decodePathInfo($pathInfo)
  2488. {
  2489. $pathInfo = urldecode($pathInfo);
  2490. // is it UTF-8?
  2491. // http://w3.org/International/questions/qa-forms-utf-8.html
  2492. if(preg_match('%^(?:
  2493. [\x09\x0A\x0D\x20-\x7E] # ASCII
  2494. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  2495. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  2496. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  2497. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  2498. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  2499. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  2500. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  2501. )*$%xs', $pathInfo))
  2502. {
  2503. return $pathInfo;
  2504. }
  2505. else
  2506. {
  2507. return utf8_encode($pathInfo);
  2508. }
  2509. }
  2510. public function getRequestUri()
  2511. {
  2512. if($this->_requestUri===null)
  2513. {
  2514. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  2515. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  2516. elseif(isset($_SERVER['REQUEST_URI']))
  2517. {
  2518. $this->_requestUri=$_SERVER['REQUEST_URI'];
  2519. if(!empty($_SERVER['HTTP_HOST']))
  2520. {
  2521. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  2522. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  2523. }
  2524. else
  2525. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  2526. }
  2527. elseif(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  2528. {
  2529. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  2530. if(!empty($_SERVER['QUERY_STRING']))
  2531. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  2532. }
  2533. else
  2534. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  2535. }
  2536. return $this->_requestUri;
  2537. }
  2538. public function getQueryString()
  2539. {
  2540. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  2541. }
  2542. public function getIsSecureConnection()
  2543. {
  2544. return isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'],'on')===0 || $_SERVER['HTTPS']==1)
  2545. || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'],'https')===0;
  2546. }
  2547. public function getRequestType()
  2548. {
  2549. if(isset($_POST['_method']))
  2550. return strtoupper($_POST['_method']);
  2551. elseif(isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']))
  2552. return strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
  2553. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  2554. }
  2555. public function getIsPostRequest()
  2556. {
  2557. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  2558. }
  2559. public function getIsDeleteRequest()
  2560. {
  2561. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE')) || $this->getIsDeleteViaPostRequest();
  2562. }
  2563. protected function getIsDeleteViaPostRequest()
  2564. {
  2565. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'DELETE');
  2566. }
  2567. public function getIsPutRequest()
  2568. {
  2569. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT')) || $this->getIsPutViaPostRequest();
  2570. }
  2571. protected function getIsPutViaPostRequest()
  2572. {
  2573. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PUT');
  2574. }
  2575. public function getIsPatchRequest()
  2576. {
  2577. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PATCH')) || $this->getIsPatchViaPostRequest();
  2578. }
  2579. protected function getIsPatchViaPostRequest()
  2580. {
  2581. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PATCH');
  2582. }
  2583. public function getIsAjaxRequest()
  2584. {
  2585. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  2586. }
  2587. public function getIsFlashRequest()
  2588. {
  2589. return isset($_SERVER['HTTP_USER_AGENT']) && (stripos($_SERVER['HTTP_USER_AGENT'],'Shockwave')!==false || stripos($_SERVER['HTTP_USER_AGENT'],'Flash')!==false);
  2590. }
  2591. public function getServerName()
  2592. {
  2593. return $_SERVER['SERVER_NAME'];
  2594. }
  2595. public function getServerPort()
  2596. {
  2597. return $_SERVER['SERVER_PORT'];
  2598. }
  2599. public function getUrlReferrer()
  2600. {
  2601. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  2602. }
  2603. public function getUserAgent()
  2604. {
  2605. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  2606. }
  2607. public function getUserHostAddress()
  2608. {
  2609. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  2610. }
  2611. public function getUserHost()
  2612. {
  2613. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  2614. }
  2615. public function getScriptFile()
  2616. {
  2617. if($this->_scriptFile!==null)
  2618. return $this->_scriptFile;
  2619. else
  2620. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  2621. }
  2622. public function getBrowser($userAgent=null)
  2623. {
  2624. return get_browser($userAgent,true);
  2625. }
  2626. public function getAcceptTypes()
  2627. {
  2628. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  2629. }
  2630. private $_port;
  2631. public function getPort()
  2632. {
  2633. if($this->_port===null)
  2634. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  2635. return $this->_port;
  2636. }
  2637. public function setPort($value)
  2638. {
  2639. $this->_port=(int)$value;
  2640. $this->_hostInfo=null;
  2641. }
  2642. private $_securePort;
  2643. public function getSecurePort()
  2644. {
  2645. if($this->_securePort===null)
  2646. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  2647. return $this->_securePort;
  2648. }
  2649. public function setSecurePort($value)
  2650. {
  2651. $this->_securePort=(int)$value;
  2652. $this->_hostInfo=null;
  2653. }
  2654. public function getCookies()
  2655. {
  2656. if($this->_cookies!==null)
  2657. return $this->_cookies;
  2658. else
  2659. return $this->_cookies=new CCookieCollection($this);
  2660. }
  2661. public function redirect($url,$terminate=true,$statusCode=302)
  2662. {
  2663. if(strpos($url,'/')===0 && strpos($url,'//')!==0)
  2664. $url=$this->getHostInfo().$url;
  2665. header('Location: '.$url, true, $statusCode);
  2666. if($terminate)
  2667. Yii::app()->end();
  2668. }
  2669. public static function parseAcceptHeader($header)
  2670. {
  2671. $matches=array();
  2672. $accepts=array();
  2673. // get individual entries with their type, subtype, basetype and params
  2674. preg_match_all('/(?:\G\s?,\s?|^)(\w+|\*)\/(\w+|\*)(?:\+(\w+))?|(?<!^)\G(?:\s?;\s?(\w+)=([\w\.]+))/',$header,$matches);
  2675. // the regexp should (in theory) always return an array of 6 arrays
  2676. if(count($matches)===6)
  2677. {
  2678. $i=0;
  2679. $itemLen=count($matches[1]);
  2680. while($i<$itemLen)
  2681. {
  2682. // fill out a content type
  2683. $accept=array(
  2684. 'type'=>$matches[1][$i],
  2685. 'subType'=>$matches[2][$i],
  2686. 'baseType'=>null,
  2687. 'params'=>array(),
  2688. );
  2689. // fill in the base type if it exists
  2690. if($matches[3][$i]!==null && $matches[3][$i]!=='')
  2691. $accept['baseType']=$matches[3][$i];
  2692. // continue looping while there is no new content type, to fill in all accompanying params
  2693. for($i++;$i<$itemLen;$i++)
  2694. {
  2695. // if the next content type is null, then the item is a param for the current content type
  2696. if($matches[1][$i]===null || $matches[1][$i]==='')
  2697. {
  2698. // if this is the quality param, convert it to a double
  2699. if($matches[4][$i]==='q')
  2700. {
  2701. // sanity check on q value
  2702. $q=(double)$matches[5][$i];
  2703. if($q>1)
  2704. $q=(double)1;
  2705. elseif($q<0)
  2706. $q=(double)0;
  2707. $accept['params'][$matches[4][$i]]=$q;
  2708. }
  2709. else
  2710. $accept['params'][$matches[4][$i]]=$matches[5][$i];
  2711. }
  2712. else
  2713. break;
  2714. }
  2715. // q defaults to 1 if not explicitly given
  2716. if(!isset($accept['params']['q']))
  2717. $accept['params']['q']=(double)1;
  2718. $accepts[] = $accept;
  2719. }
  2720. }
  2721. return $accepts;
  2722. }
  2723. public static function compareAcceptTypes($a,$b)
  2724. {
  2725. // check for equal quality first
  2726. if($a['params']['q']===$b['params']['q'])
  2727. if(!($a['type']==='*' xor $b['type']==='*'))
  2728. if (!($a['subType']==='*' xor $b['subType']==='*'))
  2729. // finally, higher number of parameters counts as greater precedence
  2730. if(count($a['params'])===count($b['params']))
  2731. return 0;
  2732. else
  2733. return count($a['params'])<count($b['params']) ? 1 : -1;
  2734. // more specific takes precedence - whichever one doesn't have a * subType
  2735. else
  2736. return $a['subType']==='*' ? 1 : -1;
  2737. // more specific takes precedence - whichever one doesn't have a * type
  2738. else
  2739. return $a['type']==='*' ? 1 : -1;
  2740. else
  2741. return ($a['params']['q']<$b['params']['q']) ? 1 : -1;
  2742. }
  2743. public function getPreferredAcceptTypes()
  2744. {
  2745. if($this->_preferredAcceptTypes===null)
  2746. {
  2747. $accepts=self::parseAcceptHeader($this->getAcceptTypes());
  2748. usort($accepts,array(get_class($this),'compareAcceptTypes'));
  2749. $this->_preferredAcceptTypes=$accepts;
  2750. }
  2751. return $this->_preferredAcceptTypes;
  2752. }
  2753. public function getPreferredAcceptType()
  2754. {
  2755. $preferredAcceptTypes=$this->getPreferredAcceptTypes();
  2756. return empty($preferredAcceptTypes) ? false : $preferredAcceptTypes[0];
  2757. }
  2758. public function getPreferredLanguages()
  2759. {
  2760. if($this->_preferredLanguages===null)
  2761. {
  2762. $sortedLanguages=array();
  2763. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $n=preg_match_all('/([\w\-_]+)(?:\s*;\s*q\s*=\s*(\d*\.?\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))
  2764. {
  2765. $languages=array();
  2766. for($i=0;$i<$n;++$i)
  2767. {
  2768. $q=$matches[2][$i];
  2769. if($q==='')
  2770. $q=1;
  2771. if($q)
  2772. $languages[]=array((float)$q,$matches[1][$i]);
  2773. }
  2774. usort($languages,create_function('$a,$b','if($a[0]==$b[0]) {return 0;} return ($a[0]<$b[0]) ? 1 : -1;'));
  2775. foreach($languages as $language)
  2776. $sortedLanguages[]=$language[1];
  2777. }
  2778. $this->_preferredLanguages=$sortedLanguages;
  2779. }
  2780. return $this->_preferredLanguages;
  2781. }
  2782. public function getPreferredLanguage($languages=array())
  2783. {
  2784. $preferredLanguages=$this->getPreferredLanguages();
  2785. if(empty($languages)) {
  2786. return !empty($preferredLanguages) ? CLocale::getCanonicalID($preferredLanguages[0]) : false;
  2787. }
  2788. foreach ($preferredLanguages as $preferredLanguage) {
  2789. $preferredLanguage=CLocale::getCanonicalID($preferredLanguage);
  2790. foreach ($languages as $language) {
  2791. $language=CLocale::getCanonicalID($language);
  2792. // en_us==en_us, en==en_us, en_us==en
  2793. if($language===$acceptedLanguage || strpos($acceptedLanguage,$language.'_')===0 || strpos($language,$acceptedLanguage.'_')===0) {
  2794. return $language;
  2795. }
  2796. }
  2797. }
  2798. return reset($languages);
  2799. }
  2800. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  2801. {
  2802. if($mimeType===null)
  2803. {
  2804. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  2805. $mimeType='text/plain';
  2806. }
  2807. $fileSize=(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content));
  2808. $contentStart=0;
  2809. $contentEnd=$fileSize-1;
  2810. $httpVersion=$this->getHttpVersion();
  2811. if(isset($_SERVER['HTTP_RANGE']))
  2812. {
  2813. header('Accept-Ranges: bytes');
  2814. //client sent us a multibyte range, can not hold this one for now
  2815. if(strpos($_SERVER['HTTP_RANGE'],',')!==false)
  2816. {
  2817. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2818. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2819. }
  2820. $range=str_replace('bytes=','',$_SERVER['HTTP_RANGE']);
  2821. //range requests starts from "-", so it means that data must be dumped the end point.
  2822. if($range[0]==='-')
  2823. $contentStart=$fileSize-substr($range,1);
  2824. else
  2825. {
  2826. $range=explode('-',$range);
  2827. $contentStart=$range[0];
  2828. // check if the last-byte-pos presents in header
  2829. if((isset($range[1]) && is_numeric($range[1])))
  2830. $contentEnd=$range[1];
  2831. }
  2832. /* Check the range and make sure it's treated according to the specs.
  2833. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  2834. */
  2835. // End bytes can not be larger than $end.
  2836. $contentEnd=($contentEnd > $fileSize) ? $fileSize-1 : $contentEnd;
  2837. // Validate the requested range and return an error if it's not correct.
  2838. $wrongContentStart=($contentStart>$contentEnd || $contentStart>$fileSize-1 || $contentStart<0);
  2839. if($wrongContentStart)
  2840. {
  2841. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2842. throw new CHttpException(416,'Requested Range Not Satisfiable');
  2843. }
  2844. header("HTTP/$httpVersion 206 Partial Content");
  2845. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  2846. }
  2847. else
  2848. header("HTTP/$httpVersion 200 OK");
  2849. $length=$contentEnd-$contentStart+1; // Calculate new content length
  2850. header('Pragma: public');
  2851. header('Expires: 0');
  2852. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2853. header("Content-Type: $mimeType");
  2854. header('Content-Length: '.$length);
  2855. header("Content-Disposition: attachment; filename=\"$fileName\"");
  2856. header('Content-Transfer-Encoding: binary');
  2857. $content=function_exists('mb_substr') ? mb_substr($content,$contentStart,$length) : substr($content,$contentStart,$length);
  2858. if($terminate)
  2859. {
  2860. // clean up the application first because the file downloading could take long time
  2861. // which may cause timeout of some resources (such as DB connection)
  2862. ob_start();
  2863. Yii::app()->end(0,false);
  2864. ob_end_clean();
  2865. echo $content;
  2866. exit(0);
  2867. }
  2868. else
  2869. echo $content;
  2870. }
  2871. public function xSendFile($filePath, $options=array())
  2872. {
  2873. if(!isset($options['forceDownload']) || $options['forceDownload'])
  2874. $disposition='attachment';
  2875. else
  2876. $disposition='inline';
  2877. if(!isset($options['saveName']))
  2878. $options['saveName']=basename($filePath);
  2879. if(!isset($options['mimeType']))
  2880. {
  2881. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  2882. $options['mimeType']='text/plain';
  2883. }
  2884. if(!isset($options['xHeader']))
  2885. $options['xHeader']='X-Sendfile';
  2886. if($options['mimeType']!==null)
  2887. header('Content-Type: '.$options['mimeType']);
  2888. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  2889. if(isset($options['addHeaders']))
  2890. {
  2891. foreach($options['addHeaders'] as $header=>$value)
  2892. header($header.': '.$value);
  2893. }
  2894. header(trim($options['xHeader']).': '.$filePath);
  2895. if(!isset($options['terminate']) || $options['terminate'])
  2896. Yii::app()->end();
  2897. }
  2898. public function getCsrfToken()
  2899. {
  2900. if($this->_csrfToken===null)
  2901. {
  2902. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  2903. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  2904. {
  2905. $cookie=$this->createCsrfCookie();
  2906. $this->_csrfToken=$cookie->value;
  2907. $this->getCookies()->add($cookie->name,$cookie);
  2908. }
  2909. }
  2910. return $this->_csrfToken;
  2911. }
  2912. protected function createCsrfCookie()
  2913. {
  2914. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  2915. if(is_array($this->csrfCookie))
  2916. {
  2917. foreach($this->csrfCookie as $name=>$value)
  2918. $cookie->$name=$value;
  2919. }
  2920. return $cookie;
  2921. }
  2922. public function validateCsrfToken($event)
  2923. {
  2924. if ($this->getIsPostRequest() ||
  2925. $this->getIsPutRequest() ||
  2926. $this->getIsPatchRequest() ||
  2927. $this->getIsDeleteRequest())
  2928. {
  2929. $cookies=$this->getCookies();
  2930. $method=$this->getRequestType();
  2931. switch($method)
  2932. {
  2933. case 'POST':
  2934. $userToken=$this->getPost($this->csrfTokenName);
  2935. break;
  2936. case 'PUT':
  2937. $userToken=$this->getPut($this->csrfTokenName);
  2938. break;
  2939. case 'PATCH':
  2940. $userToken=$this->getPatch($this->csrfTokenName);
  2941. break;
  2942. case 'DELETE':
  2943. $userToken=$this->getDelete($this->csrfTokenName);
  2944. }
  2945. if (!empty($userToken) && $cookies->contains($this->csrfTokenName))
  2946. {
  2947. $cookieToken=$cookies->itemAt($this->csrfTokenName)->value;
  2948. $valid=$cookieToken===$userToken;
  2949. }
  2950. else
  2951. $valid = false;
  2952. if (!$valid)
  2953. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  2954. }
  2955. }
  2956. public function getHttpVersion()
  2957. {
  2958. if($this->_httpVersion===null)
  2959. {
  2960. if(isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL']==='HTTP/1.0')
  2961. $this->_httpVersion='1.0';
  2962. else
  2963. $this->_httpVersion='1.1';
  2964. }
  2965. return $this->_httpVersion;
  2966. }
  2967. }
  2968. class CCookieCollection extends CMap
  2969. {
  2970. private $_request;
  2971. private $_initialized=false;
  2972. public function __construct(CHttpRequest $request)
  2973. {
  2974. $this->_request=$request;
  2975. $this->copyfrom($this->getCookies());
  2976. $this->_initialized=true;
  2977. }
  2978. public function getRequest()
  2979. {
  2980. return $this->_request;
  2981. }
  2982. protected function getCookies()
  2983. {
  2984. $cookies=array();
  2985. if($this->_request->enableCookieValidation)
  2986. {
  2987. $sm=Yii::app()->getSecurityManager();
  2988. foreach($_COOKIE as $name=>$value)
  2989. {
  2990. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  2991. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  2992. }
  2993. }
  2994. else
  2995. {
  2996. foreach($_COOKIE as $name=>$value)
  2997. $cookies[$name]=new CHttpCookie($name,$value);
  2998. }
  2999. return $cookies;
  3000. }
  3001. public function add($name,$cookie)
  3002. {
  3003. if($cookie instanceof CHttpCookie)
  3004. {
  3005. $this->remove($name);
  3006. parent::add($name,$cookie);
  3007. if($this->_initialized)
  3008. $this->addCookie($cookie);
  3009. }
  3010. else
  3011. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  3012. }
  3013. public function remove($name,$options=array())
  3014. {
  3015. if(($cookie=parent::remove($name))!==null)
  3016. {
  3017. if($this->_initialized)
  3018. {
  3019. $cookie->configure($options);
  3020. $this->removeCookie($cookie);
  3021. }
  3022. }
  3023. return $cookie;
  3024. }
  3025. protected function addCookie($cookie)
  3026. {
  3027. $value=$cookie->value;
  3028. if($this->_request->enableCookieValidation)
  3029. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  3030. if(version_compare(PHP_VERSION,'5.2.0','>='))
  3031. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  3032. else
  3033. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  3034. }
  3035. protected function removeCookie($cookie)
  3036. {
  3037. if(version_compare(PHP_VERSION,'5.2.0','>='))
  3038. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  3039. else
  3040. setcookie($cookie->name,'',0,$cookie->path,$cookie->domain,$cookie->secure);
  3041. }
  3042. }
  3043. class CUrlManager extends CApplicationComponent
  3044. {
  3045. const CACHE_KEY='Yii.CUrlManager.rules';
  3046. const GET_FORMAT='get';
  3047. const PATH_FORMAT='path';
  3048. public $rules=array();
  3049. public $urlSuffix='';
  3050. public $showScriptName=true;
  3051. public $appendParams=true;
  3052. public $routeVar='r';
  3053. public $caseSensitive=true;
  3054. public $matchValue=false;
  3055. public $cacheID='cache';
  3056. public $useStrictParsing=false;
  3057. public $urlRuleClass='CUrlRule';
  3058. private $_urlFormat=self::GET_FORMAT;
  3059. private $_rules=array();
  3060. private $_baseUrl;
  3061. public function init()
  3062. {
  3063. parent::init();
  3064. $this->processRules();
  3065. }
  3066. protected function processRules()
  3067. {
  3068. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  3069. return;
  3070. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  3071. {
  3072. $hash=md5(serialize($this->rules));
  3073. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  3074. {
  3075. $this->_rules=$data[0];
  3076. return;
  3077. }
  3078. }
  3079. foreach($this->rules as $pattern=>$route)
  3080. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3081. if(isset($cache))
  3082. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  3083. }
  3084. public function addRules($rules,$append=true)
  3085. {
  3086. if ($append)
  3087. {
  3088. foreach($rules as $pattern=>$route)
  3089. $this->_rules[]=$this->createUrlRule($route,$pattern);
  3090. }
  3091. else
  3092. {
  3093. $rules=array_reverse($rules);
  3094. foreach($rules as $pattern=>$route)
  3095. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  3096. }
  3097. }
  3098. protected function createUrlRule($route,$pattern)
  3099. {
  3100. if(is_array($route) && isset($route['class']))
  3101. return $route;
  3102. else
  3103. {
  3104. $urlRuleClass=Yii::import($this->urlRuleClass,true);
  3105. return new $urlRuleClass($route,$pattern);
  3106. }
  3107. }
  3108. public function createUrl($route,$params=array(),$ampersand='&')
  3109. {
  3110. unset($params[$this->routeVar]);
  3111. foreach($params as $i=>$param)
  3112. if($param===null)
  3113. $params[$i]='';
  3114. if(isset($params['#']))
  3115. {
  3116. $anchor='#'.$params['#'];
  3117. unset($params['#']);
  3118. }
  3119. else
  3120. $anchor='';
  3121. $route=trim($route,'/');
  3122. foreach($this->_rules as $i=>$rule)
  3123. {
  3124. if(is_array($rule))
  3125. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3126. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  3127. {
  3128. if($rule->hasHostInfo)
  3129. return $url==='' ? '/'.$anchor : $url.$anchor;
  3130. else
  3131. return $this->getBaseUrl().'/'.$url.$anchor;
  3132. }
  3133. }
  3134. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  3135. }
  3136. protected function createUrlDefault($route,$params,$ampersand)
  3137. {
  3138. if($this->getUrlFormat()===self::PATH_FORMAT)
  3139. {
  3140. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  3141. if($this->appendParams)
  3142. {
  3143. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  3144. return $route==='' ? $url : $url.$this->urlSuffix;
  3145. }
  3146. else
  3147. {
  3148. if($route!=='')
  3149. $url.=$this->urlSuffix;
  3150. $query=$this->createPathInfo($params,'=',$ampersand);
  3151. return $query==='' ? $url : $url.'?'.$query;
  3152. }
  3153. }
  3154. else
  3155. {
  3156. $url=$this->getBaseUrl();
  3157. if(!$this->showScriptName)
  3158. $url.='/';
  3159. if($route!=='')
  3160. {
  3161. $url.='?'.$this->routeVar.'='.$route;
  3162. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3163. $url.=$ampersand.$query;
  3164. }
  3165. elseif(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  3166. $url.='?'.$query;
  3167. return $url;
  3168. }
  3169. }
  3170. public function parseUrl($request)
  3171. {
  3172. if($this->getUrlFormat()===self::PATH_FORMAT)
  3173. {
  3174. $rawPathInfo=$request->getPathInfo();
  3175. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3176. foreach($this->_rules as $i=>$rule)
  3177. {
  3178. if(is_array($rule))
  3179. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  3180. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  3181. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  3182. }
  3183. if($this->useStrictParsing)
  3184. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  3185. array('{route}'=>$pathInfo)));
  3186. else
  3187. return $pathInfo;
  3188. }
  3189. elseif(isset($_GET[$this->routeVar]))
  3190. return $_GET[$this->routeVar];
  3191. elseif(isset($_POST[$this->routeVar]))
  3192. return $_POST[$this->routeVar];
  3193. else
  3194. return '';
  3195. }
  3196. public function parsePathInfo($pathInfo)
  3197. {
  3198. if($pathInfo==='')
  3199. return;
  3200. $segs=explode('/',$pathInfo.'/');
  3201. $n=count($segs);
  3202. for($i=0;$i<$n-1;$i+=2)
  3203. {
  3204. $key=$segs[$i];
  3205. if($key==='') continue;
  3206. $value=$segs[$i+1];
  3207. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  3208. {
  3209. $name=substr($key,0,$pos);
  3210. for($j=$m-1;$j>=0;--$j)
  3211. {
  3212. if($matches[1][$j]==='')
  3213. $value=array($value);
  3214. else
  3215. $value=array($matches[1][$j]=>$value);
  3216. }
  3217. if(isset($_GET[$name]) && is_array($_GET[$name]))
  3218. $value=CMap::mergeArray($_GET[$name],$value);
  3219. $_REQUEST[$name]=$_GET[$name]=$value;
  3220. }
  3221. else
  3222. $_REQUEST[$key]=$_GET[$key]=$value;
  3223. }
  3224. }
  3225. public function createPathInfo($params,$equal,$ampersand, $key=null)
  3226. {
  3227. $pairs = array();
  3228. foreach($params as $k => $v)
  3229. {
  3230. if ($key!==null)
  3231. $k = $key.'['.$k.']';
  3232. if (is_array($v))
  3233. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  3234. else
  3235. $pairs[]=urlencode($k).$equal.urlencode($v);
  3236. }
  3237. return implode($ampersand,$pairs);
  3238. }
  3239. public function removeUrlSuffix($pathInfo,$urlSuffix)
  3240. {
  3241. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  3242. return substr($pathInfo,0,-strlen($urlSuffix));
  3243. else
  3244. return $pathInfo;
  3245. }
  3246. public function getBaseUrl()
  3247. {
  3248. if($this->_baseUrl!==null)
  3249. return $this->_baseUrl;
  3250. else
  3251. {
  3252. if($this->showScriptName)
  3253. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  3254. else
  3255. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  3256. return $this->_baseUrl;
  3257. }
  3258. }
  3259. public function setBaseUrl($value)
  3260. {
  3261. $this->_baseUrl=$value;
  3262. }
  3263. public function getUrlFormat()
  3264. {
  3265. return $this->_urlFormat;
  3266. }
  3267. public function setUrlFormat($value)
  3268. {
  3269. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  3270. $this->_urlFormat=$value;
  3271. else
  3272. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  3273. }
  3274. }
  3275. abstract class CBaseUrlRule extends CComponent
  3276. {
  3277. public $hasHostInfo=false;
  3278. abstract public function createUrl($manager,$route,$params,$ampersand);
  3279. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  3280. }
  3281. class CUrlRule extends CBaseUrlRule
  3282. {
  3283. public $urlSuffix;
  3284. public $caseSensitive;
  3285. public $defaultParams=array();
  3286. public $matchValue;
  3287. public $verb;
  3288. public $parsingOnly=false;
  3289. public $route;
  3290. public $references=array();
  3291. public $routePattern;
  3292. public $pattern;
  3293. public $template;
  3294. public $params=array();
  3295. public $append;
  3296. public $hasHostInfo;
  3297. public function __construct($route,$pattern)
  3298. {
  3299. if(is_array($route))
  3300. {
  3301. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  3302. {
  3303. if(isset($route[$name]))
  3304. $this->$name=$route[$name];
  3305. }
  3306. if(isset($route['pattern']))
  3307. $pattern=$route['pattern'];
  3308. $route=$route[0];
  3309. }
  3310. $this->route=trim($route,'/');
  3311. $tr2['/']=$tr['/']='\\/';
  3312. $tr['.']='\\.';
  3313. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  3314. {
  3315. foreach($matches2[1] as $name)
  3316. $this->references[$name]="<$name>";
  3317. }
  3318. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  3319. if($this->verb!==null)
  3320. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  3321. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  3322. {
  3323. $tokens=array_combine($matches[1],$matches[2]);
  3324. foreach($tokens as $name=>$value)
  3325. {
  3326. if($value==='')
  3327. $value='[^\/]+';
  3328. $tr["<$name>"]="(?P<$name>$value)";
  3329. if(isset($this->references[$name]))
  3330. $tr2["<$name>"]=$tr["<$name>"];
  3331. else
  3332. $this->params[$name]=$value;
  3333. }
  3334. }
  3335. $p=rtrim($pattern,'*');
  3336. $this->append=$p!==$pattern;
  3337. $p=trim($p,'/');
  3338. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  3339. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  3340. if($this->append)
  3341. $this->pattern.='/u';
  3342. else
  3343. $this->pattern.='$/u';
  3344. if($this->references!==array())
  3345. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  3346. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  3347. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  3348. array('{route}'=>$route,'{pattern}'=>$pattern)));
  3349. }
  3350. public function createUrl($manager,$route,$params,$ampersand)
  3351. {
  3352. if($this->parsingOnly)
  3353. return false;
  3354. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3355. $case='';
  3356. else
  3357. $case='i';
  3358. $tr=array();
  3359. if($route!==$this->route)
  3360. {
  3361. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  3362. {
  3363. foreach($this->references as $key=>$name)
  3364. $tr[$name]=$matches[$key];
  3365. }
  3366. else
  3367. return false;
  3368. }
  3369. foreach($this->defaultParams as $key=>$value)
  3370. {
  3371. if(isset($params[$key]))
  3372. {
  3373. if($params[$key]==$value)
  3374. unset($params[$key]);
  3375. else
  3376. return false;
  3377. }
  3378. }
  3379. foreach($this->params as $key=>$value)
  3380. if(!isset($params[$key]))
  3381. return false;
  3382. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  3383. {
  3384. foreach($this->params as $key=>$value)
  3385. {
  3386. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  3387. return false;
  3388. }
  3389. }
  3390. foreach($this->params as $key=>$value)
  3391. {
  3392. $tr["<$key>"]=urlencode($params[$key]);
  3393. unset($params[$key]);
  3394. }
  3395. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3396. $url=strtr($this->template,$tr);
  3397. if($this->hasHostInfo)
  3398. {
  3399. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  3400. if(stripos($url,$hostInfo)===0)
  3401. $url=substr($url,strlen($hostInfo));
  3402. }
  3403. if(empty($params))
  3404. return $url!=='' ? $url.$suffix : $url;
  3405. if($this->append)
  3406. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  3407. else
  3408. {
  3409. if($url!=='')
  3410. $url.=$suffix;
  3411. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  3412. }
  3413. return $url;
  3414. }
  3415. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  3416. {
  3417. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  3418. return false;
  3419. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  3420. $case='';
  3421. else
  3422. $case='i';
  3423. if($this->urlSuffix!==null)
  3424. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  3425. // URL suffix required, but not found in the requested URL
  3426. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  3427. {
  3428. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  3429. if($urlSuffix!='' && $urlSuffix!=='/')
  3430. return false;
  3431. }
  3432. if($this->hasHostInfo)
  3433. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  3434. $pathInfo.='/';
  3435. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  3436. {
  3437. foreach($this->defaultParams as $name=>$value)
  3438. {
  3439. if(!isset($_GET[$name]))
  3440. $_REQUEST[$name]=$_GET[$name]=$value;
  3441. }
  3442. $tr=array();
  3443. foreach($matches as $key=>$value)
  3444. {
  3445. if(isset($this->references[$key]))
  3446. $tr[$this->references[$key]]=$value;
  3447. elseif(isset($this->params[$key]))
  3448. $_REQUEST[$key]=$_GET[$key]=$value;
  3449. }
  3450. if($pathInfo!==$matches[0]) // there're additional GET params
  3451. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  3452. if($this->routePattern!==null)
  3453. return strtr($this->route,$tr);
  3454. else
  3455. return $this->route;
  3456. }
  3457. else
  3458. return false;
  3459. }
  3460. }
  3461. abstract class CBaseController extends CComponent
  3462. {
  3463. private $_widgetStack=array();
  3464. abstract public function getViewFile($viewName);
  3465. public function renderFile($viewFile,$data=null,$return=false)
  3466. {
  3467. $widgetCount=count($this->_widgetStack);
  3468. if(($renderer=Yii::app()->getViewRenderer())!==null && $renderer->fileExtension==='.'.CFileHelper::getExtension($viewFile))
  3469. $content=$renderer->renderFile($this,$viewFile,$data,$return);
  3470. else
  3471. $content=$this->renderInternal($viewFile,$data,$return);
  3472. if(count($this->_widgetStack)===$widgetCount)
  3473. return $content;
  3474. else
  3475. {
  3476. $widget=end($this->_widgetStack);
  3477. throw new CException(Yii::t('yii','{controller} contains improperly nested widget tags in its view "{view}". A {widget} widget does not have an endWidget() call.',
  3478. array('{controller}'=>get_class($this), '{view}'=>$viewFile, '{widget}'=>get_class($widget))));
  3479. }
  3480. }
  3481. public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
  3482. {
  3483. // we use special variable names here to avoid conflict when extracting data
  3484. if(is_array($_data_))
  3485. extract($_data_,EXTR_PREFIX_SAME,'data');
  3486. else
  3487. $data=$_data_;
  3488. if($_return_)
  3489. {
  3490. ob_start();
  3491. ob_implicit_flush(false);
  3492. require($_viewFile_);
  3493. return ob_get_clean();
  3494. }
  3495. else
  3496. require($_viewFile_);
  3497. }
  3498. public function createWidget($className,$properties=array())
  3499. {
  3500. $widget=Yii::app()->getWidgetFactory()->createWidget($this,$className,$properties);
  3501. $widget->init();
  3502. return $widget;
  3503. }
  3504. public function widget($className,$properties=array(),$captureOutput=false)
  3505. {
  3506. if($captureOutput)
  3507. {
  3508. ob_start();
  3509. ob_implicit_flush(false);
  3510. try
  3511. {
  3512. $widget=$this->createWidget($className,$properties);
  3513. $widget->run();
  3514. }
  3515. catch(Exception $e)
  3516. {
  3517. ob_end_clean();
  3518. throw $e;
  3519. }
  3520. return ob_get_clean();
  3521. }
  3522. else
  3523. {
  3524. $widget=$this->createWidget($className,$properties);
  3525. $widget->run();
  3526. return $widget;
  3527. }
  3528. }
  3529. public function beginWidget($className,$properties=array())
  3530. {
  3531. $widget=$this->createWidget($className,$properties);
  3532. $this->_widgetStack[]=$widget;
  3533. return $widget;
  3534. }
  3535. public function endWidget($id='')
  3536. {
  3537. if(($widget=array_pop($this->_widgetStack))!==null)
  3538. {
  3539. $widget->run();
  3540. return $widget;
  3541. }
  3542. else
  3543. throw new CException(Yii::t('yii','{controller} has an extra endWidget({id}) call in its view.',
  3544. array('{controller}'=>get_class($this),'{id}'=>$id)));
  3545. }
  3546. public function beginClip($id,$properties=array())
  3547. {
  3548. $properties['id']=$id;
  3549. $this->beginWidget('CClipWidget',$properties);
  3550. }
  3551. public function endClip()
  3552. {
  3553. $this->endWidget('CClipWidget');
  3554. }
  3555. public function beginCache($id,$properties=array())
  3556. {
  3557. $properties['id']=$id;
  3558. $cache=$this->beginWidget('COutputCache',$properties);
  3559. if($cache->getIsContentCached())
  3560. {
  3561. $this->endCache();
  3562. return false;
  3563. }
  3564. else
  3565. return true;
  3566. }
  3567. public function endCache()
  3568. {
  3569. $this->endWidget('COutputCache');
  3570. }
  3571. public function beginContent($view=null,$data=array())
  3572. {
  3573. $this->beginWidget('CContentDecorator',array('view'=>$view, 'data'=>$data));
  3574. }
  3575. public function endContent()
  3576. {
  3577. $this->endWidget('CContentDecorator');
  3578. }
  3579. }
  3580. class CController extends CBaseController
  3581. {
  3582. const STATE_INPUT_NAME='YII_PAGE_STATE';
  3583. public $layout;
  3584. public $defaultAction='index';
  3585. private $_id;
  3586. private $_action;
  3587. private $_pageTitle;
  3588. private $_cachingStack;
  3589. private $_clips;
  3590. private $_dynamicOutput;
  3591. private $_pageStates;
  3592. private $_module;
  3593. public function __construct($id,$module=null)
  3594. {
  3595. $this->_id=$id;
  3596. $this->_module=$module;
  3597. $this->attachBehaviors($this->behaviors());
  3598. }
  3599. public function init()
  3600. {
  3601. }
  3602. public function filters()
  3603. {
  3604. return array();
  3605. }
  3606. public function actions()
  3607. {
  3608. return array();
  3609. }
  3610. public function behaviors()
  3611. {
  3612. return array();
  3613. }
  3614. public function accessRules()
  3615. {
  3616. return array();
  3617. }
  3618. public function run($actionID)
  3619. {
  3620. if(($action=$this->createAction($actionID))!==null)
  3621. {
  3622. if(($parent=$this->getModule())===null)
  3623. $parent=Yii::app();
  3624. if($parent->beforeControllerAction($this,$action))
  3625. {
  3626. $this->runActionWithFilters($action,$this->filters());
  3627. $parent->afterControllerAction($this,$action);
  3628. }
  3629. }
  3630. else
  3631. $this->missingAction($actionID);
  3632. }
  3633. public function runActionWithFilters($action,$filters)
  3634. {
  3635. if(empty($filters))
  3636. $this->runAction($action);
  3637. else
  3638. {
  3639. $priorAction=$this->_action;
  3640. $this->_action=$action;
  3641. CFilterChain::create($this,$action,$filters)->run();
  3642. $this->_action=$priorAction;
  3643. }
  3644. }
  3645. public function runAction($action)
  3646. {
  3647. $priorAction=$this->_action;
  3648. $this->_action=$action;
  3649. if($this->beforeAction($action))
  3650. {
  3651. if($action->runWithParams($this->getActionParams())===false)
  3652. $this->invalidActionParams($action);
  3653. else
  3654. $this->afterAction($action);
  3655. }
  3656. $this->_action=$priorAction;
  3657. }
  3658. public function getActionParams()
  3659. {
  3660. return $_GET;
  3661. }
  3662. public function invalidActionParams($action)
  3663. {
  3664. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  3665. }
  3666. public function processOutput($output)
  3667. {
  3668. Yii::app()->getClientScript()->render($output);
  3669. // if using page caching, we should delay dynamic output replacement
  3670. if($this->_dynamicOutput!==null && $this->isCachingStackEmpty())
  3671. {
  3672. $output=$this->processDynamicOutput($output);
  3673. $this->_dynamicOutput=null;
  3674. }
  3675. if($this->_pageStates===null)
  3676. $this->_pageStates=$this->loadPageStates();
  3677. if(!empty($this->_pageStates))
  3678. $this->savePageStates($this->_pageStates,$output);
  3679. return $output;
  3680. }
  3681. public function processDynamicOutput($output)
  3682. {
  3683. if($this->_dynamicOutput)
  3684. {
  3685. $output=preg_replace_callback('/<###dynamic-(\d+)###>/',array($this,'replaceDynamicOutput'),$output);
  3686. }
  3687. return $output;
  3688. }
  3689. protected function replaceDynamicOutput($matches)
  3690. {
  3691. $content=$matches[0];
  3692. if(isset($this->_dynamicOutput[$matches[1]]))
  3693. {
  3694. $content=$this->_dynamicOutput[$matches[1]];
  3695. $this->_dynamicOutput[$matches[1]]=null;
  3696. }
  3697. return $content;
  3698. }
  3699. public function createAction($actionID)
  3700. {
  3701. if($actionID==='')
  3702. $actionID=$this->defaultAction;
  3703. if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
  3704. return new CInlineAction($this,$actionID);
  3705. else
  3706. {
  3707. $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
  3708. if($action!==null && !method_exists($action,'run'))
  3709. throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
  3710. return $action;
  3711. }
  3712. }
  3713. protected function createActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
  3714. {
  3715. if(($pos=strpos($actionID,'.'))===false && isset($actionMap[$actionID]))
  3716. {
  3717. $baseConfig=is_array($actionMap[$actionID]) ? $actionMap[$actionID] : array('class'=>$actionMap[$actionID]);
  3718. return Yii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
  3719. }
  3720. elseif($pos===false)
  3721. return null;
  3722. // the action is defined in a provider
  3723. $prefix=substr($actionID,0,$pos+1);
  3724. if(!isset($actionMap[$prefix]))
  3725. return null;
  3726. $actionID=(string)substr($actionID,$pos+1);
  3727. $provider=$actionMap[$prefix];
  3728. if(is_string($provider))
  3729. $providerType=$provider;
  3730. elseif(is_array($provider) && isset($provider['class']))
  3731. {
  3732. $providerType=$provider['class'];
  3733. if(isset($provider[$actionID]))
  3734. {
  3735. if(is_string($provider[$actionID]))
  3736. $config=array_merge(array('class'=>$provider[$actionID]),$config);
  3737. else
  3738. $config=array_merge($provider[$actionID],$config);
  3739. }
  3740. }
  3741. else
  3742. throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
  3743. $class=Yii::import($providerType,true);
  3744. $map=call_user_func(array($class,'actions'));
  3745. return $this->createActionFromMap($map,$actionID,$requestActionID,$config);
  3746. }
  3747. public function missingAction($actionID)
  3748. {
  3749. throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
  3750. array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
  3751. }
  3752. public function getAction()
  3753. {
  3754. return $this->_action;
  3755. }
  3756. public function setAction($value)
  3757. {
  3758. $this->_action=$value;
  3759. }
  3760. public function getId()
  3761. {
  3762. return $this->_id;
  3763. }
  3764. public function getUniqueId()
  3765. {
  3766. return $this->_module ? $this->_module->getId().'/'.$this->_id : $this->_id;
  3767. }
  3768. public function getRoute()
  3769. {
  3770. if(($action=$this->getAction())!==null)
  3771. return $this->getUniqueId().'/'.$action->getId();
  3772. else
  3773. return $this->getUniqueId();
  3774. }
  3775. public function getModule()
  3776. {
  3777. return $this->_module;
  3778. }
  3779. public function getViewPath()
  3780. {
  3781. if(($module=$this->getModule())===null)
  3782. $module=Yii::app();
  3783. return $module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
  3784. }
  3785. public function getViewFile($viewName)
  3786. {
  3787. if(($theme=Yii::app()->getTheme())!==null && ($viewFile=$theme->getViewFile($this,$viewName))!==false)
  3788. return $viewFile;
  3789. $moduleViewPath=$basePath=Yii::app()->getViewPath();
  3790. if(($module=$this->getModule())!==null)
  3791. $moduleViewPath=$module->getViewPath();
  3792. return $this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
  3793. }
  3794. public function getLayoutFile($layoutName)
  3795. {
  3796. if($layoutName===false)
  3797. return false;
  3798. if(($theme=Yii::app()->getTheme())!==null && ($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
  3799. return $layoutFile;
  3800. if(empty($layoutName))
  3801. {
  3802. $module=$this->getModule();
  3803. while($module!==null)
  3804. {
  3805. if($module->layout===false)
  3806. return false;
  3807. if(!empty($module->layout))
  3808. break;
  3809. $module=$module->getParentModule();
  3810. }
  3811. if($module===null)
  3812. $module=Yii::app();
  3813. $layoutName=$module->layout;
  3814. }
  3815. elseif(($module=$this->getModule())===null)
  3816. $module=Yii::app();
  3817. return $this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
  3818. }
  3819. public function resolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
  3820. {
  3821. if(empty($viewName))
  3822. return false;
  3823. if($moduleViewPath===null)
  3824. $moduleViewPath=$basePath;
  3825. if(($renderer=Yii::app()->getViewRenderer())!==null)
  3826. $extension=$renderer->fileExtension;
  3827. else
  3828. $extension='.php';
  3829. if($viewName[0]==='/')
  3830. {
  3831. if(strncmp($viewName,'//',2)===0)
  3832. $viewFile=$basePath.$viewName;
  3833. else
  3834. $viewFile=$moduleViewPath.$viewName;
  3835. }
  3836. elseif(strpos($viewName,'.'))
  3837. $viewFile=Yii::getPathOfAlias($viewName);
  3838. else
  3839. $viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;
  3840. if(is_file($viewFile.$extension))
  3841. return Yii::app()->findLocalizedFile($viewFile.$extension);
  3842. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  3843. return Yii::app()->findLocalizedFile($viewFile.'.php');
  3844. else
  3845. return false;
  3846. }
  3847. public function getClips()
  3848. {
  3849. if($this->_clips!==null)
  3850. return $this->_clips;
  3851. else
  3852. return $this->_clips=new CMap;
  3853. }
  3854. public function forward($route,$exit=true)
  3855. {
  3856. if(strpos($route,'/')===false)
  3857. $this->run($route);
  3858. else
  3859. {
  3860. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3861. $route=$module->getId().'/'.$route;
  3862. Yii::app()->runController($route);
  3863. }
  3864. if($exit)
  3865. Yii::app()->end();
  3866. }
  3867. public function render($view,$data=null,$return=false)
  3868. {
  3869. if($this->beforeRender($view))
  3870. {
  3871. $output=$this->renderPartial($view,$data,true);
  3872. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3873. $output=$this->renderFile($layoutFile,array('content'=>$output),true);
  3874. $this->afterRender($view,$output);
  3875. $output=$this->processOutput($output);
  3876. if($return)
  3877. return $output;
  3878. else
  3879. echo $output;
  3880. }
  3881. }
  3882. protected function beforeRender($view)
  3883. {
  3884. return true;
  3885. }
  3886. protected function afterRender($view, &$output)
  3887. {
  3888. }
  3889. public function renderText($text,$return=false)
  3890. {
  3891. if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
  3892. $text=$this->renderFile($layoutFile,array('content'=>$text),true);
  3893. $text=$this->processOutput($text);
  3894. if($return)
  3895. return $text;
  3896. else
  3897. echo $text;
  3898. }
  3899. public function renderPartial($view,$data=null,$return=false,$processOutput=false)
  3900. {
  3901. if(($viewFile=$this->getViewFile($view))!==false)
  3902. {
  3903. $output=$this->renderFile($viewFile,$data,true);
  3904. if($processOutput)
  3905. $output=$this->processOutput($output);
  3906. if($return)
  3907. return $output;
  3908. else
  3909. echo $output;
  3910. }
  3911. else
  3912. throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
  3913. array('{controller}'=>get_class($this), '{view}'=>$view)));
  3914. }
  3915. public function renderClip($name,$params=array(),$return=false)
  3916. {
  3917. $text=isset($this->clips[$name]) ? strtr($this->clips[$name], $params) : '';
  3918. if($return)
  3919. return $text;
  3920. else
  3921. echo $text;
  3922. }
  3923. public function renderDynamic($callback)
  3924. {
  3925. $n=count($this->_dynamicOutput);
  3926. echo "<###dynamic-$n###>";
  3927. $params=func_get_args();
  3928. array_shift($params);
  3929. $this->renderDynamicInternal($callback,$params);
  3930. }
  3931. public function renderDynamicInternal($callback,$params)
  3932. {
  3933. $this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
  3934. if(is_string($callback) && method_exists($this,$callback))
  3935. $callback=array($this,$callback);
  3936. $this->_dynamicOutput[]=call_user_func_array($callback,$params);
  3937. }
  3938. public function createUrl($route,$params=array(),$ampersand='&')
  3939. {
  3940. if($route==='')
  3941. $route=$this->getId().'/'.$this->getAction()->getId();
  3942. elseif(strpos($route,'/')===false)
  3943. $route=$this->getId().'/'.$route;
  3944. if($route[0]!=='/' && ($module=$this->getModule())!==null)
  3945. $route=$module->getId().'/'.$route;
  3946. return Yii::app()->createUrl(trim($route,'/'),$params,$ampersand);
  3947. }
  3948. public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
  3949. {
  3950. $url=$this->createUrl($route,$params,$ampersand);
  3951. if(strpos($url,'http')===0)
  3952. return $url;
  3953. else
  3954. return Yii::app()->getRequest()->getHostInfo($schema).$url;
  3955. }
  3956. public function getPageTitle()
  3957. {
  3958. if($this->_pageTitle!==null)
  3959. return $this->_pageTitle;
  3960. else
  3961. {
  3962. $name=ucfirst(basename($this->getId()));
  3963. if($this->getAction()!==null && strcasecmp($this->getAction()->getId(),$this->defaultAction))
  3964. return $this->_pageTitle=Yii::app()->name.' - '.ucfirst($this->getAction()->getId()).' '.$name;
  3965. else
  3966. return $this->_pageTitle=Yii::app()->name.' - '.$name;
  3967. }
  3968. }
  3969. public function setPageTitle($value)
  3970. {
  3971. $this->_pageTitle=$value;
  3972. }
  3973. public function redirect($url,$terminate=true,$statusCode=302)
  3974. {
  3975. if(is_array($url))
  3976. {
  3977. $route=isset($url[0]) ? $url[0] : '';
  3978. $url=$this->createUrl($route,array_splice($url,1));
  3979. }
  3980. Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
  3981. }
  3982. public function refresh($terminate=true,$anchor='')
  3983. {
  3984. $this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
  3985. }
  3986. public function recordCachingAction($context,$method,$params)
  3987. {
  3988. if($this->_cachingStack) // record only when there is an active output cache
  3989. {
  3990. foreach($this->_cachingStack as $cache)
  3991. $cache->recordAction($context,$method,$params);
  3992. }
  3993. }
  3994. public function getCachingStack($createIfNull=true)
  3995. {
  3996. if(!$this->_cachingStack)
  3997. $this->_cachingStack=new CStack;
  3998. return $this->_cachingStack;
  3999. }
  4000. public function isCachingStackEmpty()
  4001. {
  4002. return $this->_cachingStack===null || !$this->_cachingStack->getCount();
  4003. }
  4004. protected function beforeAction($action)
  4005. {
  4006. return true;
  4007. }
  4008. protected function afterAction($action)
  4009. {
  4010. }
  4011. public function filterPostOnly($filterChain)
  4012. {
  4013. if(Yii::app()->getRequest()->getIsPostRequest())
  4014. $filterChain->run();
  4015. else
  4016. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  4017. }
  4018. public function filterAjaxOnly($filterChain)
  4019. {
  4020. if(Yii::app()->getRequest()->getIsAjaxRequest())
  4021. $filterChain->run();
  4022. else
  4023. throw new CHttpException(400,Yii::t('yii','Your request is invalid.'));
  4024. }
  4025. public function filterAccessControl($filterChain)
  4026. {
  4027. $filter=new CAccessControlFilter;
  4028. $filter->setRules($this->accessRules());
  4029. $filter->filter($filterChain);
  4030. }
  4031. public function getPageState($name,$defaultValue=null)
  4032. {
  4033. if($this->_pageStates===null)
  4034. $this->_pageStates=$this->loadPageStates();
  4035. return isset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
  4036. }
  4037. public function setPageState($name,$value,$defaultValue=null)
  4038. {
  4039. if($this->_pageStates===null)
  4040. $this->_pageStates=$this->loadPageStates();
  4041. if($value===$defaultValue)
  4042. unset($this->_pageStates[$name]);
  4043. else
  4044. $this->_pageStates[$name]=$value;
  4045. $params=func_get_args();
  4046. $this->recordCachingAction('','setPageState',$params);
  4047. }
  4048. public function clearPageStates()
  4049. {
  4050. $this->_pageStates=array();
  4051. }
  4052. protected function loadPageStates()
  4053. {
  4054. if(!empty($_POST[self::STATE_INPUT_NAME]))
  4055. {
  4056. if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
  4057. {
  4058. if(extension_loaded('zlib'))
  4059. $data=@gzuncompress($data);
  4060. if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
  4061. return unserialize($data);
  4062. }
  4063. }
  4064. return array();
  4065. }
  4066. protected function savePageStates($states,&$output)
  4067. {
  4068. $data=Yii::app()->getSecurityManager()->hashData(serialize($states));
  4069. if(extension_loaded('zlib'))
  4070. $data=gzcompress($data);
  4071. $value=base64_encode($data);
  4072. $output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
  4073. }
  4074. }
  4075. abstract class CAction extends CComponent implements IAction
  4076. {
  4077. private $_id;
  4078. private $_controller;
  4079. public function __construct($controller,$id)
  4080. {
  4081. $this->_controller=$controller;
  4082. $this->_id=$id;
  4083. }
  4084. public function getController()
  4085. {
  4086. return $this->_controller;
  4087. }
  4088. public function getId()
  4089. {
  4090. return $this->_id;
  4091. }
  4092. public function runWithParams($params)
  4093. {
  4094. $method=new ReflectionMethod($this, 'run');
  4095. if($method->getNumberOfParameters()>0)
  4096. return $this->runWithParamsInternal($this, $method, $params);
  4097. $this->run();
  4098. return true;
  4099. }
  4100. protected function runWithParamsInternal($object, $method, $params)
  4101. {
  4102. $ps=array();
  4103. foreach($method->getParameters() as $i=>$param)
  4104. {
  4105. $name=$param->getName();
  4106. if(isset($params[$name]))
  4107. {
  4108. if($param->isArray())
  4109. $ps[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
  4110. elseif(!is_array($params[$name]))
  4111. $ps[]=$params[$name];
  4112. else
  4113. return false;
  4114. }
  4115. elseif($param->isDefaultValueAvailable())
  4116. $ps[]=$param->getDefaultValue();
  4117. else
  4118. return false;
  4119. }
  4120. $method->invokeArgs($object,$ps);
  4121. return true;
  4122. }
  4123. }
  4124. class CInlineAction extends CAction
  4125. {
  4126. public function run()
  4127. {
  4128. $method='action'.$this->getId();
  4129. $this->getController()->$method();
  4130. }
  4131. public function runWithParams($params)
  4132. {
  4133. $methodName='action'.$this->getId();
  4134. $controller=$this->getController();
  4135. $method=new ReflectionMethod($controller, $methodName);
  4136. if($method->getNumberOfParameters()>0)
  4137. return $this->runWithParamsInternal($controller, $method, $params);
  4138. $controller->$methodName();
  4139. return true;
  4140. }
  4141. }
  4142. class CWebUser extends CApplicationComponent implements IWebUser
  4143. {
  4144. const FLASH_KEY_PREFIX='Yii.CWebUser.flash.';
  4145. const FLASH_COUNTERS='Yii.CWebUser.flashcounters';
  4146. const STATES_VAR='__states';
  4147. const AUTH_TIMEOUT_VAR='__timeout';
  4148. const AUTH_ABSOLUTE_TIMEOUT_VAR='__absolute_timeout';
  4149. public $allowAutoLogin=false;
  4150. public $guestName='Guest';
  4151. public $loginUrl=array('/site/login');
  4152. public $identityCookie;
  4153. public $authTimeout;
  4154. public $absoluteAuthTimeout;
  4155. public $autoRenewCookie=false;
  4156. public $autoUpdateFlash=true;
  4157. public $loginRequiredAjaxResponse;
  4158. private $_keyPrefix;
  4159. private $_access=array();
  4160. public function __get($name)
  4161. {
  4162. if($this->hasState($name))
  4163. return $this->getState($name);
  4164. else
  4165. return parent::__get($name);
  4166. }
  4167. public function __set($name,$value)
  4168. {
  4169. if($this->hasState($name))
  4170. $this->setState($name,$value);
  4171. else
  4172. parent::__set($name,$value);
  4173. }
  4174. public function __isset($name)
  4175. {
  4176. if($this->hasState($name))
  4177. return $this->getState($name)!==null;
  4178. else
  4179. return parent::__isset($name);
  4180. }
  4181. public function __unset($name)
  4182. {
  4183. if($this->hasState($name))
  4184. $this->setState($name,null);
  4185. else
  4186. parent::__unset($name);
  4187. }
  4188. public function init()
  4189. {
  4190. parent::init();
  4191. Yii::app()->getSession()->open();
  4192. if($this->getIsGuest() && $this->allowAutoLogin)
  4193. $this->restoreFromCookie();
  4194. elseif($this->autoRenewCookie && $this->allowAutoLogin)
  4195. $this->renewCookie();
  4196. if($this->autoUpdateFlash)
  4197. $this->updateFlash();
  4198. $this->updateAuthStatus();
  4199. }
  4200. public function login($identity,$duration=0)
  4201. {
  4202. $id=$identity->getId();
  4203. $states=$identity->getPersistentStates();
  4204. if($this->beforeLogin($id,$states,false))
  4205. {
  4206. $this->changeIdentity($id,$identity->getName(),$states);
  4207. if($duration>0)
  4208. {
  4209. if($this->allowAutoLogin)
  4210. $this->saveToCookie($duration);
  4211. else
  4212. throw new CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
  4213. array('{class}'=>get_class($this))));
  4214. }
  4215. if ($this->absoluteAuthTimeout)
  4216. $this->setState(self::AUTH_ABSOLUTE_TIMEOUT_VAR, time()+$this->absoluteAuthTimeout);
  4217. $this->afterLogin(false);
  4218. }
  4219. return !$this->getIsGuest();
  4220. }
  4221. public function logout($destroySession=true)
  4222. {
  4223. if($this->beforeLogout())
  4224. {
  4225. if($this->allowAutoLogin)
  4226. {
  4227. Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
  4228. if($this->identityCookie!==null)
  4229. {
  4230. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4231. $cookie->value=null;
  4232. $cookie->expire=0;
  4233. Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
  4234. }
  4235. }
  4236. if($destroySession)
  4237. Yii::app()->getSession()->destroy();
  4238. else
  4239. $this->clearStates();
  4240. $this->_access=array();
  4241. $this->afterLogout();
  4242. }
  4243. }
  4244. public function getIsGuest()
  4245. {
  4246. return $this->getState('__id')===null;
  4247. }
  4248. public function getId()
  4249. {
  4250. return $this->getState('__id');
  4251. }
  4252. public function setId($value)
  4253. {
  4254. $this->setState('__id',$value);
  4255. }
  4256. public function getName()
  4257. {
  4258. if(($name=$this->getState('__name'))!==null)
  4259. return $name;
  4260. else
  4261. return $this->guestName;
  4262. }
  4263. public function setName($value)
  4264. {
  4265. $this->setState('__name',$value);
  4266. }
  4267. public function getReturnUrl($defaultUrl=null)
  4268. {
  4269. if($defaultUrl===null)
  4270. {
  4271. $defaultReturnUrl=Yii::app()->getUrlManager()->showScriptName ? Yii::app()->getRequest()->getScriptUrl() : Yii::app()->getRequest()->getBaseUrl().'/';
  4272. }
  4273. else
  4274. {
  4275. $defaultReturnUrl=CHtml::normalizeUrl($defaultUrl);
  4276. }
  4277. return $this->getState('__returnUrl',$defaultReturnUrl);
  4278. }
  4279. public function setReturnUrl($value)
  4280. {
  4281. $this->setState('__returnUrl',$value);
  4282. }
  4283. public function loginRequired()
  4284. {
  4285. $app=Yii::app();
  4286. $request=$app->getRequest();
  4287. if(!$request->getIsAjaxRequest())
  4288. {
  4289. $this->setReturnUrl($request->getUrl());
  4290. if(($url=$this->loginUrl)!==null)
  4291. {
  4292. if(is_array($url))
  4293. {
  4294. $route=isset($url[0]) ? $url[0] : $app->defaultController;
  4295. $url=$app->createUrl($route,array_splice($url,1));
  4296. }
  4297. $request->redirect($url);
  4298. }
  4299. }
  4300. elseif(isset($this->loginRequiredAjaxResponse))
  4301. {
  4302. echo $this->loginRequiredAjaxResponse;
  4303. Yii::app()->end();
  4304. }
  4305. throw new CHttpException(403,Yii::t('yii','Login Required'));
  4306. }
  4307. protected function beforeLogin($id,$states,$fromCookie)
  4308. {
  4309. return true;
  4310. }
  4311. protected function afterLogin($fromCookie)
  4312. {
  4313. }
  4314. protected function beforeLogout()
  4315. {
  4316. return true;
  4317. }
  4318. protected function afterLogout()
  4319. {
  4320. }
  4321. protected function restoreFromCookie()
  4322. {
  4323. $app=Yii::app();
  4324. $request=$app->getRequest();
  4325. $cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
  4326. if($cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
  4327. {
  4328. $data=@unserialize($data);
  4329. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4330. {
  4331. list($id,$name,$duration,$states)=$data;
  4332. if($this->beforeLogin($id,$states,true))
  4333. {
  4334. $this->changeIdentity($id,$name,$states);
  4335. if($this->autoRenewCookie)
  4336. {
  4337. $this->saveToCookie($duration);
  4338. }
  4339. $this->afterLogin(true);
  4340. }
  4341. }
  4342. }
  4343. }
  4344. protected function renewCookie()
  4345. {
  4346. $request=Yii::app()->getRequest();
  4347. $cookies=$request->getCookies();
  4348. $cookie=$cookies->itemAt($this->getStateKeyPrefix());
  4349. if($cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
  4350. {
  4351. $data=@unserialize($data);
  4352. if(is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
  4353. {
  4354. $this->saveToCookie($data[2]);
  4355. }
  4356. }
  4357. }
  4358. protected function saveToCookie($duration)
  4359. {
  4360. $app=Yii::app();
  4361. $cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
  4362. $cookie->expire=time()+$duration;
  4363. $data=array(
  4364. $this->getId(),
  4365. $this->getName(),
  4366. $duration,
  4367. $this->saveIdentityStates(),
  4368. );
  4369. $cookie->value=$app->getSecurityManager()->hashData(serialize($data));
  4370. $app->getRequest()->getCookies()->add($cookie->name,$cookie);
  4371. }
  4372. protected function createIdentityCookie($name)
  4373. {
  4374. $cookie=new CHttpCookie($name,'');
  4375. if(is_array($this->identityCookie))
  4376. {
  4377. foreach($this->identityCookie as $name=>$value)
  4378. $cookie->$name=$value;
  4379. }
  4380. return $cookie;
  4381. }
  4382. public function getStateKeyPrefix()
  4383. {
  4384. if($this->_keyPrefix!==null)
  4385. return $this->_keyPrefix;
  4386. else
  4387. return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
  4388. }
  4389. public function setStateKeyPrefix($value)
  4390. {
  4391. $this->_keyPrefix=$value;
  4392. }
  4393. public function getState($key,$defaultValue=null)
  4394. {
  4395. $key=$this->getStateKeyPrefix().$key;
  4396. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4397. }
  4398. public function setState($key,$value,$defaultValue=null)
  4399. {
  4400. $key=$this->getStateKeyPrefix().$key;
  4401. if($value===$defaultValue)
  4402. unset($_SESSION[$key]);
  4403. else
  4404. $_SESSION[$key]=$value;
  4405. }
  4406. public function hasState($key)
  4407. {
  4408. $key=$this->getStateKeyPrefix().$key;
  4409. return isset($_SESSION[$key]);
  4410. }
  4411. public function clearStates()
  4412. {
  4413. $keys=array_keys($_SESSION);
  4414. $prefix=$this->getStateKeyPrefix();
  4415. $n=strlen($prefix);
  4416. foreach($keys as $key)
  4417. {
  4418. if(!strncmp($key,$prefix,$n))
  4419. unset($_SESSION[$key]);
  4420. }
  4421. }
  4422. public function getFlashes($delete=true)
  4423. {
  4424. $flashes=array();
  4425. $prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
  4426. $keys=array_keys($_SESSION);
  4427. $n=strlen($prefix);
  4428. foreach($keys as $key)
  4429. {
  4430. if(!strncmp($key,$prefix,$n))
  4431. {
  4432. $flashes[substr($key,$n)]=$_SESSION[$key];
  4433. if($delete)
  4434. unset($_SESSION[$key]);
  4435. }
  4436. }
  4437. if($delete)
  4438. $this->setState(self::FLASH_COUNTERS,array());
  4439. return $flashes;
  4440. }
  4441. public function getFlash($key,$defaultValue=null,$delete=true)
  4442. {
  4443. $value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
  4444. if($delete)
  4445. $this->setFlash($key,null);
  4446. return $value;
  4447. }
  4448. public function setFlash($key,$value,$defaultValue=null)
  4449. {
  4450. $this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
  4451. $counters=$this->getState(self::FLASH_COUNTERS,array());
  4452. if($value===$defaultValue)
  4453. unset($counters[$key]);
  4454. else
  4455. $counters[$key]=0;
  4456. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4457. }
  4458. public function hasFlash($key)
  4459. {
  4460. return $this->getFlash($key, null, false)!==null;
  4461. }
  4462. protected function changeIdentity($id,$name,$states)
  4463. {
  4464. Yii::app()->getSession()->regenerateID(true);
  4465. $this->setId($id);
  4466. $this->setName($name);
  4467. $this->loadIdentityStates($states);
  4468. }
  4469. protected function saveIdentityStates()
  4470. {
  4471. $states=array();
  4472. foreach($this->getState(self::STATES_VAR,array()) as $name=>$dummy)
  4473. $states[$name]=$this->getState($name);
  4474. return $states;
  4475. }
  4476. protected function loadIdentityStates($states)
  4477. {
  4478. $names=array();
  4479. if(is_array($states))
  4480. {
  4481. foreach($states as $name=>$value)
  4482. {
  4483. $this->setState($name,$value);
  4484. $names[$name]=true;
  4485. }
  4486. }
  4487. $this->setState(self::STATES_VAR,$names);
  4488. }
  4489. protected function updateFlash()
  4490. {
  4491. $counters=$this->getState(self::FLASH_COUNTERS);
  4492. if(!is_array($counters))
  4493. return;
  4494. foreach($counters as $key=>$count)
  4495. {
  4496. if($count)
  4497. {
  4498. unset($counters[$key]);
  4499. $this->setState(self::FLASH_KEY_PREFIX.$key,null);
  4500. }
  4501. else
  4502. $counters[$key]++;
  4503. }
  4504. $this->setState(self::FLASH_COUNTERS,$counters,array());
  4505. }
  4506. protected function updateAuthStatus()
  4507. {
  4508. if(($this->authTimeout!==null || $this->absoluteAuthTimeout!==null) && !$this->getIsGuest())
  4509. {
  4510. $expires=$this->getState(self::AUTH_TIMEOUT_VAR);
  4511. $expiresAbsolute=$this->getState(self::AUTH_ABSOLUTE_TIMEOUT_VAR);
  4512. if ($expires!==null && $expires < time() || $expiresAbsolute!==null && $expiresAbsolute < time())
  4513. $this->logout(false);
  4514. else
  4515. $this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
  4516. }
  4517. }
  4518. public function checkAccess($operation,$params=array(),$allowCaching=true)
  4519. {
  4520. if($allowCaching && $params===array() && isset($this->_access[$operation]))
  4521. return $this->_access[$operation];
  4522. $access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
  4523. if($allowCaching && $params===array())
  4524. $this->_access[$operation]=$access;
  4525. return $access;
  4526. }
  4527. }
  4528. class CHttpSession extends CApplicationComponent implements IteratorAggregate,ArrayAccess,Countable
  4529. {
  4530. public $autoStart=true;
  4531. public function init()
  4532. {
  4533. parent::init();
  4534. if($this->autoStart)
  4535. $this->open();
  4536. register_shutdown_function(array($this,'close'));
  4537. }
  4538. public function getUseCustomStorage()
  4539. {
  4540. return false;
  4541. }
  4542. public function open()
  4543. {
  4544. if($this->getUseCustomStorage())
  4545. @session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));
  4546. @session_start();
  4547. if(YII_DEBUG && session_id()=='')
  4548. {
  4549. $message=Yii::t('yii','Failed to start session.');
  4550. if(function_exists('error_get_last'))
  4551. {
  4552. $error=error_get_last();
  4553. if(isset($error['message']))
  4554. $message=$error['message'];
  4555. }
  4556. Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
  4557. }
  4558. }
  4559. public function close()
  4560. {
  4561. if(session_id()!=='')
  4562. @session_write_close();
  4563. }
  4564. public function destroy()
  4565. {
  4566. if(session_id()!=='')
  4567. {
  4568. @session_unset();
  4569. @session_destroy();
  4570. }
  4571. }
  4572. public function getIsStarted()
  4573. {
  4574. return session_id()!=='';
  4575. }
  4576. public function getSessionID()
  4577. {
  4578. return session_id();
  4579. }
  4580. public function setSessionID($value)
  4581. {
  4582. session_id($value);
  4583. }
  4584. public function regenerateID($deleteOldSession=false)
  4585. {
  4586. if($this->getIsStarted())
  4587. session_regenerate_id($deleteOldSession);
  4588. }
  4589. public function getSessionName()
  4590. {
  4591. return session_name();
  4592. }
  4593. public function setSessionName($value)
  4594. {
  4595. session_name($value);
  4596. }
  4597. public function getSavePath()
  4598. {
  4599. return session_save_path();
  4600. }
  4601. public function setSavePath($value)
  4602. {
  4603. if(is_dir($value))
  4604. session_save_path($value);
  4605. else
  4606. throw new CException(Yii::t('yii','CHttpSession.savePath "{path}" is not a valid directory.',
  4607. array('{path}'=>$value)));
  4608. }
  4609. public function getCookieParams()
  4610. {
  4611. return session_get_cookie_params();
  4612. }
  4613. public function setCookieParams($value)
  4614. {
  4615. $data=session_get_cookie_params();
  4616. extract($data);
  4617. extract($value);
  4618. if(isset($httponly))
  4619. session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
  4620. else
  4621. session_set_cookie_params($lifetime,$path,$domain,$secure);
  4622. }
  4623. public function getCookieMode()
  4624. {
  4625. if(ini_get('session.use_cookies')==='0')
  4626. return 'none';
  4627. elseif(ini_get('session.use_only_cookies')==='0')
  4628. return 'allow';
  4629. else
  4630. return 'only';
  4631. }
  4632. public function setCookieMode($value)
  4633. {
  4634. if($value==='none')
  4635. {
  4636. ini_set('session.use_cookies','0');
  4637. ini_set('session.use_only_cookies','0');
  4638. }
  4639. elseif($value==='allow')
  4640. {
  4641. ini_set('session.use_cookies','1');
  4642. ini_set('session.use_only_cookies','0');
  4643. }
  4644. elseif($value==='only')
  4645. {
  4646. ini_set('session.use_cookies','1');
  4647. ini_set('session.use_only_cookies','1');
  4648. }
  4649. else
  4650. throw new CException(Yii::t('yii','CHttpSession.cookieMode can only be "none", "allow" or "only".'));
  4651. }
  4652. public function getGCProbability()
  4653. {
  4654. return (float)(ini_get('session.gc_probability')/ini_get('session.gc_divisor')*100);
  4655. }
  4656. public function setGCProbability($value)
  4657. {
  4658. if($value>=0 && $value<=100)
  4659. {
  4660. // percent * 21474837 / 2147483647 ≈ percent * 0.01
  4661. ini_set('session.gc_probability',floor($value*21474836.47));
  4662. ini_set('session.gc_divisor',2147483647);
  4663. }
  4664. else
  4665. throw new CException(Yii::t('yii','CHttpSession.gcProbability "{value}" is invalid. It must be a float between 0 and 100.',
  4666. array('{value}'=>$value)));
  4667. }
  4668. public function getUseTransparentSessionID()
  4669. {
  4670. return ini_get('session.use_trans_sid')==1;
  4671. }
  4672. public function setUseTransparentSessionID($value)
  4673. {
  4674. ini_set('session.use_trans_sid',$value?'1':'0');
  4675. }
  4676. public function getTimeout()
  4677. {
  4678. return (int)ini_get('session.gc_maxlifetime');
  4679. }
  4680. public function setTimeout($value)
  4681. {
  4682. ini_set('session.gc_maxlifetime',$value);
  4683. }
  4684. public function openSession($savePath,$sessionName)
  4685. {
  4686. return true;
  4687. }
  4688. public function closeSession()
  4689. {
  4690. return true;
  4691. }
  4692. public function readSession($id)
  4693. {
  4694. return '';
  4695. }
  4696. public function writeSession($id,$data)
  4697. {
  4698. return true;
  4699. }
  4700. public function destroySession($id)
  4701. {
  4702. return true;
  4703. }
  4704. public function gcSession($maxLifetime)
  4705. {
  4706. return true;
  4707. }
  4708. //------ The following methods enable CHttpSession to be CMap-like -----
  4709. public function getIterator()
  4710. {
  4711. return new CHttpSessionIterator;
  4712. }
  4713. public function getCount()
  4714. {
  4715. return count($_SESSION);
  4716. }
  4717. public function count()
  4718. {
  4719. return $this->getCount();
  4720. }
  4721. public function getKeys()
  4722. {
  4723. return array_keys($_SESSION);
  4724. }
  4725. public function get($key,$defaultValue=null)
  4726. {
  4727. return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
  4728. }
  4729. public function itemAt($key)
  4730. {
  4731. return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
  4732. }
  4733. public function add($key,$value)
  4734. {
  4735. $_SESSION[$key]=$value;
  4736. }
  4737. public function remove($key)
  4738. {
  4739. if(isset($_SESSION[$key]))
  4740. {
  4741. $value=$_SESSION[$key];
  4742. unset($_SESSION[$key]);
  4743. return $value;
  4744. }
  4745. else
  4746. return null;
  4747. }
  4748. public function clear()
  4749. {
  4750. foreach(array_keys($_SESSION) as $key)
  4751. unset($_SESSION[$key]);
  4752. }
  4753. public function contains($key)
  4754. {
  4755. return isset($_SESSION[$key]);
  4756. }
  4757. public function toArray()
  4758. {
  4759. return $_SESSION;
  4760. }
  4761. public function offsetExists($offset)
  4762. {
  4763. return isset($_SESSION[$offset]);
  4764. }
  4765. public function offsetGet($offset)
  4766. {
  4767. return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
  4768. }
  4769. public function offsetSet($offset,$item)
  4770. {
  4771. $_SESSION[$offset]=$item;
  4772. }
  4773. public function offsetUnset($offset)
  4774. {
  4775. unset($_SESSION[$offset]);
  4776. }
  4777. }
  4778. class CHtml
  4779. {
  4780. const ID_PREFIX='yt';
  4781. public static $errorSummaryCss='errorSummary';
  4782. public static $errorMessageCss='errorMessage';
  4783. public static $errorCss='error';
  4784. public static $errorContainerTag='div';
  4785. public static $requiredCss='required';
  4786. public static $beforeRequiredLabel='';
  4787. public static $afterRequiredLabel=' <span class="required">*</span>';
  4788. public static $count=0;
  4789. public static $liveEvents=true;
  4790. public static $closeSingleTags=true;
  4791. public static $renderSpecialAttributesValue=true;
  4792. private static $_modelNameConverter;
  4793. public static function encode($text)
  4794. {
  4795. return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);
  4796. }
  4797. public static function decode($text)
  4798. {
  4799. return htmlspecialchars_decode($text,ENT_QUOTES);
  4800. }
  4801. public static function encodeArray($data)
  4802. {
  4803. $d=array();
  4804. foreach($data as $key=>$value)
  4805. {
  4806. if(is_string($key))
  4807. $key=htmlspecialchars($key,ENT_QUOTES,Yii::app()->charset);
  4808. if(is_string($value))
  4809. $value=htmlspecialchars($value,ENT_QUOTES,Yii::app()->charset);
  4810. elseif(is_array($value))
  4811. $value=self::encodeArray($value);
  4812. $d[$key]=$value;
  4813. }
  4814. return $d;
  4815. }
  4816. public static function tag($tag,$htmlOptions=array(),$content=false,$closeTag=true)
  4817. {
  4818. $html='<' . $tag . self::renderAttributes($htmlOptions);
  4819. if($content===false)
  4820. return $closeTag && self::$closeSingleTags ? $html.' />' : $html.'>';
  4821. else
  4822. return $closeTag ? $html.'>'.$content.'</'.$tag.'>' : $html.'>'.$content;
  4823. }
  4824. public static function openTag($tag,$htmlOptions=array())
  4825. {
  4826. return '<' . $tag . self::renderAttributes($htmlOptions) . '>';
  4827. }
  4828. public static function closeTag($tag)
  4829. {
  4830. return '</'.$tag.'>';
  4831. }
  4832. public static function cdata($text)
  4833. {
  4834. return '<![CDATA[' . $text . ']]>';
  4835. }
  4836. public static function metaTag($content,$name=null,$httpEquiv=null,$options=array())
  4837. {
  4838. if($name!==null)
  4839. $options['name']=$name;
  4840. if($httpEquiv!==null)
  4841. $options['http-equiv']=$httpEquiv;
  4842. $options['content']=$content;
  4843. return self::tag('meta',$options);
  4844. }
  4845. public static function linkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  4846. {
  4847. if($relation!==null)
  4848. $options['rel']=$relation;
  4849. if($type!==null)
  4850. $options['type']=$type;
  4851. if($href!==null)
  4852. $options['href']=$href;
  4853. if($media!==null)
  4854. $options['media']=$media;
  4855. return self::tag('link',$options);
  4856. }
  4857. public static function css($text,$media='')
  4858. {
  4859. if($media!=='')
  4860. $media=' media="'.$media.'"';
  4861. return "<style type=\"text/css\"{$media}>\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n</style>";
  4862. }
  4863. public static function refresh($seconds,$url='')
  4864. {
  4865. $content="$seconds";
  4866. if($url!=='')
  4867. $content.=';url='.self::normalizeUrl($url);
  4868. Yii::app()->clientScript->registerMetaTag($content,null,'refresh');
  4869. }
  4870. public static function cssFile($url,$media='')
  4871. {
  4872. return CHtml::linkTag('stylesheet','text/css',$url,$media!=='' ? $media : null);
  4873. }
  4874. public static function script($text,array $htmlOptions=array())
  4875. {
  4876. $defaultHtmlOptions=array(
  4877. 'type'=>'text/javascript',
  4878. );
  4879. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  4880. return self::tag('script',$htmlOptions,"\n/*<![CDATA[*/\n{$text}\n/*]]>*/\n");
  4881. }
  4882. public static function scriptFile($url,array $htmlOptions=array())
  4883. {
  4884. $defaultHtmlOptions=array(
  4885. 'type'=>'text/javascript',
  4886. 'src'=>$url
  4887. );
  4888. $htmlOptions=array_merge($defaultHtmlOptions,$htmlOptions);
  4889. return self::tag('script',$htmlOptions,'');
  4890. }
  4891. public static function form($action='',$method='post',$htmlOptions=array())
  4892. {
  4893. return self::beginForm($action,$method,$htmlOptions);
  4894. }
  4895. public static function beginForm($action='',$method='post',$htmlOptions=array())
  4896. {
  4897. $htmlOptions['action']=$url=self::normalizeUrl($action);
  4898. if(strcasecmp($method,'get')!==0 && strcasecmp($method,'post')!==0)
  4899. {
  4900. $customMethod=$method;
  4901. $method='post';
  4902. }
  4903. else
  4904. $customMethod=false;
  4905. $htmlOptions['method']=$method;
  4906. $form=self::tag('form',$htmlOptions,false,false);
  4907. $hiddens=array();
  4908. if(!strcasecmp($method,'get') && ($pos=strpos($url,'?'))!==false)
  4909. {
  4910. foreach(explode('&',substr($url,$pos+1)) as $pair)
  4911. {
  4912. if(($pos=strpos($pair,'='))!==false)
  4913. $hiddens[]=self::hiddenField(urldecode(substr($pair,0,$pos)),urldecode(substr($pair,$pos+1)),array('id'=>false));
  4914. else
  4915. $hiddens[]=self::hiddenField(urldecode($pair),'',array('id'=>false));
  4916. }
  4917. }
  4918. $request=Yii::app()->request;
  4919. if($request->enableCsrfValidation && !strcasecmp($method,'post'))
  4920. $hiddens[]=self::hiddenField($request->csrfTokenName,$request->getCsrfToken(),array('id'=>false));
  4921. if($customMethod!==false)
  4922. $hiddens[]=self::hiddenField('_method',$customMethod);
  4923. if($hiddens!==array())
  4924. $form.="\n".implode("\n",$hiddens);
  4925. return $form;
  4926. }
  4927. public static function endForm()
  4928. {
  4929. return '</form>';
  4930. }
  4931. public static function statefulForm($action='',$method='post',$htmlOptions=array())
  4932. {
  4933. return self::form($action,$method,$htmlOptions)."\n".
  4934. self::tag('div',array('style'=>'display:none'),self::pageStateField(''));
  4935. }
  4936. public static function pageStateField($value)
  4937. {
  4938. return '<input type="hidden" name="'.CController::STATE_INPUT_NAME.'" value="'.$value.'" />';
  4939. }
  4940. public static function link($text,$url='#',$htmlOptions=array())
  4941. {
  4942. if($url!=='')
  4943. $htmlOptions['href']=self::normalizeUrl($url);
  4944. self::clientChange('click',$htmlOptions);
  4945. return self::tag('a',$htmlOptions,$text);
  4946. }
  4947. public static function mailto($text,$email='',$htmlOptions=array())
  4948. {
  4949. if($email==='')
  4950. $email=$text;
  4951. return self::link($text,'mailto:'.$email,$htmlOptions);
  4952. }
  4953. public static function image($src,$alt='',$htmlOptions=array())
  4954. {
  4955. $htmlOptions['src']=$src;
  4956. $htmlOptions['alt']=$alt;
  4957. return self::tag('img',$htmlOptions);
  4958. }
  4959. public static function button($label='button',$htmlOptions=array())
  4960. {
  4961. if(!isset($htmlOptions['name']))
  4962. {
  4963. if(!array_key_exists('name',$htmlOptions))
  4964. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4965. }
  4966. if(!isset($htmlOptions['type']))
  4967. $htmlOptions['type']='button';
  4968. if(!isset($htmlOptions['value']) && $htmlOptions['type']!='image')
  4969. $htmlOptions['value']=$label;
  4970. self::clientChange('click',$htmlOptions);
  4971. return self::tag('input',$htmlOptions);
  4972. }
  4973. public static function htmlButton($label='button',$htmlOptions=array())
  4974. {
  4975. if(!isset($htmlOptions['name']))
  4976. $htmlOptions['name']=self::ID_PREFIX.self::$count++;
  4977. if(!isset($htmlOptions['type']))
  4978. $htmlOptions['type']='button';
  4979. self::clientChange('click',$htmlOptions);
  4980. return self::tag('button',$htmlOptions,$label);
  4981. }
  4982. public static function submitButton($label='submit',$htmlOptions=array())
  4983. {
  4984. $htmlOptions['type']='submit';
  4985. return self::button($label,$htmlOptions);
  4986. }
  4987. public static function resetButton($label='reset',$htmlOptions=array())
  4988. {
  4989. $htmlOptions['type']='reset';
  4990. return self::button($label,$htmlOptions);
  4991. }
  4992. public static function imageButton($src,$htmlOptions=array())
  4993. {
  4994. $htmlOptions['src']=$src;
  4995. $htmlOptions['type']='image';
  4996. return self::button('submit',$htmlOptions);
  4997. }
  4998. public static function linkButton($label='submit',$htmlOptions=array())
  4999. {
  5000. if(!isset($htmlOptions['submit']))
  5001. $htmlOptions['submit']=isset($htmlOptions['href']) ? $htmlOptions['href'] : '';
  5002. return self::link($label,'#',$htmlOptions);
  5003. }
  5004. public static function label($label,$for,$htmlOptions=array())
  5005. {
  5006. if($for===false)
  5007. unset($htmlOptions['for']);
  5008. else
  5009. $htmlOptions['for']=$for;
  5010. if(isset($htmlOptions['required']))
  5011. {
  5012. if($htmlOptions['required'])
  5013. {
  5014. if(isset($htmlOptions['class']))
  5015. $htmlOptions['class'].=' '.self::$requiredCss;
  5016. else
  5017. $htmlOptions['class']=self::$requiredCss;
  5018. $label=self::$beforeRequiredLabel.$label.self::$afterRequiredLabel;
  5019. }
  5020. unset($htmlOptions['required']);
  5021. }
  5022. return self::tag('label',$htmlOptions,$label);
  5023. }
  5024. public static function colorField($name,$value='',$htmlOptions=array())
  5025. {
  5026. self::clientChange('change',$htmlOptions);
  5027. return self::inputField('color',$name,$value,$htmlOptions);
  5028. }
  5029. public static function textField($name,$value='',$htmlOptions=array())
  5030. {
  5031. self::clientChange('change',$htmlOptions);
  5032. return self::inputField('text',$name,$value,$htmlOptions);
  5033. }
  5034. public static function searchField($name,$value='',$htmlOptions=array())
  5035. {
  5036. self::clientChange('change',$htmlOptions);
  5037. return self::inputField('search',$name,$value,$htmlOptions);
  5038. }
  5039. public static function numberField($name,$value='',$htmlOptions=array())
  5040. {
  5041. self::clientChange('change',$htmlOptions);
  5042. return self::inputField('number',$name,$value,$htmlOptions);
  5043. }
  5044. public static function rangeField($name,$value='',$htmlOptions=array())
  5045. {
  5046. self::clientChange('change',$htmlOptions);
  5047. return self::inputField('range',$name,$value,$htmlOptions);
  5048. }
  5049. public static function dateField($name,$value='',$htmlOptions=array())
  5050. {
  5051. self::clientChange('change',$htmlOptions);
  5052. return self::inputField('date',$name,$value,$htmlOptions);
  5053. }
  5054. public static function timeField($name,$value='',$htmlOptions=array())
  5055. {
  5056. self::clientChange('change',$htmlOptions);
  5057. return self::inputField('time',$name,$value,$htmlOptions);
  5058. }
  5059. public static function dateTimeField($name,$value='',$htmlOptions=array())
  5060. {
  5061. self::clientChange('change',$htmlOptions);
  5062. return self::inputField('datetime',$name,$value,$htmlOptions);
  5063. }
  5064. public static function dateTimeLocalField($name,$value='',$htmlOptions=array())
  5065. {
  5066. self::clientChange('change',$htmlOptions);
  5067. return self::inputField('datetime-local',$name,$value,$htmlOptions);
  5068. }
  5069. public static function weekField($name,$value='',$htmlOptions=array())
  5070. {
  5071. self::clientChange('change',$htmlOptions);
  5072. return self::inputField('week',$name,$value,$htmlOptions);
  5073. }
  5074. public static function emailField($name,$value='',$htmlOptions=array())
  5075. {
  5076. self::clientChange('change',$htmlOptions);
  5077. return self::inputField('email',$name,$value,$htmlOptions);
  5078. }
  5079. public static function telField($name,$value='',$htmlOptions=array())
  5080. {
  5081. self::clientChange('change',$htmlOptions);
  5082. return self::inputField('tel',$name,$value,$htmlOptions);
  5083. }
  5084. public static function urlField($name,$value='',$htmlOptions=array())
  5085. {
  5086. self::clientChange('change',$htmlOptions);
  5087. return self::inputField('url',$name,$value,$htmlOptions);
  5088. }
  5089. public static function hiddenField($name,$value='',$htmlOptions=array())
  5090. {
  5091. return self::inputField('hidden',$name,$value,$htmlOptions);
  5092. }
  5093. public static function passwordField($name,$value='',$htmlOptions=array())
  5094. {
  5095. self::clientChange('change',$htmlOptions);
  5096. return self::inputField('password',$name,$value,$htmlOptions);
  5097. }
  5098. public static function fileField($name,$value='',$htmlOptions=array())
  5099. {
  5100. return self::inputField('file',$name,$value,$htmlOptions);
  5101. }
  5102. public static function textArea($name,$value='',$htmlOptions=array())
  5103. {
  5104. $htmlOptions['name']=$name;
  5105. if(!isset($htmlOptions['id']))
  5106. $htmlOptions['id']=self::getIdByName($name);
  5107. elseif($htmlOptions['id']===false)
  5108. unset($htmlOptions['id']);
  5109. self::clientChange('change',$htmlOptions);
  5110. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $value : self::encode($value));
  5111. }
  5112. public static function radioButton($name,$checked=false,$htmlOptions=array())
  5113. {
  5114. if($checked)
  5115. $htmlOptions['checked']='checked';
  5116. else
  5117. unset($htmlOptions['checked']);
  5118. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5119. self::clientChange('click',$htmlOptions);
  5120. if(array_key_exists('uncheckValue',$htmlOptions))
  5121. {
  5122. $uncheck=$htmlOptions['uncheckValue'];
  5123. unset($htmlOptions['uncheckValue']);
  5124. }
  5125. else
  5126. $uncheck=null;
  5127. if($uncheck!==null)
  5128. {
  5129. // add a hidden field so that if the radio button is not selected, it still submits a value
  5130. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5131. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5132. else
  5133. $uncheckOptions=array('id'=>false);
  5134. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5135. }
  5136. else
  5137. $hidden='';
  5138. // add a hidden field so that if the radio button is not selected, it still submits a value
  5139. return $hidden . self::inputField('radio',$name,$value,$htmlOptions);
  5140. }
  5141. public static function checkBox($name,$checked=false,$htmlOptions=array())
  5142. {
  5143. if($checked)
  5144. $htmlOptions['checked']='checked';
  5145. else
  5146. unset($htmlOptions['checked']);
  5147. $value=isset($htmlOptions['value']) ? $htmlOptions['value'] : 1;
  5148. self::clientChange('click',$htmlOptions);
  5149. if(array_key_exists('uncheckValue',$htmlOptions))
  5150. {
  5151. $uncheck=$htmlOptions['uncheckValue'];
  5152. unset($htmlOptions['uncheckValue']);
  5153. }
  5154. else
  5155. $uncheck=null;
  5156. if($uncheck!==null)
  5157. {
  5158. // add a hidden field so that if the check box is not checked, it still submits a value
  5159. if(isset($htmlOptions['id']) && $htmlOptions['id']!==false)
  5160. $uncheckOptions=array('id'=>self::ID_PREFIX.$htmlOptions['id']);
  5161. else
  5162. $uncheckOptions=array('id'=>false);
  5163. $hidden=self::hiddenField($name,$uncheck,$uncheckOptions);
  5164. }
  5165. else
  5166. $hidden='';
  5167. // add a hidden field so that if the check box is not checked, it still submits a value
  5168. return $hidden . self::inputField('checkbox',$name,$value,$htmlOptions);
  5169. }
  5170. public static function dropDownList($name,$select,$data,$htmlOptions=array())
  5171. {
  5172. $htmlOptions['name']=$name;
  5173. if(!isset($htmlOptions['id']))
  5174. $htmlOptions['id']=self::getIdByName($name);
  5175. elseif($htmlOptions['id']===false)
  5176. unset($htmlOptions['id']);
  5177. self::clientChange('change',$htmlOptions);
  5178. $options="\n".self::listOptions($select,$data,$htmlOptions);
  5179. $hidden='';
  5180. if(!empty($htmlOptions['multiple']))
  5181. {
  5182. if(substr($htmlOptions['name'],-2)!=='[]')
  5183. $htmlOptions['name'].='[]';
  5184. if(isset($htmlOptions['unselectValue']))
  5185. {
  5186. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5187. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5188. unset($htmlOptions['unselectValue']);
  5189. }
  5190. }
  5191. // add a hidden field so that if the option is not selected, it still submits a value
  5192. return $hidden . self::tag('select',$htmlOptions,$options);
  5193. }
  5194. public static function listBox($name,$select,$data,$htmlOptions=array())
  5195. {
  5196. if(!isset($htmlOptions['size']))
  5197. $htmlOptions['size']=4;
  5198. if(!empty($htmlOptions['multiple']))
  5199. {
  5200. if(substr($name,-2)!=='[]')
  5201. $name.='[]';
  5202. }
  5203. return self::dropDownList($name,$select,$data,$htmlOptions);
  5204. }
  5205. public static function checkBoxList($name,$select,$data,$htmlOptions=array())
  5206. {
  5207. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5208. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
  5209. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5210. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5211. if(substr($name,-2)!=='[]')
  5212. $name.='[]';
  5213. if(isset($htmlOptions['checkAll']))
  5214. {
  5215. $checkAllLabel=$htmlOptions['checkAll'];
  5216. $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
  5217. }
  5218. unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
  5219. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5220. unset($htmlOptions['labelOptions']);
  5221. $items=array();
  5222. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5223. unset($htmlOptions['baseID']);
  5224. $id=0;
  5225. $checkAll=true;
  5226. foreach($data as $value=>$labelTitle)
  5227. {
  5228. $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
  5229. $checkAll=$checkAll && $checked;
  5230. $htmlOptions['value']=$value;
  5231. $htmlOptions['id']=$baseID.'_'.$id++;
  5232. $option=self::checkBox($name,$checked,$htmlOptions);
  5233. $beginLabel=self::openTag('label',$labelOptions);
  5234. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5235. $endLabel=self::closeTag('label');
  5236. $items[]=strtr($template,array(
  5237. '{input}'=>$option,
  5238. '{beginLabel}'=>$beginLabel,
  5239. '{label}'=>$label,
  5240. '{labelTitle}'=>$labelTitle,
  5241. '{endLabel}'=>$endLabel,
  5242. ));
  5243. }
  5244. if(isset($checkAllLabel))
  5245. {
  5246. $htmlOptions['value']=1;
  5247. $htmlOptions['id']=$id=$baseID.'_all';
  5248. $option=self::checkBox($id,$checkAll,$htmlOptions);
  5249. $beginLabel=self::openTag('label',$labelOptions);
  5250. $label=self::label($checkAllLabel,$id,$labelOptions);
  5251. $endLabel=self::closeTag('label');
  5252. $item=strtr($template,array(
  5253. '{input}'=>$option,
  5254. '{beginLabel}'=>$beginLabel,
  5255. '{label}'=>$label,
  5256. '{labelTitle}'=>$checkAllLabel,
  5257. '{endLabel}'=>$endLabel,
  5258. ));
  5259. if($checkAllLast)
  5260. $items[]=$item;
  5261. else
  5262. array_unshift($items,$item);
  5263. $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
  5264. $js=<<<EOD
  5265. jQuery('#$id').click(function() {
  5266. jQuery("input[name='$name']").prop('checked', this.checked);
  5267. });
  5268. jQuery("input[name='$name']").click(function() {
  5269. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5270. });
  5271. jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
  5272. EOD;
  5273. $cs=Yii::app()->getClientScript();
  5274. $cs->registerCoreScript('jquery');
  5275. $cs->registerScript($id,$js);
  5276. }
  5277. if(empty($container))
  5278. return implode($separator,$items);
  5279. else
  5280. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5281. }
  5282. public static function radioButtonList($name,$select,$data,$htmlOptions=array())
  5283. {
  5284. $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
  5285. $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
  5286. $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
  5287. unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
  5288. $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
  5289. unset($htmlOptions['labelOptions']);
  5290. if(isset($htmlOptions['empty']))
  5291. {
  5292. if(!is_array($htmlOptions['empty']))
  5293. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5294. $data=CMap::mergeArray($htmlOptions['empty'],$data);
  5295. unset($htmlOptions['empty']);
  5296. }
  5297. $items=array();
  5298. $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
  5299. unset($htmlOptions['baseID']);
  5300. $id=0;
  5301. foreach($data as $value=>$labelTitle)
  5302. {
  5303. $checked=!strcmp($value,$select);
  5304. $htmlOptions['value']=$value;
  5305. $htmlOptions['id']=$baseID.'_'.$id++;
  5306. $option=self::radioButton($name,$checked,$htmlOptions);
  5307. $beginLabel=self::openTag('label',$labelOptions);
  5308. $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
  5309. $endLabel=self::closeTag('label');
  5310. $items[]=strtr($template,array(
  5311. '{input}'=>$option,
  5312. '{beginLabel}'=>$beginLabel,
  5313. '{label}'=>$label,
  5314. '{labelTitle}'=>$labelTitle,
  5315. '{endLabel}'=>$endLabel,
  5316. ));
  5317. }
  5318. if(empty($container))
  5319. return implode($separator,$items);
  5320. else
  5321. return self::tag($container,array('id'=>$baseID),implode($separator,$items));
  5322. }
  5323. public static function ajaxLink($text,$url,$ajaxOptions=array(),$htmlOptions=array())
  5324. {
  5325. if(!isset($htmlOptions['href']))
  5326. $htmlOptions['href']='#';
  5327. $ajaxOptions['url']=$url;
  5328. $htmlOptions['ajax']=$ajaxOptions;
  5329. self::clientChange('click',$htmlOptions);
  5330. return self::tag('a',$htmlOptions,$text);
  5331. }
  5332. public static function ajaxButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5333. {
  5334. $ajaxOptions['url']=$url;
  5335. $htmlOptions['ajax']=$ajaxOptions;
  5336. return self::button($label,$htmlOptions);
  5337. }
  5338. public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
  5339. {
  5340. $ajaxOptions['type']='POST';
  5341. $htmlOptions['type']='submit';
  5342. return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
  5343. }
  5344. public static function ajax($options)
  5345. {
  5346. Yii::app()->getClientScript()->registerCoreScript('jquery');
  5347. if(!isset($options['url']))
  5348. $options['url']=new CJavaScriptExpression('location.href');
  5349. else
  5350. $options['url']=self::normalizeUrl($options['url']);
  5351. if(!isset($options['cache']))
  5352. $options['cache']=false;
  5353. if(!isset($options['data']) && isset($options['type']))
  5354. $options['data']=new CJavaScriptExpression('jQuery(this).parents("form").serialize()');
  5355. foreach(array('beforeSend','complete','error','success') as $name)
  5356. {
  5357. if(isset($options[$name]) && !($options[$name] instanceof CJavaScriptExpression))
  5358. $options[$name]=new CJavaScriptExpression($options[$name]);
  5359. }
  5360. if(isset($options['update']))
  5361. {
  5362. if(!isset($options['success']))
  5363. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['update'].'").html(html)}');
  5364. unset($options['update']);
  5365. }
  5366. if(isset($options['replace']))
  5367. {
  5368. if(!isset($options['success']))
  5369. $options['success']=new CJavaScriptExpression('function(html){jQuery("'.$options['replace'].'").replaceWith(html)}');
  5370. unset($options['replace']);
  5371. }
  5372. return 'jQuery.ajax('.CJavaScript::encode($options).');';
  5373. }
  5374. public static function asset($path,$hashByName=false)
  5375. {
  5376. return Yii::app()->getAssetManager()->publish($path,$hashByName);
  5377. }
  5378. public static function normalizeUrl($url)
  5379. {
  5380. if(is_array($url))
  5381. {
  5382. if(isset($url[0]))
  5383. {
  5384. if(($c=Yii::app()->getController())!==null)
  5385. $url=$c->createUrl($url[0],array_splice($url,1));
  5386. else
  5387. $url=Yii::app()->createUrl($url[0],array_splice($url,1));
  5388. }
  5389. else
  5390. $url='';
  5391. }
  5392. return $url==='' ? Yii::app()->getRequest()->getUrl() : $url;
  5393. }
  5394. protected static function inputField($type,$name,$value,$htmlOptions)
  5395. {
  5396. $htmlOptions['type']=$type;
  5397. $htmlOptions['value']=$value;
  5398. $htmlOptions['name']=$name;
  5399. if(!isset($htmlOptions['id']))
  5400. $htmlOptions['id']=self::getIdByName($name);
  5401. elseif($htmlOptions['id']===false)
  5402. unset($htmlOptions['id']);
  5403. return self::tag('input',$htmlOptions);
  5404. }
  5405. public static function activeLabel($model,$attribute,$htmlOptions=array())
  5406. {
  5407. $inputName=self::resolveName($model,$attribute);
  5408. if(isset($htmlOptions['for']))
  5409. {
  5410. $for=$htmlOptions['for'];
  5411. unset($htmlOptions['for']);
  5412. }
  5413. else
  5414. $for=self::getIdByName($inputName);
  5415. if(isset($htmlOptions['label']))
  5416. {
  5417. if(($label=$htmlOptions['label'])===false)
  5418. return '';
  5419. unset($htmlOptions['label']);
  5420. }
  5421. else
  5422. $label=$model->getAttributeLabel($attribute);
  5423. if($model->hasErrors($attribute))
  5424. self::addErrorCss($htmlOptions);
  5425. return self::label($label,$for,$htmlOptions);
  5426. }
  5427. public static function activeLabelEx($model,$attribute,$htmlOptions=array())
  5428. {
  5429. $realAttribute=$attribute;
  5430. self::resolveName($model,$attribute); // strip off square brackets if any
  5431. $htmlOptions['required']=$model->isAttributeRequired($attribute);
  5432. return self::activeLabel($model,$realAttribute,$htmlOptions);
  5433. }
  5434. public static function activeTextField($model,$attribute,$htmlOptions=array())
  5435. {
  5436. self::resolveNameID($model,$attribute,$htmlOptions);
  5437. self::clientChange('change',$htmlOptions);
  5438. return self::activeInputField('text',$model,$attribute,$htmlOptions);
  5439. }
  5440. public static function activeSearchField($model,$attribute,$htmlOptions=array())
  5441. {
  5442. self::resolveNameID($model,$attribute,$htmlOptions);
  5443. self::clientChange('change',$htmlOptions);
  5444. return self::activeInputField('search',$model,$attribute,$htmlOptions);
  5445. }
  5446. public static function activeUrlField($model,$attribute,$htmlOptions=array())
  5447. {
  5448. self::resolveNameID($model,$attribute,$htmlOptions);
  5449. self::clientChange('change',$htmlOptions);
  5450. return self::activeInputField('url',$model,$attribute,$htmlOptions);
  5451. }
  5452. public static function activeEmailField($model,$attribute,$htmlOptions=array())
  5453. {
  5454. self::resolveNameID($model,$attribute,$htmlOptions);
  5455. self::clientChange('change',$htmlOptions);
  5456. return self::activeInputField('email',$model,$attribute,$htmlOptions);
  5457. }
  5458. public static function activeNumberField($model,$attribute,$htmlOptions=array())
  5459. {
  5460. self::resolveNameID($model,$attribute,$htmlOptions);
  5461. self::clientChange('change',$htmlOptions);
  5462. return self::activeInputField('number',$model,$attribute,$htmlOptions);
  5463. }
  5464. public static function activeRangeField($model,$attribute,$htmlOptions=array())
  5465. {
  5466. self::resolveNameID($model,$attribute,$htmlOptions);
  5467. self::clientChange('change',$htmlOptions);
  5468. return self::activeInputField('range',$model,$attribute,$htmlOptions);
  5469. }
  5470. public static function activeDateField($model,$attribute,$htmlOptions=array())
  5471. {
  5472. self::resolveNameID($model,$attribute,$htmlOptions);
  5473. self::clientChange('change',$htmlOptions);
  5474. return self::activeInputField('date',$model,$attribute,$htmlOptions);
  5475. }
  5476. public static function activeTimeField($model,$attribute,$htmlOptions=array())
  5477. {
  5478. self::resolveNameID($model,$attribute,$htmlOptions);
  5479. self::clientChange('change',$htmlOptions);
  5480. return self::activeInputField('time',$model,$attribute,$htmlOptions);
  5481. }
  5482. public static function activeDateTimeField($model,$attribute,$htmlOptions=array())
  5483. {
  5484. self::resolveNameID($model,$attribute,$htmlOptions);
  5485. self::clientChange('change',$htmlOptions);
  5486. return self::activeInputField('datetime',$model,$attribute,$htmlOptions);
  5487. }
  5488. public static function activeDateTimeLocalField($model,$attribute,$htmlOptions=array())
  5489. {
  5490. self::resolveNameID($model,$attribute,$htmlOptions);
  5491. self::clientChange('change',$htmlOptions);
  5492. return self::activeInputField('datetime-local',$model,$attribute,$htmlOptions);
  5493. }
  5494. public static function activeWeekField($model,$attribute,$htmlOptions=array())
  5495. {
  5496. self::resolveNameID($model,$attribute,$htmlOptions);
  5497. self::clientChange('change',$htmlOptions);
  5498. return self::activeInputField('week',$model,$attribute,$htmlOptions);
  5499. }
  5500. public static function activeColorField($model,$attribute,$htmlOptions=array())
  5501. {
  5502. self::resolveNameID($model,$attribute,$htmlOptions);
  5503. self::clientChange('change',$htmlOptions);
  5504. return self::activeInputField('color',$model,$attribute,$htmlOptions);
  5505. }
  5506. public static function activeTelField($model,$attribute,$htmlOptions=array())
  5507. {
  5508. self::resolveNameID($model,$attribute,$htmlOptions);
  5509. self::clientChange('change',$htmlOptions);
  5510. return self::activeInputField('tel',$model,$attribute,$htmlOptions);
  5511. }
  5512. public static function activeHiddenField($model,$attribute,$htmlOptions=array())
  5513. {
  5514. self::resolveNameID($model,$attribute,$htmlOptions);
  5515. return self::activeInputField('hidden',$model,$attribute,$htmlOptions);
  5516. }
  5517. public static function activePasswordField($model,$attribute,$htmlOptions=array())
  5518. {
  5519. self::resolveNameID($model,$attribute,$htmlOptions);
  5520. self::clientChange('change',$htmlOptions);
  5521. return self::activeInputField('password',$model,$attribute,$htmlOptions);
  5522. }
  5523. public static function activeTextArea($model,$attribute,$htmlOptions=array())
  5524. {
  5525. self::resolveNameID($model,$attribute,$htmlOptions);
  5526. self::clientChange('change',$htmlOptions);
  5527. if($model->hasErrors($attribute))
  5528. self::addErrorCss($htmlOptions);
  5529. if(isset($htmlOptions['value']))
  5530. {
  5531. $text=$htmlOptions['value'];
  5532. unset($htmlOptions['value']);
  5533. }
  5534. else
  5535. $text=self::resolveValue($model,$attribute);
  5536. return self::tag('textarea',$htmlOptions,isset($htmlOptions['encode']) && !$htmlOptions['encode'] ? $text : self::encode($text));
  5537. }
  5538. public static function activeFileField($model,$attribute,$htmlOptions=array())
  5539. {
  5540. self::resolveNameID($model,$attribute,$htmlOptions);
  5541. // add a hidden field so that if a model only has a file field, we can
  5542. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  5543. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5544. return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
  5545. . self::activeInputField('file',$model,$attribute,$htmlOptions);
  5546. }
  5547. public static function activeRadioButton($model,$attribute,$htmlOptions=array())
  5548. {
  5549. self::resolveNameID($model,$attribute,$htmlOptions);
  5550. if(!isset($htmlOptions['value']))
  5551. $htmlOptions['value']=1;
  5552. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5553. $htmlOptions['checked']='checked';
  5554. self::clientChange('click',$htmlOptions);
  5555. if(array_key_exists('uncheckValue',$htmlOptions))
  5556. {
  5557. $uncheck=$htmlOptions['uncheckValue'];
  5558. unset($htmlOptions['uncheckValue']);
  5559. }
  5560. else
  5561. $uncheck='0';
  5562. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5563. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5564. // add a hidden field so that if the radio button is not selected, it still submits a value
  5565. return $hidden . self::activeInputField('radio',$model,$attribute,$htmlOptions);
  5566. }
  5567. public static function activeCheckBox($model,$attribute,$htmlOptions=array())
  5568. {
  5569. self::resolveNameID($model,$attribute,$htmlOptions);
  5570. if(!isset($htmlOptions['value']))
  5571. $htmlOptions['value']=1;
  5572. if(!isset($htmlOptions['checked']) && self::resolveValue($model,$attribute)==$htmlOptions['value'])
  5573. $htmlOptions['checked']='checked';
  5574. self::clientChange('click',$htmlOptions);
  5575. if(array_key_exists('uncheckValue',$htmlOptions))
  5576. {
  5577. $uncheck=$htmlOptions['uncheckValue'];
  5578. unset($htmlOptions['uncheckValue']);
  5579. }
  5580. else
  5581. $uncheck='0';
  5582. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5583. $hidden=$uncheck!==null ? self::hiddenField($htmlOptions['name'],$uncheck,$hiddenOptions) : '';
  5584. return $hidden . self::activeInputField('checkbox',$model,$attribute,$htmlOptions);
  5585. }
  5586. public static function activeDropDownList($model,$attribute,$data,$htmlOptions=array())
  5587. {
  5588. self::resolveNameID($model,$attribute,$htmlOptions);
  5589. $selection=self::resolveValue($model,$attribute);
  5590. $options="\n".self::listOptions($selection,$data,$htmlOptions);
  5591. self::clientChange('change',$htmlOptions);
  5592. if($model->hasErrors($attribute))
  5593. self::addErrorCss($htmlOptions);
  5594. $hidden='';
  5595. if(!empty($htmlOptions['multiple']))
  5596. {
  5597. if(substr($htmlOptions['name'],-2)!=='[]')
  5598. $htmlOptions['name'].='[]';
  5599. if(isset($htmlOptions['unselectValue']))
  5600. {
  5601. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5602. $hidden=self::hiddenField(substr($htmlOptions['name'],0,-2),$htmlOptions['unselectValue'],$hiddenOptions);
  5603. unset($htmlOptions['unselectValue']);
  5604. }
  5605. }
  5606. return $hidden . self::tag('select',$htmlOptions,$options);
  5607. }
  5608. public static function activeListBox($model,$attribute,$data,$htmlOptions=array())
  5609. {
  5610. if(!isset($htmlOptions['size']))
  5611. $htmlOptions['size']=4;
  5612. return self::activeDropDownList($model,$attribute,$data,$htmlOptions);
  5613. }
  5614. public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
  5615. {
  5616. self::resolveNameID($model,$attribute,$htmlOptions);
  5617. $selection=self::resolveValue($model,$attribute);
  5618. if($model->hasErrors($attribute))
  5619. self::addErrorCss($htmlOptions);
  5620. $name=$htmlOptions['name'];
  5621. unset($htmlOptions['name']);
  5622. if(array_key_exists('uncheckValue',$htmlOptions))
  5623. {
  5624. $uncheck=$htmlOptions['uncheckValue'];
  5625. unset($htmlOptions['uncheckValue']);
  5626. }
  5627. else
  5628. $uncheck='';
  5629. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5630. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5631. return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
  5632. }
  5633. public static function activeRadioButtonList($model,$attribute,$data,$htmlOptions=array())
  5634. {
  5635. self::resolveNameID($model,$attribute,$htmlOptions);
  5636. $selection=self::resolveValue($model,$attribute);
  5637. if($model->hasErrors($attribute))
  5638. self::addErrorCss($htmlOptions);
  5639. $name=$htmlOptions['name'];
  5640. unset($htmlOptions['name']);
  5641. if(array_key_exists('uncheckValue',$htmlOptions))
  5642. {
  5643. $uncheck=$htmlOptions['uncheckValue'];
  5644. unset($htmlOptions['uncheckValue']);
  5645. }
  5646. else
  5647. $uncheck='';
  5648. $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
  5649. $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
  5650. return $hidden . self::radioButtonList($name,$selection,$data,$htmlOptions);
  5651. }
  5652. public static function errorSummary($model,$header=null,$footer=null,$htmlOptions=array())
  5653. {
  5654. $content='';
  5655. if(!is_array($model))
  5656. $model=array($model);
  5657. if(isset($htmlOptions['firstError']))
  5658. {
  5659. $firstError=$htmlOptions['firstError'];
  5660. unset($htmlOptions['firstError']);
  5661. }
  5662. else
  5663. $firstError=false;
  5664. foreach($model as $m)
  5665. {
  5666. foreach($m->getErrors() as $errors)
  5667. {
  5668. foreach($errors as $error)
  5669. {
  5670. if($error!='')
  5671. $content.="<li>$error</li>\n";
  5672. if($firstError)
  5673. break;
  5674. }
  5675. }
  5676. }
  5677. if($content!=='')
  5678. {
  5679. if($header===null)
  5680. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  5681. if(!isset($htmlOptions['class']))
  5682. $htmlOptions['class']=self::$errorSummaryCss;
  5683. return self::tag('div',$htmlOptions,$header."\n<ul>\n$content</ul>".$footer);
  5684. }
  5685. else
  5686. return '';
  5687. }
  5688. public static function error($model,$attribute,$htmlOptions=array())
  5689. {
  5690. self::resolveName($model,$attribute); // turn [a][b]attr into attr
  5691. $error=$model->getError($attribute);
  5692. if($error!='')
  5693. {
  5694. if(!isset($htmlOptions['class']))
  5695. $htmlOptions['class']=self::$errorMessageCss;
  5696. return self::tag(self::$errorContainerTag,$htmlOptions,$error);
  5697. }
  5698. else
  5699. return '';
  5700. }
  5701. public static function listData($models,$valueField,$textField,$groupField='')
  5702. {
  5703. $listData=array();
  5704. if($groupField==='')
  5705. {
  5706. foreach($models as $model)
  5707. {
  5708. $value=self::value($model,$valueField);
  5709. $text=self::value($model,$textField);
  5710. $listData[$value]=$text;
  5711. }
  5712. }
  5713. else
  5714. {
  5715. foreach($models as $model)
  5716. {
  5717. $group=self::value($model,$groupField);
  5718. $value=self::value($model,$valueField);
  5719. $text=self::value($model,$textField);
  5720. if($group===null)
  5721. $listData[$value]=$text;
  5722. else
  5723. $listData[$group][$value]=$text;
  5724. }
  5725. }
  5726. return $listData;
  5727. }
  5728. public static function value($model,$attribute,$defaultValue=null)
  5729. {
  5730. if(is_scalar($attribute) || $attribute===null)
  5731. foreach(explode('.',$attribute) as $name)
  5732. {
  5733. if(is_object($model) && isset($model->$name))
  5734. $model=$model->$name;
  5735. elseif(is_array($model) && isset($model[$name]))
  5736. $model=$model[$name];
  5737. else
  5738. return $defaultValue;
  5739. }
  5740. else
  5741. return call_user_func($attribute,$model);
  5742. return $model;
  5743. }
  5744. public static function getIdByName($name)
  5745. {
  5746. return str_replace(array('[]','][','[',']',' '),array('','_','_','','_'),$name);
  5747. }
  5748. public static function activeId($model,$attribute)
  5749. {
  5750. return self::getIdByName(self::activeName($model,$attribute));
  5751. }
  5752. public static function modelName($model)
  5753. {
  5754. if(is_callable(self::$_modelNameConverter))
  5755. return call_user_func(self::$_modelNameConverter,$model);
  5756. $className=is_object($model) ? get_class($model) : (string)$model;
  5757. return trim(str_replace('\\','_',$className),'_');
  5758. }
  5759. public static function setModelNameConverter($converter)
  5760. {
  5761. if(is_callable($converter))
  5762. self::$_modelNameConverter=$converter;
  5763. elseif($converter===null)
  5764. self::$_modelNameConverter=null;
  5765. else
  5766. throw new CException(Yii::t('yii','The $converter argument must be a valid callback or null.'));
  5767. }
  5768. public static function activeName($model,$attribute)
  5769. {
  5770. $a=$attribute; // because the attribute name may be changed by resolveName
  5771. return self::resolveName($model,$a);
  5772. }
  5773. protected static function activeInputField($type,$model,$attribute,$htmlOptions)
  5774. {
  5775. $htmlOptions['type']=$type;
  5776. if($type==='text'||$type==='password'||$type==='color'||$type==='date'||$type==='datetime'||
  5777. $type==='datetime-local'||$type==='email'||$type==='month'||$type==='number'||$type==='range'||
  5778. $type==='search'||$type==='tel'||$type==='time'||$type==='url'||$type==='week')
  5779. {
  5780. if(!isset($htmlOptions['maxlength']))
  5781. {
  5782. foreach($model->getValidators($attribute) as $validator)
  5783. {
  5784. if($validator instanceof CStringValidator && $validator->max!==null)
  5785. {
  5786. $htmlOptions['maxlength']=$validator->max;
  5787. break;
  5788. }
  5789. }
  5790. }
  5791. elseif($htmlOptions['maxlength']===false)
  5792. unset($htmlOptions['maxlength']);
  5793. }
  5794. if($type==='file')
  5795. unset($htmlOptions['value']);
  5796. elseif(!isset($htmlOptions['value']))
  5797. $htmlOptions['value']=self::resolveValue($model,$attribute);
  5798. if($model->hasErrors($attribute))
  5799. self::addErrorCss($htmlOptions);
  5800. return self::tag('input',$htmlOptions);
  5801. }
  5802. public static function listOptions($selection,$listData,&$htmlOptions)
  5803. {
  5804. $raw=isset($htmlOptions['encode']) && !$htmlOptions['encode'];
  5805. $content='';
  5806. if(isset($htmlOptions['prompt']))
  5807. {
  5808. $content.='<option value="">'.strtr($htmlOptions['prompt'],array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  5809. unset($htmlOptions['prompt']);
  5810. }
  5811. if(isset($htmlOptions['empty']))
  5812. {
  5813. if(!is_array($htmlOptions['empty']))
  5814. $htmlOptions['empty']=array(''=>$htmlOptions['empty']);
  5815. foreach($htmlOptions['empty'] as $value=>$label)
  5816. $content.='<option value="'.self::encode($value).'">'.strtr($label,array('<'=>'&lt;','>'=>'&gt;'))."</option>\n";
  5817. unset($htmlOptions['empty']);
  5818. }
  5819. if(isset($htmlOptions['options']))
  5820. {
  5821. $options=$htmlOptions['options'];
  5822. unset($htmlOptions['options']);
  5823. }
  5824. else
  5825. $options=array();
  5826. $key=isset($htmlOptions['key']) ? $htmlOptions['key'] : 'primaryKey';
  5827. if(is_array($selection))
  5828. {
  5829. foreach($selection as $i=>$item)
  5830. {
  5831. if(is_object($item))
  5832. $selection[$i]=$item->$key;
  5833. }
  5834. }
  5835. elseif(is_object($selection))
  5836. $selection=$selection->$key;
  5837. foreach($listData as $key=>$value)
  5838. {
  5839. if(is_array($value))
  5840. {
  5841. $content.='<optgroup label="'.($raw?$key : self::encode($key))."\">\n";
  5842. $dummy=array('options'=>$options);
  5843. if(isset($htmlOptions['encode']))
  5844. $dummy['encode']=$htmlOptions['encode'];
  5845. $content.=self::listOptions($selection,$value,$dummy);
  5846. $content.='</optgroup>'."\n";
  5847. }
  5848. else
  5849. {
  5850. $attributes=array('value'=>(string)$key,'encode'=>!$raw);
  5851. if(!is_array($selection) && !strcmp($key,$selection) || is_array($selection) && in_array($key,$selection))
  5852. $attributes['selected']='selected';
  5853. if(isset($options[$key]))
  5854. $attributes=array_merge($attributes,$options[$key]);
  5855. $content.=self::tag('option',$attributes,$raw?(string)$value : self::encode((string)$value))."\n";
  5856. }
  5857. }
  5858. unset($htmlOptions['key']);
  5859. return $content;
  5860. }
  5861. protected static function clientChange($event,&$htmlOptions)
  5862. {
  5863. if(!isset($htmlOptions['submit']) && !isset($htmlOptions['confirm']) && !isset($htmlOptions['ajax']))
  5864. return;
  5865. if(isset($htmlOptions['live']))
  5866. {
  5867. $live=$htmlOptions['live'];
  5868. unset($htmlOptions['live']);
  5869. }
  5870. else
  5871. $live = self::$liveEvents;
  5872. if(isset($htmlOptions['return']) && $htmlOptions['return'])
  5873. $return='return true';
  5874. else
  5875. $return='return false';
  5876. if(isset($htmlOptions['on'.$event]))
  5877. {
  5878. $handler=trim($htmlOptions['on'.$event],';').';';
  5879. unset($htmlOptions['on'.$event]);
  5880. }
  5881. else
  5882. $handler='';
  5883. if(isset($htmlOptions['id']))
  5884. $id=$htmlOptions['id'];
  5885. else
  5886. $id=$htmlOptions['id']=isset($htmlOptions['name'])?$htmlOptions['name']:self::ID_PREFIX.self::$count++;
  5887. $cs=Yii::app()->getClientScript();
  5888. $cs->registerCoreScript('jquery');
  5889. if(isset($htmlOptions['submit']))
  5890. {
  5891. $cs->registerCoreScript('yii');
  5892. $request=Yii::app()->getRequest();
  5893. if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])
  5894. $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();
  5895. if(isset($htmlOptions['params']))
  5896. $params=CJavaScript::encode($htmlOptions['params']);
  5897. else
  5898. $params='{}';
  5899. if($htmlOptions['submit']!=='')
  5900. $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));
  5901. else
  5902. $url='';
  5903. $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";
  5904. }
  5905. if(isset($htmlOptions['ajax']))
  5906. $handler.=self::ajax($htmlOptions['ajax'])."{$return};";
  5907. if(isset($htmlOptions['confirm']))
  5908. {
  5909. $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';
  5910. if($handler!=='')
  5911. $handler="if($confirm) {".$handler."} else return false;";
  5912. else
  5913. $handler="return $confirm;";
  5914. }
  5915. if($live)
  5916. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('body').on('$event','#$id',function(){{$handler}});");
  5917. else
  5918. $cs->registerScript('Yii.CHtml.#' . $id,"jQuery('#$id').on('$event', function(){{$handler}});");
  5919. unset($htmlOptions['params'],$htmlOptions['submit'],$htmlOptions['ajax'],$htmlOptions['confirm'],$htmlOptions['return'],$htmlOptions['csrf']);
  5920. }
  5921. public static function resolveNameID($model,&$attribute,&$htmlOptions)
  5922. {
  5923. if(!isset($htmlOptions['name']))
  5924. $htmlOptions['name']=self::resolveName($model,$attribute);
  5925. if(!isset($htmlOptions['id']))
  5926. $htmlOptions['id']=self::getIdByName($htmlOptions['name']);
  5927. elseif($htmlOptions['id']===false)
  5928. unset($htmlOptions['id']);
  5929. }
  5930. public static function resolveName($model,&$attribute)
  5931. {
  5932. $modelName=self::modelName($model);
  5933. if(($pos=strpos($attribute,'['))!==false)
  5934. {
  5935. if($pos!==0) // e.g. name[a][b]
  5936. return $modelName.'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
  5937. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a][b]name
  5938. {
  5939. $sub=substr($attribute,0,$pos+1);
  5940. $attribute=substr($attribute,$pos+1);
  5941. return $modelName.$sub.'['.$attribute.']';
  5942. }
  5943. if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
  5944. {
  5945. $name=$modelName.'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
  5946. $attribute=$matches[1];
  5947. return $name;
  5948. }
  5949. }
  5950. return $modelName.'['.$attribute.']';
  5951. }
  5952. public static function resolveValue($model,$attribute)
  5953. {
  5954. if(($pos=strpos($attribute,'['))!==false)
  5955. {
  5956. if($pos===0) // [a]name[b][c], should ignore [a]
  5957. {
  5958. if(preg_match('/\](\w+(\[.+)?)/',$attribute,$matches))
  5959. $attribute=$matches[1]; // we get: name[b][c]
  5960. if(($pos=strpos($attribute,'['))===false)
  5961. return $model->$attribute;
  5962. }
  5963. $name=substr($attribute,0,$pos);
  5964. $value=$model->$name;
  5965. foreach(explode('][',rtrim(substr($attribute,$pos+1),']')) as $id)
  5966. {
  5967. if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
  5968. $value=$value[$id];
  5969. else
  5970. return null;
  5971. }
  5972. return $value;
  5973. }
  5974. else
  5975. return $model->$attribute;
  5976. }
  5977. protected static function addErrorCss(&$htmlOptions)
  5978. {
  5979. if(empty(self::$errorCss))
  5980. return;
  5981. if(isset($htmlOptions['class']))
  5982. $htmlOptions['class'].=' '.self::$errorCss;
  5983. else
  5984. $htmlOptions['class']=self::$errorCss;
  5985. }
  5986. public static function renderAttributes($htmlOptions)
  5987. {
  5988. static $specialAttributes=array(
  5989. 'autofocus'=>1,
  5990. 'autoplay'=>1,
  5991. 'async'=>1,
  5992. 'checked'=>1,
  5993. 'controls'=>1,
  5994. 'declare'=>1,
  5995. 'default'=>1,
  5996. 'defer'=>1,
  5997. 'disabled'=>1,
  5998. 'formnovalidate'=>1,
  5999. 'hidden'=>1,
  6000. 'ismap'=>1,
  6001. 'itemscope'=>1,
  6002. 'loop'=>1,
  6003. 'multiple'=>1,
  6004. 'muted'=>1,
  6005. 'nohref'=>1,
  6006. 'noresize'=>1,
  6007. 'novalidate'=>1,
  6008. 'open'=>1,
  6009. 'readonly'=>1,
  6010. 'required'=>1,
  6011. 'reversed'=>1,
  6012. 'scoped'=>1,
  6013. 'seamless'=>1,
  6014. 'selected'=>1,
  6015. 'typemustmatch'=>1,
  6016. );
  6017. if($htmlOptions===array())
  6018. return '';
  6019. $html='';
  6020. if(isset($htmlOptions['encode']))
  6021. {
  6022. $raw=!$htmlOptions['encode'];
  6023. unset($htmlOptions['encode']);
  6024. }
  6025. else
  6026. $raw=false;
  6027. foreach($htmlOptions as $name=>$value)
  6028. {
  6029. if(isset($specialAttributes[$name]))
  6030. {
  6031. if($value===false && $name==='async') {
  6032. $html .= ' ' . $name.'="false"';
  6033. }
  6034. elseif($value)
  6035. {
  6036. $html .= ' ' . $name;
  6037. if(self::$renderSpecialAttributesValue)
  6038. $html .= '="' . $name . '"';
  6039. }
  6040. }
  6041. elseif($value!==null)
  6042. $html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"';
  6043. }
  6044. return $html;
  6045. }
  6046. }
  6047. class CWidgetFactory extends CApplicationComponent implements IWidgetFactory
  6048. {
  6049. public $enableSkin=false;
  6050. public $widgets=array();
  6051. public $skinnableWidgets;
  6052. public $skinPath;
  6053. private $_skins=array(); // class name, skin name, property name => value
  6054. public function init()
  6055. {
  6056. parent::init();
  6057. if($this->enableSkin && $this->skinPath===null)
  6058. $this->skinPath=Yii::app()->getViewPath().DIRECTORY_SEPARATOR.'skins';
  6059. }
  6060. public function createWidget($owner,$className,$properties=array())
  6061. {
  6062. $className=Yii::import($className,true);
  6063. $widget=new $className($owner);
  6064. if(isset($this->widgets[$className]))
  6065. $properties=$properties===array() ? $this->widgets[$className] : CMap::mergeArray($this->widgets[$className],$properties);
  6066. if($this->enableSkin)
  6067. {
  6068. if($this->skinnableWidgets===null || in_array($className,$this->skinnableWidgets))
  6069. {
  6070. $skinName=isset($properties['skin']) ? $properties['skin'] : 'default';
  6071. if($skinName!==false && ($skin=$this->getSkin($className,$skinName))!==array())
  6072. $properties=$properties===array() ? $skin : CMap::mergeArray($skin,$properties);
  6073. }
  6074. }
  6075. foreach($properties as $name=>$value)
  6076. $widget->$name=$value;
  6077. return $widget;
  6078. }
  6079. protected function getSkin($className,$skinName)
  6080. {
  6081. if(!isset($this->_skins[$className][$skinName]))
  6082. {
  6083. $skinFile=$this->skinPath.DIRECTORY_SEPARATOR.$className.'.php';
  6084. if(is_file($skinFile))
  6085. $this->_skins[$className]=require($skinFile);
  6086. else
  6087. $this->_skins[$className]=array();
  6088. if(($theme=Yii::app()->getTheme())!==null)
  6089. {
  6090. $skinFile=$theme->getSkinPath().DIRECTORY_SEPARATOR.$className.'.php';
  6091. if(is_file($skinFile))
  6092. {
  6093. $skins=require($skinFile);
  6094. foreach($skins as $name=>$skin)
  6095. $this->_skins[$className][$name]=$skin;
  6096. }
  6097. }
  6098. if(!isset($this->_skins[$className][$skinName]))
  6099. $this->_skins[$className][$skinName]=array();
  6100. }
  6101. return $this->_skins[$className][$skinName];
  6102. }
  6103. }
  6104. class CWidget extends CBaseController
  6105. {
  6106. public $actionPrefix;
  6107. public $skin='default';
  6108. private static $_viewPaths;
  6109. private static $_counter=0;
  6110. private $_id;
  6111. private $_owner;
  6112. public static function actions()
  6113. {
  6114. return array();
  6115. }
  6116. public function __construct($owner=null)
  6117. {
  6118. $this->_owner=$owner===null?Yii::app()->getController():$owner;
  6119. }
  6120. public function getOwner()
  6121. {
  6122. return $this->_owner;
  6123. }
  6124. public function getId($autoGenerate=true)
  6125. {
  6126. if($this->_id!==null)
  6127. return $this->_id;
  6128. elseif($autoGenerate)
  6129. return $this->_id='yw'.self::$_counter++;
  6130. }
  6131. public function setId($value)
  6132. {
  6133. $this->_id=$value;
  6134. }
  6135. public function getController()
  6136. {
  6137. if($this->_owner instanceof CController)
  6138. return $this->_owner;
  6139. else
  6140. return Yii::app()->getController();
  6141. }
  6142. public function init()
  6143. {
  6144. }
  6145. public function run()
  6146. {
  6147. }
  6148. public function getViewPath($checkTheme=false)
  6149. {
  6150. $className=get_class($this);
  6151. $scope=$checkTheme?'theme':'local';
  6152. if(isset(self::$_viewPaths[$className][$scope]))
  6153. return self::$_viewPaths[$className][$scope];
  6154. else
  6155. {
  6156. if($checkTheme && ($theme=Yii::app()->getTheme())!==null)
  6157. {
  6158. $path=$theme->getViewPath().DIRECTORY_SEPARATOR;
  6159. if(strpos($className,'\\')!==false) // namespaced class
  6160. $path.=str_replace('\\','_',ltrim($className,'\\'));
  6161. else
  6162. $path.=$className;
  6163. if(is_dir($path))
  6164. return self::$_viewPaths[$className]['theme']=$path;
  6165. }
  6166. $class=new ReflectionClass($className);
  6167. return self::$_viewPaths[$className]['local']=dirname($class->getFileName()).DIRECTORY_SEPARATOR.'views';
  6168. }
  6169. }
  6170. public function getViewFile($viewName)
  6171. {
  6172. if(($renderer=Yii::app()->getViewRenderer())!==null)
  6173. $extension=$renderer->fileExtension;
  6174. else
  6175. $extension='.php';
  6176. if(strpos($viewName,'.')) // a path alias
  6177. $viewFile=Yii::getPathOfAlias($viewName);
  6178. else
  6179. {
  6180. $viewFile=$this->getViewPath(true).DIRECTORY_SEPARATOR.$viewName;
  6181. if(is_file($viewFile.$extension))
  6182. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6183. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6184. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6185. $viewFile=$this->getViewPath(false).DIRECTORY_SEPARATOR.$viewName;
  6186. }
  6187. if(is_file($viewFile.$extension))
  6188. return Yii::app()->findLocalizedFile($viewFile.$extension);
  6189. elseif($extension!=='.php' && is_file($viewFile.'.php'))
  6190. return Yii::app()->findLocalizedFile($viewFile.'.php');
  6191. else
  6192. return false;
  6193. }
  6194. public function render($view,$data=null,$return=false)
  6195. {
  6196. if(($viewFile=$this->getViewFile($view))!==false)
  6197. return $this->renderFile($viewFile,$data,$return);
  6198. else
  6199. throw new CException(Yii::t('yii','{widget} cannot find the view "{view}".',
  6200. array('{widget}'=>get_class($this), '{view}'=>$view)));
  6201. }
  6202. }
  6203. class CClientScript extends CApplicationComponent
  6204. {
  6205. const POS_HEAD=0;
  6206. const POS_BEGIN=1;
  6207. const POS_END=2;
  6208. const POS_LOAD=3;
  6209. const POS_READY=4;
  6210. public $enableJavaScript=true;
  6211. public $scriptMap=array();
  6212. public $packages=array();
  6213. public $corePackages;
  6214. public $scripts=array();
  6215. protected $cssFiles=array();
  6216. protected $scriptFiles=array();
  6217. protected $metaTags=array();
  6218. protected $linkTags=array();
  6219. protected $css=array();
  6220. protected $hasScripts=false;
  6221. protected $coreScripts=array();
  6222. public $coreScriptPosition=self::POS_HEAD;
  6223. public $defaultScriptFilePosition=self::POS_HEAD;
  6224. public $defaultScriptPosition=self::POS_READY;
  6225. private $_baseUrl;
  6226. public function reset()
  6227. {
  6228. $this->hasScripts=false;
  6229. $this->coreScripts=array();
  6230. $this->cssFiles=array();
  6231. $this->css=array();
  6232. $this->scriptFiles=array();
  6233. $this->scripts=array();
  6234. $this->metaTags=array();
  6235. $this->linkTags=array();
  6236. $this->recordCachingAction('clientScript','reset',array());
  6237. }
  6238. public function render(&$output)
  6239. {
  6240. if(!$this->hasScripts)
  6241. return;
  6242. $this->renderCoreScripts();
  6243. if(!empty($this->scriptMap))
  6244. $this->remapScripts();
  6245. $this->unifyScripts();
  6246. $this->renderHead($output);
  6247. if($this->enableJavaScript)
  6248. {
  6249. $this->renderBodyBegin($output);
  6250. $this->renderBodyEnd($output);
  6251. }
  6252. }
  6253. protected function unifyScripts()
  6254. {
  6255. if(!$this->enableJavaScript)
  6256. return;
  6257. $map=array();
  6258. if(isset($this->scriptFiles[self::POS_HEAD]))
  6259. $map=$this->scriptFiles[self::POS_HEAD];
  6260. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6261. {
  6262. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFile=>$scriptFileValue)
  6263. {
  6264. if(isset($map[$scriptFile]))
  6265. unset($this->scriptFiles[self::POS_BEGIN][$scriptFile]);
  6266. else
  6267. $map[$scriptFile]=true;
  6268. }
  6269. }
  6270. if(isset($this->scriptFiles[self::POS_END]))
  6271. {
  6272. foreach($this->scriptFiles[self::POS_END] as $key=>$scriptFile)
  6273. {
  6274. if(isset($map[$key]))
  6275. unset($this->scriptFiles[self::POS_END][$key]);
  6276. }
  6277. }
  6278. }
  6279. protected function remapScripts()
  6280. {
  6281. $cssFiles=array();
  6282. foreach($this->cssFiles as $url=>$media)
  6283. {
  6284. $name=basename($url);
  6285. if(isset($this->scriptMap[$name]))
  6286. {
  6287. if($this->scriptMap[$name]!==false)
  6288. $cssFiles[$this->scriptMap[$name]]=$media;
  6289. }
  6290. elseif(isset($this->scriptMap['*.css']))
  6291. {
  6292. if($this->scriptMap['*.css']!==false)
  6293. $cssFiles[$this->scriptMap['*.css']]=$media;
  6294. }
  6295. else
  6296. $cssFiles[$url]=$media;
  6297. }
  6298. $this->cssFiles=$cssFiles;
  6299. $jsFiles=array();
  6300. foreach($this->scriptFiles as $position=>$scriptFiles)
  6301. {
  6302. $jsFiles[$position]=array();
  6303. foreach($scriptFiles as $scriptFile=>$scriptFileValue)
  6304. {
  6305. $name=basename($scriptFile);
  6306. if(isset($this->scriptMap[$name]))
  6307. {
  6308. if($this->scriptMap[$name]!==false)
  6309. $jsFiles[$position][$this->scriptMap[$name]]=$this->scriptMap[$name];
  6310. }
  6311. elseif(isset($this->scriptMap['*.js']))
  6312. {
  6313. if($this->scriptMap['*.js']!==false)
  6314. $jsFiles[$position][$this->scriptMap['*.js']]=$this->scriptMap['*.js'];
  6315. }
  6316. else
  6317. $jsFiles[$position][$scriptFile]=$scriptFileValue;
  6318. }
  6319. }
  6320. $this->scriptFiles=$jsFiles;
  6321. }
  6322. protected function renderScriptBatch(array $scripts)
  6323. {
  6324. $html = '';
  6325. $scriptBatches = array();
  6326. foreach($scripts as $scriptValue)
  6327. {
  6328. if(is_array($scriptValue))
  6329. {
  6330. $scriptContent = $scriptValue['content'];
  6331. unset($scriptValue['content']);
  6332. $scriptHtmlOptions = $scriptValue;
  6333. ksort($scriptHtmlOptions);
  6334. }
  6335. else
  6336. {
  6337. $scriptContent = $scriptValue;
  6338. $scriptHtmlOptions = array();
  6339. }
  6340. $key=serialize($scriptHtmlOptions);
  6341. $scriptBatches[$key]['htmlOptions']=$scriptHtmlOptions;
  6342. $scriptBatches[$key]['scripts'][]=$scriptContent;
  6343. }
  6344. foreach($scriptBatches as $scriptBatch)
  6345. if(!empty($scriptBatch['scripts']))
  6346. $html.=CHtml::script(implode("\n",$scriptBatch['scripts']),$scriptBatch['htmlOptions'])."\n";
  6347. return $html;
  6348. }
  6349. public function renderCoreScripts()
  6350. {
  6351. if($this->coreScripts===null)
  6352. return;
  6353. $cssFiles=array();
  6354. $jsFiles=array();
  6355. foreach($this->coreScripts as $name=>$package)
  6356. {
  6357. $baseUrl=$this->getPackageBaseUrl($name);
  6358. if(!empty($package['js']))
  6359. {
  6360. foreach($package['js'] as $js)
  6361. $jsFiles[$baseUrl.'/'.$js]=$baseUrl.'/'.$js;
  6362. }
  6363. if(!empty($package['css']))
  6364. {
  6365. foreach($package['css'] as $css)
  6366. $cssFiles[$baseUrl.'/'.$css]='';
  6367. }
  6368. }
  6369. // merge in place
  6370. if($cssFiles!==array())
  6371. {
  6372. foreach($this->cssFiles as $cssFile=>$media)
  6373. $cssFiles[$cssFile]=$media;
  6374. $this->cssFiles=$cssFiles;
  6375. }
  6376. if($jsFiles!==array())
  6377. {
  6378. if(isset($this->scriptFiles[$this->coreScriptPosition]))
  6379. {
  6380. foreach($this->scriptFiles[$this->coreScriptPosition] as $url => $value)
  6381. $jsFiles[$url]=$value;
  6382. }
  6383. $this->scriptFiles[$this->coreScriptPosition]=$jsFiles;
  6384. }
  6385. }
  6386. public function renderHead(&$output)
  6387. {
  6388. $html='';
  6389. foreach($this->metaTags as $meta)
  6390. $html.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
  6391. foreach($this->linkTags as $link)
  6392. $html.=CHtml::linkTag(null,null,null,null,$link)."\n";
  6393. foreach($this->cssFiles as $url=>$media)
  6394. $html.=CHtml::cssFile($url,$media)."\n";
  6395. foreach($this->css as $css)
  6396. $html.=CHtml::css($css[0],$css[1])."\n";
  6397. if($this->enableJavaScript)
  6398. {
  6399. if(isset($this->scriptFiles[self::POS_HEAD]))
  6400. {
  6401. foreach($this->scriptFiles[self::POS_HEAD] as $scriptFileValueUrl=>$scriptFileValue)
  6402. {
  6403. if(is_array($scriptFileValue))
  6404. $html.=CHtml::scriptFile($scriptFileValueUrl,$scriptFileValue)."\n";
  6405. else
  6406. $html.=CHtml::scriptFile($scriptFileValueUrl)."\n";
  6407. }
  6408. }
  6409. if(isset($this->scripts[self::POS_HEAD]))
  6410. $html.=$this->renderScriptBatch($this->scripts[self::POS_HEAD]);
  6411. }
  6412. if($html!=='')
  6413. {
  6414. $count=0;
  6415. $output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
  6416. if($count)
  6417. $output=str_replace('<###head###>',$html,$output);
  6418. else
  6419. $output=$html.$output;
  6420. }
  6421. }
  6422. public function renderBodyBegin(&$output)
  6423. {
  6424. $html='';
  6425. if(isset($this->scriptFiles[self::POS_BEGIN]))
  6426. {
  6427. foreach($this->scriptFiles[self::POS_BEGIN] as $scriptFileUrl=>$scriptFileValue)
  6428. {
  6429. if(is_array($scriptFileValue))
  6430. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6431. else
  6432. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6433. }
  6434. }
  6435. if(isset($this->scripts[self::POS_BEGIN]))
  6436. $html.=$this->renderScriptBatch($this->scripts[self::POS_BEGIN]);
  6437. if($html!=='')
  6438. {
  6439. $count=0;
  6440. $output=preg_replace('/(<body\b[^>]*>)/is','$1<###begin###>',$output,1,$count);
  6441. if($count)
  6442. $output=str_replace('<###begin###>',$html,$output);
  6443. else
  6444. $output=$html.$output;
  6445. }
  6446. }
  6447. public function renderBodyEnd(&$output)
  6448. {
  6449. if(!isset($this->scriptFiles[self::POS_END]) && !isset($this->scripts[self::POS_END])
  6450. && !isset($this->scripts[self::POS_READY]) && !isset($this->scripts[self::POS_LOAD]))
  6451. return;
  6452. $fullPage=0;
  6453. $output=preg_replace('/(<\\/body\s*>)/is','<###end###>$1',$output,1,$fullPage);
  6454. $html='';
  6455. if(isset($this->scriptFiles[self::POS_END]))
  6456. {
  6457. foreach($this->scriptFiles[self::POS_END] as $scriptFileUrl=>$scriptFileValue)
  6458. {
  6459. if(is_array($scriptFileValue))
  6460. $html.=CHtml::scriptFile($scriptFileUrl,$scriptFileValue)."\n";
  6461. else
  6462. $html.=CHtml::scriptFile($scriptFileUrl)."\n";
  6463. }
  6464. }
  6465. $scripts=isset($this->scripts[self::POS_END]) ? $this->scripts[self::POS_END] : array();
  6466. if(isset($this->scripts[self::POS_READY]))
  6467. {
  6468. if($fullPage)
  6469. $scripts[]="jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";
  6470. else
  6471. $scripts[]=implode("\n",$this->scripts[self::POS_READY]);
  6472. }
  6473. if(isset($this->scripts[self::POS_LOAD]))
  6474. {
  6475. if($fullPage)
  6476. $scripts[]="jQuery(window).on('load',function() {\n".implode("\n",$this->scripts[self::POS_LOAD])."\n});";
  6477. else
  6478. $scripts[]=implode("\n",$this->scripts[self::POS_LOAD]);
  6479. }
  6480. if(!empty($scripts))
  6481. $html.=$this->renderScriptBatch($scripts);
  6482. if($fullPage)
  6483. $output=str_replace('<###end###>',$html,$output);
  6484. else
  6485. $output=$output.$html;
  6486. }
  6487. public function getCoreScriptUrl()
  6488. {
  6489. if($this->_baseUrl!==null)
  6490. return $this->_baseUrl;
  6491. else
  6492. return $this->_baseUrl=Yii::app()->getAssetManager()->publish(YII_PATH.'/web/js/source');
  6493. }
  6494. public function setCoreScriptUrl($value)
  6495. {
  6496. $this->_baseUrl=$value;
  6497. }
  6498. public function getPackageBaseUrl($name)
  6499. {
  6500. if(!isset($this->coreScripts[$name]))
  6501. return false;
  6502. $package=$this->coreScripts[$name];
  6503. if(isset($package['baseUrl']))
  6504. {
  6505. $baseUrl=$package['baseUrl'];
  6506. if($baseUrl==='' || $baseUrl[0]!=='/' && strpos($baseUrl,'://')===false)
  6507. $baseUrl=Yii::app()->getRequest()->getBaseUrl().'/'.$baseUrl;
  6508. $baseUrl=rtrim($baseUrl,'/');
  6509. }
  6510. elseif(isset($package['basePath']))
  6511. $baseUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias($package['basePath']));
  6512. else
  6513. $baseUrl=$this->getCoreScriptUrl();
  6514. return $this->coreScripts[$name]['baseUrl']=$baseUrl;
  6515. }
  6516. public function registerPackage($name)
  6517. {
  6518. return $this->registerCoreScript($name);
  6519. }
  6520. public function registerCoreScript($name)
  6521. {
  6522. if(isset($this->coreScripts[$name]))
  6523. return $this;
  6524. if(isset($this->packages[$name]))
  6525. $package=$this->packages[$name];
  6526. else
  6527. {
  6528. if($this->corePackages===null)
  6529. $this->corePackages=require(YII_PATH.'/web/js/packages.php');
  6530. if(isset($this->corePackages[$name]))
  6531. $package=$this->corePackages[$name];
  6532. }
  6533. if(isset($package))
  6534. {
  6535. if(!empty($package['depends']))
  6536. {
  6537. foreach($package['depends'] as $p)
  6538. $this->registerCoreScript($p);
  6539. }
  6540. $this->coreScripts[$name]=$package;
  6541. $this->hasScripts=true;
  6542. $params=func_get_args();
  6543. $this->recordCachingAction('clientScript','registerCoreScript',$params);
  6544. }
  6545. elseif(YII_DEBUG)
  6546. throw new CException('There is no CClientScript package: '.$name);
  6547. else
  6548. Yii::log('There is no CClientScript package: '.$name,CLogger::LEVEL_WARNING,'system.web.CClientScript');
  6549. return $this;
  6550. }
  6551. public function registerCssFile($url,$media='')
  6552. {
  6553. $this->hasScripts=true;
  6554. $this->cssFiles[$url]=$media;
  6555. $params=func_get_args();
  6556. $this->recordCachingAction('clientScript','registerCssFile',$params);
  6557. return $this;
  6558. }
  6559. public function registerCss($id,$css,$media='')
  6560. {
  6561. $this->hasScripts=true;
  6562. $this->css[$id]=array($css,$media);
  6563. $params=func_get_args();
  6564. $this->recordCachingAction('clientScript','registerCss',$params);
  6565. return $this;
  6566. }
  6567. public function registerScriptFile($url,$position=null,array $htmlOptions=array())
  6568. {
  6569. if($position===null)
  6570. $position=$this->defaultScriptFilePosition;
  6571. $this->hasScripts=true;
  6572. if(empty($htmlOptions))
  6573. $value=$url;
  6574. else
  6575. {
  6576. $value=$htmlOptions;
  6577. $value['src']=$url;
  6578. }
  6579. $this->scriptFiles[$position][$url]=$value;
  6580. $params=func_get_args();
  6581. $this->recordCachingAction('clientScript','registerScriptFile',$params);
  6582. return $this;
  6583. }
  6584. public function registerScript($id,$script,$position=null,array $htmlOptions=array())
  6585. {
  6586. if($position===null)
  6587. $position=$this->defaultScriptPosition;
  6588. $this->hasScripts=true;
  6589. if(empty($htmlOptions))
  6590. $scriptValue=$script;
  6591. else
  6592. {
  6593. if($position==self::POS_LOAD || $position==self::POS_READY)
  6594. throw new CException(Yii::t('yii','Script HTML options are not allowed for "CClientScript::POS_LOAD" and "CClientScript::POS_READY".'));
  6595. $scriptValue=$htmlOptions;
  6596. $scriptValue['content']=$script;
  6597. }
  6598. $this->scripts[$position][$id]=$scriptValue;
  6599. if($position===self::POS_READY || $position===self::POS_LOAD)
  6600. $this->registerCoreScript('jquery');
  6601. $params=func_get_args();
  6602. $this->recordCachingAction('clientScript','registerScript',$params);
  6603. return $this;
  6604. }
  6605. public function registerMetaTag($content,$name=null,$httpEquiv=null,$options=array(),$id=null)
  6606. {
  6607. $this->hasScripts=true;
  6608. if($name!==null)
  6609. $options['name']=$name;
  6610. if($httpEquiv!==null)
  6611. $options['http-equiv']=$httpEquiv;
  6612. $options['content']=$content;
  6613. $this->metaTags[null===$id?count($this->metaTags):$id]=$options;
  6614. $params=func_get_args();
  6615. $this->recordCachingAction('clientScript','registerMetaTag',$params);
  6616. return $this;
  6617. }
  6618. public function registerLinkTag($relation=null,$type=null,$href=null,$media=null,$options=array())
  6619. {
  6620. $this->hasScripts=true;
  6621. if($relation!==null)
  6622. $options['rel']=$relation;
  6623. if($type!==null)
  6624. $options['type']=$type;
  6625. if($href!==null)
  6626. $options['href']=$href;
  6627. if($media!==null)
  6628. $options['media']=$media;
  6629. $this->linkTags[serialize($options)]=$options;
  6630. $params=func_get_args();
  6631. $this->recordCachingAction('clientScript','registerLinkTag',$params);
  6632. return $this;
  6633. }
  6634. public function isCssFileRegistered($url)
  6635. {
  6636. return isset($this->cssFiles[$url]);
  6637. }
  6638. public function isCssRegistered($id)
  6639. {
  6640. return isset($this->css[$id]);
  6641. }
  6642. public function isScriptFileRegistered($url,$position=self::POS_HEAD)
  6643. {
  6644. return isset($this->scriptFiles[$position][$url]);
  6645. }
  6646. public function isScriptRegistered($id,$position=self::POS_READY)
  6647. {
  6648. return isset($this->scripts[$position][$id]);
  6649. }
  6650. protected function recordCachingAction($context,$method,$params)
  6651. {
  6652. if(($controller=Yii::app()->getController())!==null)
  6653. $controller->recordCachingAction($context,$method,$params);
  6654. }
  6655. public function addPackage($name,$definition)
  6656. {
  6657. $this->packages[$name]=$definition;
  6658. return $this;
  6659. }
  6660. }
  6661. class CList extends CComponent implements IteratorAggregate,ArrayAccess,Countable
  6662. {
  6663. private $_d=array();
  6664. private $_c=0;
  6665. private $_r=false;
  6666. public function __construct($data=null,$readOnly=false)
  6667. {
  6668. if($data!==null)
  6669. $this->copyFrom($data);
  6670. $this->setReadOnly($readOnly);
  6671. }
  6672. public function getReadOnly()
  6673. {
  6674. return $this->_r;
  6675. }
  6676. protected function setReadOnly($value)
  6677. {
  6678. $this->_r=$value;
  6679. }
  6680. public function getIterator()
  6681. {
  6682. return new CListIterator($this->_d);
  6683. }
  6684. public function count()
  6685. {
  6686. return $this->getCount();
  6687. }
  6688. public function getCount()
  6689. {
  6690. return $this->_c;
  6691. }
  6692. public function itemAt($index)
  6693. {
  6694. if(isset($this->_d[$index]))
  6695. return $this->_d[$index];
  6696. elseif($index>=0 && $index<$this->_c) // in case the value is null
  6697. return $this->_d[$index];
  6698. else
  6699. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6700. array('{index}'=>$index)));
  6701. }
  6702. public function add($item)
  6703. {
  6704. $this->insertAt($this->_c,$item);
  6705. return $this->_c-1;
  6706. }
  6707. public function insertAt($index,$item)
  6708. {
  6709. if(!$this->_r)
  6710. {
  6711. if($index===$this->_c)
  6712. $this->_d[$this->_c++]=$item;
  6713. elseif($index>=0 && $index<$this->_c)
  6714. {
  6715. array_splice($this->_d,$index,0,array($item));
  6716. $this->_c++;
  6717. }
  6718. else
  6719. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6720. array('{index}'=>$index)));
  6721. }
  6722. else
  6723. throw new CException(Yii::t('yii','The list is read only.'));
  6724. }
  6725. public function remove($item)
  6726. {
  6727. if(($index=$this->indexOf($item))>=0)
  6728. {
  6729. $this->removeAt($index);
  6730. return $index;
  6731. }
  6732. else
  6733. return false;
  6734. }
  6735. public function removeAt($index)
  6736. {
  6737. if(!$this->_r)
  6738. {
  6739. if($index>=0 && $index<$this->_c)
  6740. {
  6741. $this->_c--;
  6742. if($index===$this->_c)
  6743. return array_pop($this->_d);
  6744. else
  6745. {
  6746. $item=$this->_d[$index];
  6747. array_splice($this->_d,$index,1);
  6748. return $item;
  6749. }
  6750. }
  6751. else
  6752. throw new CException(Yii::t('yii','List index "{index}" is out of bound.',
  6753. array('{index}'=>$index)));
  6754. }
  6755. else
  6756. throw new CException(Yii::t('yii','The list is read only.'));
  6757. }
  6758. public function clear()
  6759. {
  6760. for($i=$this->_c-1;$i>=0;--$i)
  6761. $this->removeAt($i);
  6762. }
  6763. public function contains($item)
  6764. {
  6765. return $this->indexOf($item)>=0;
  6766. }
  6767. public function indexOf($item)
  6768. {
  6769. if(($index=array_search($item,$this->_d,true))!==false)
  6770. return $index;
  6771. else
  6772. return -1;
  6773. }
  6774. public function toArray()
  6775. {
  6776. return $this->_d;
  6777. }
  6778. public function copyFrom($data)
  6779. {
  6780. if(is_array($data) || ($data instanceof Traversable))
  6781. {
  6782. if($this->_c>0)
  6783. $this->clear();
  6784. if($data instanceof CList)
  6785. $data=$data->_d;
  6786. foreach($data as $item)
  6787. $this->add($item);
  6788. }
  6789. elseif($data!==null)
  6790. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6791. }
  6792. public function mergeWith($data)
  6793. {
  6794. if(is_array($data) || ($data instanceof Traversable))
  6795. {
  6796. if($data instanceof CList)
  6797. $data=$data->_d;
  6798. foreach($data as $item)
  6799. $this->add($item);
  6800. }
  6801. elseif($data!==null)
  6802. throw new CException(Yii::t('yii','List data must be an array or an object implementing Traversable.'));
  6803. }
  6804. public function offsetExists($offset)
  6805. {
  6806. return ($offset>=0 && $offset<$this->_c);
  6807. }
  6808. public function offsetGet($offset)
  6809. {
  6810. return $this->itemAt($offset);
  6811. }
  6812. public function offsetSet($offset,$item)
  6813. {
  6814. if($offset===null || $offset===$this->_c)
  6815. $this->insertAt($this->_c,$item);
  6816. else
  6817. {
  6818. $this->removeAt($offset);
  6819. $this->insertAt($offset,$item);
  6820. }
  6821. }
  6822. public function offsetUnset($offset)
  6823. {
  6824. $this->removeAt($offset);
  6825. }
  6826. }
  6827. class CFilterChain extends CList
  6828. {
  6829. public $controller;
  6830. public $action;
  6831. public $filterIndex=0;
  6832. public function __construct($controller,$action)
  6833. {
  6834. $this->controller=$controller;
  6835. $this->action=$action;
  6836. }
  6837. public static function create($controller,$action,$filters)
  6838. {
  6839. $chain=new CFilterChain($controller,$action);
  6840. $actionID=$action->getId();
  6841. foreach($filters as $filter)
  6842. {
  6843. if(is_string($filter)) // filterName [+|- action1 action2]
  6844. {
  6845. if(($pos=strpos($filter,'+'))!==false || ($pos=strpos($filter,'-'))!==false)
  6846. {
  6847. $matched=preg_match("/\b{$actionID}\b/i",substr($filter,$pos+1))>0;
  6848. if(($filter[$pos]==='+')===$matched)
  6849. $filter=CInlineFilter::create($controller,trim(substr($filter,0,$pos)));
  6850. }
  6851. else
  6852. $filter=CInlineFilter::create($controller,$filter);
  6853. }
  6854. elseif(is_array($filter)) // array('path.to.class [+|- action1, action2]','param1'=>'value1',...)
  6855. {
  6856. if(!isset($filter[0]))
  6857. throw new CException(Yii::t('yii','The first element in a filter configuration must be the filter class.'));
  6858. $filterClass=$filter[0];
  6859. unset($filter[0]);
  6860. if(($pos=strpos($filterClass,'+'))!==false || ($pos=strpos($filterClass,'-'))!==false)
  6861. {
  6862. $matched=preg_match("/\b{$actionID}\b/i",substr($filterClass,$pos+1))>0;
  6863. if(($filterClass[$pos]==='+')===$matched)
  6864. $filterClass=trim(substr($filterClass,0,$pos));
  6865. else
  6866. continue;
  6867. }
  6868. $filter['class']=$filterClass;
  6869. $filter=Yii::createComponent($filter);
  6870. }
  6871. if(is_object($filter))
  6872. {
  6873. $filter->init();
  6874. $chain->add($filter);
  6875. }
  6876. }
  6877. return $chain;
  6878. }
  6879. public function insertAt($index,$item)
  6880. {
  6881. if($item instanceof IFilter)
  6882. parent::insertAt($index,$item);
  6883. else
  6884. throw new CException(Yii::t('yii','CFilterChain can only take objects implementing the IFilter interface.'));
  6885. }
  6886. public function run()
  6887. {
  6888. if($this->offsetExists($this->filterIndex))
  6889. {
  6890. $filter=$this->itemAt($this->filterIndex++);
  6891. $filter->filter($this);
  6892. }
  6893. else
  6894. $this->controller->runAction($this->action);
  6895. }
  6896. }
  6897. class CFilter extends CComponent implements IFilter
  6898. {
  6899. public function filter($filterChain)
  6900. {
  6901. if($this->preFilter($filterChain))
  6902. {
  6903. $filterChain->run();
  6904. $this->postFilter($filterChain);
  6905. }
  6906. }
  6907. public function init()
  6908. {
  6909. }
  6910. protected function preFilter($filterChain)
  6911. {
  6912. return true;
  6913. }
  6914. protected function postFilter($filterChain)
  6915. {
  6916. }
  6917. }
  6918. class CInlineFilter extends CFilter
  6919. {
  6920. public $name;
  6921. public static function create($controller,$filterName)
  6922. {
  6923. if(method_exists($controller,'filter'.$filterName))
  6924. {
  6925. $filter=new CInlineFilter;
  6926. $filter->name=$filterName;
  6927. return $filter;
  6928. }
  6929. else
  6930. throw new CException(Yii::t('yii','Filter "{filter}" is invalid. Controller "{class}" does not have the filter method "filter{filter}".',
  6931. array('{filter}'=>$filterName, '{class}'=>get_class($controller))));
  6932. }
  6933. public function filter($filterChain)
  6934. {
  6935. $method='filter'.$this->name;
  6936. $filterChain->controller->$method($filterChain);
  6937. }
  6938. }
  6939. class CAccessControlFilter extends CFilter
  6940. {
  6941. public $message;
  6942. private $_rules=array();
  6943. public function getRules()
  6944. {
  6945. return $this->_rules;
  6946. }
  6947. public function setRules($rules)
  6948. {
  6949. foreach($rules as $rule)
  6950. {
  6951. if(is_array($rule) && isset($rule[0]))
  6952. {
  6953. $r=new CAccessRule;
  6954. $r->allow=$rule[0]==='allow';
  6955. foreach(array_slice($rule,1) as $name=>$value)
  6956. {
  6957. if($name==='expression' || $name==='roles' || $name==='message' || $name==='deniedCallback')
  6958. $r->$name=$value;
  6959. else
  6960. $r->$name=array_map('strtolower',$value);
  6961. }
  6962. $this->_rules[]=$r;
  6963. }
  6964. }
  6965. }
  6966. protected function preFilter($filterChain)
  6967. {
  6968. $app=Yii::app();
  6969. $request=$app->getRequest();
  6970. $user=$app->getUser();
  6971. $verb=$request->getRequestType();
  6972. $ip=$request->getUserHostAddress();
  6973. foreach($this->getRules() as $rule)
  6974. {
  6975. if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
  6976. break;
  6977. elseif($allow<0) // denied
  6978. {
  6979. if(isset($rule->deniedCallback))
  6980. call_user_func($rule->deniedCallback, $rule);
  6981. else
  6982. $this->accessDenied($user,$this->resolveErrorMessage($rule));
  6983. return false;
  6984. }
  6985. }
  6986. return true;
  6987. }
  6988. protected function resolveErrorMessage($rule)
  6989. {
  6990. if($rule->message!==null)
  6991. return $rule->message;
  6992. elseif($this->message!==null)
  6993. return $this->message;
  6994. else
  6995. return Yii::t('yii','You are not authorized to perform this action.');
  6996. }
  6997. protected function accessDenied($user,$message)
  6998. {
  6999. if($user->getIsGuest())
  7000. $user->loginRequired();
  7001. else
  7002. throw new CHttpException(403,$message);
  7003. }
  7004. }
  7005. class CAccessRule extends CComponent
  7006. {
  7007. public $allow;
  7008. public $actions;
  7009. public $controllers;
  7010. public $users;
  7011. public $roles;
  7012. public $ips;
  7013. public $verbs;
  7014. public $expression;
  7015. public $message;
  7016. public $deniedCallback;
  7017. public function isUserAllowed($user,$controller,$action,$ip,$verb)
  7018. {
  7019. if($this->isActionMatched($action)
  7020. && $this->isUserMatched($user)
  7021. && $this->isRoleMatched($user)
  7022. && $this->isIpMatched($ip)
  7023. && $this->isVerbMatched($verb)
  7024. && $this->isControllerMatched($controller)
  7025. && $this->isExpressionMatched($user))
  7026. return $this->allow ? 1 : -1;
  7027. else
  7028. return 0;
  7029. }
  7030. protected function isActionMatched($action)
  7031. {
  7032. return empty($this->actions) || in_array(strtolower($action->getId()),$this->actions);
  7033. }
  7034. protected function isControllerMatched($controller)
  7035. {
  7036. return empty($this->controllers) || in_array(strtolower($controller->getUniqueId()),$this->controllers);
  7037. }
  7038. protected function isUserMatched($user)
  7039. {
  7040. if(empty($this->users))
  7041. return true;
  7042. foreach($this->users as $u)
  7043. {
  7044. if($u==='*')
  7045. return true;
  7046. elseif($u==='?' && $user->getIsGuest())
  7047. return true;
  7048. elseif($u==='@' && !$user->getIsGuest())
  7049. return true;
  7050. elseif(!strcasecmp($u,$user->getName()))
  7051. return true;
  7052. }
  7053. return false;
  7054. }
  7055. protected function isRoleMatched($user)
  7056. {
  7057. if(empty($this->roles))
  7058. return true;
  7059. foreach($this->roles as $key=>$role)
  7060. {
  7061. if(is_numeric($key))
  7062. {
  7063. if($user->checkAccess($role))
  7064. return true;
  7065. }
  7066. else
  7067. {
  7068. if($user->checkAccess($key,$role))
  7069. return true;
  7070. }
  7071. }
  7072. return false;
  7073. }
  7074. protected function isIpMatched($ip)
  7075. {
  7076. if(empty($this->ips))
  7077. return true;
  7078. foreach($this->ips as $rule)
  7079. {
  7080. if($rule==='*' || $rule===$ip || (($pos=strpos($rule,'*'))!==false && !strncmp($ip,$rule,$pos)))
  7081. return true;
  7082. }
  7083. return false;
  7084. }
  7085. protected function isVerbMatched($verb)
  7086. {
  7087. return empty($this->verbs) || in_array(strtolower($verb),$this->verbs);
  7088. }
  7089. protected function isExpressionMatched($user)
  7090. {
  7091. if($this->expression===null)
  7092. return true;
  7093. else
  7094. return $this->evaluateExpression($this->expression, array('user'=>$user));
  7095. }
  7096. }
  7097. abstract class CModel extends CComponent implements IteratorAggregate, ArrayAccess
  7098. {
  7099. private $_errors=array(); // attribute name => array of errors
  7100. private $_validators; // validators
  7101. private $_scenario=''; // scenario
  7102. abstract public function attributeNames();
  7103. public function rules()
  7104. {
  7105. return array();
  7106. }
  7107. public function behaviors()
  7108. {
  7109. return array();
  7110. }
  7111. public function attributeLabels()
  7112. {
  7113. return array();
  7114. }
  7115. public function validate($attributes=null, $clearErrors=true)
  7116. {
  7117. if($clearErrors)
  7118. $this->clearErrors();
  7119. if($this->beforeValidate())
  7120. {
  7121. foreach($this->getValidators() as $validator)
  7122. $validator->validate($this,$attributes);
  7123. $this->afterValidate();
  7124. return !$this->hasErrors();
  7125. }
  7126. else
  7127. return false;
  7128. }
  7129. protected function afterConstruct()
  7130. {
  7131. if($this->hasEventHandler('onAfterConstruct'))
  7132. $this->onAfterConstruct(new CEvent($this));
  7133. }
  7134. protected function beforeValidate()
  7135. {
  7136. $event=new CModelEvent($this);
  7137. $this->onBeforeValidate($event);
  7138. return $event->isValid;
  7139. }
  7140. protected function afterValidate()
  7141. {
  7142. $this->onAfterValidate(new CEvent($this));
  7143. }
  7144. public function onAfterConstruct($event)
  7145. {
  7146. $this->raiseEvent('onAfterConstruct',$event);
  7147. }
  7148. public function onBeforeValidate($event)
  7149. {
  7150. $this->raiseEvent('onBeforeValidate',$event);
  7151. }
  7152. public function onAfterValidate($event)
  7153. {
  7154. $this->raiseEvent('onAfterValidate',$event);
  7155. }
  7156. public function getValidatorList()
  7157. {
  7158. if($this->_validators===null)
  7159. $this->_validators=$this->createValidators();
  7160. return $this->_validators;
  7161. }
  7162. public function getValidators($attribute=null)
  7163. {
  7164. if($this->_validators===null)
  7165. $this->_validators=$this->createValidators();
  7166. $validators=array();
  7167. $scenario=$this->getScenario();
  7168. foreach($this->_validators as $validator)
  7169. {
  7170. if($validator->applyTo($scenario))
  7171. {
  7172. if($attribute===null || in_array($attribute,$validator->attributes,true))
  7173. $validators[]=$validator;
  7174. }
  7175. }
  7176. return $validators;
  7177. }
  7178. public function createValidators()
  7179. {
  7180. $validators=new CList;
  7181. foreach($this->rules() as $rule)
  7182. {
  7183. if(isset($rule[0],$rule[1])) // attributes, validator name
  7184. $validators->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
  7185. else
  7186. throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
  7187. array('{class}'=>get_class($this))));
  7188. }
  7189. return $validators;
  7190. }
  7191. public function isAttributeRequired($attribute)
  7192. {
  7193. foreach($this->getValidators($attribute) as $validator)
  7194. {
  7195. if($validator instanceof CRequiredValidator)
  7196. return true;
  7197. }
  7198. return false;
  7199. }
  7200. public function isAttributeSafe($attribute)
  7201. {
  7202. $attributes=$this->getSafeAttributeNames();
  7203. return in_array($attribute,$attributes);
  7204. }
  7205. public function getAttributeLabel($attribute)
  7206. {
  7207. $labels=$this->attributeLabels();
  7208. if(isset($labels[$attribute]))
  7209. return $labels[$attribute];
  7210. else
  7211. return $this->generateAttributeLabel($attribute);
  7212. }
  7213. public function hasErrors($attribute=null)
  7214. {
  7215. if($attribute===null)
  7216. return $this->_errors!==array();
  7217. else
  7218. return isset($this->_errors[$attribute]);
  7219. }
  7220. public function getErrors($attribute=null)
  7221. {
  7222. if($attribute===null)
  7223. return $this->_errors;
  7224. else
  7225. return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array();
  7226. }
  7227. public function getError($attribute)
  7228. {
  7229. return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
  7230. }
  7231. public function addError($attribute,$error)
  7232. {
  7233. $this->_errors[$attribute][]=$error;
  7234. }
  7235. public function addErrors($errors)
  7236. {
  7237. foreach($errors as $attribute=>$error)
  7238. {
  7239. if(is_array($error))
  7240. {
  7241. foreach($error as $e)
  7242. $this->addError($attribute, $e);
  7243. }
  7244. else
  7245. $this->addError($attribute, $error);
  7246. }
  7247. }
  7248. public function clearErrors($attribute=null)
  7249. {
  7250. if($attribute===null)
  7251. $this->_errors=array();
  7252. else
  7253. unset($this->_errors[$attribute]);
  7254. }
  7255. public function generateAttributeLabel($name)
  7256. {
  7257. return ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
  7258. }
  7259. public function getAttributes($names=null)
  7260. {
  7261. $values=array();
  7262. foreach($this->attributeNames() as $name)
  7263. $values[$name]=$this->$name;
  7264. if(is_array($names))
  7265. {
  7266. $values2=array();
  7267. foreach($names as $name)
  7268. $values2[$name]=isset($values[$name]) ? $values[$name] : null;
  7269. return $values2;
  7270. }
  7271. else
  7272. return $values;
  7273. }
  7274. public function setAttributes($values,$safeOnly=true)
  7275. {
  7276. if(!is_array($values))
  7277. return;
  7278. $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  7279. foreach($values as $name=>$value)
  7280. {
  7281. if(isset($attributes[$name]))
  7282. $this->$name=$value;
  7283. elseif($safeOnly)
  7284. $this->onUnsafeAttribute($name,$value);
  7285. }
  7286. }
  7287. public function unsetAttributes($names=null)
  7288. {
  7289. if($names===null)
  7290. $names=$this->attributeNames();
  7291. foreach($names as $name)
  7292. $this->$name=null;
  7293. }
  7294. public function onUnsafeAttribute($name,$value)
  7295. {
  7296. if(YII_DEBUG)
  7297. Yii::log(Yii::t('yii','Failed to set unsafe attribute "{attribute}" of "{class}".',array('{attribute}'=>$name, '{class}'=>get_class($this))),CLogger::LEVEL_WARNING);
  7298. }
  7299. public function getScenario()
  7300. {
  7301. return $this->_scenario;
  7302. }
  7303. public function setScenario($value)
  7304. {
  7305. $this->_scenario=$value;
  7306. }
  7307. public function getSafeAttributeNames()
  7308. {
  7309. $attributes=array();
  7310. $unsafe=array();
  7311. foreach($this->getValidators() as $validator)
  7312. {
  7313. if(!$validator->safe)
  7314. {
  7315. foreach($validator->attributes as $name)
  7316. $unsafe[]=$name;
  7317. }
  7318. else
  7319. {
  7320. foreach($validator->attributes as $name)
  7321. $attributes[$name]=true;
  7322. }
  7323. }
  7324. foreach($unsafe as $name)
  7325. unset($attributes[$name]);
  7326. return array_keys($attributes);
  7327. }
  7328. public function getIterator()
  7329. {
  7330. $attributes=$this->getAttributes();
  7331. return new CMapIterator($attributes);
  7332. }
  7333. public function offsetExists($offset)
  7334. {
  7335. return property_exists($this,$offset);
  7336. }
  7337. public function offsetGet($offset)
  7338. {
  7339. return $this->$offset;
  7340. }
  7341. public function offsetSet($offset,$item)
  7342. {
  7343. $this->$offset=$item;
  7344. }
  7345. public function offsetUnset($offset)
  7346. {
  7347. unset($this->$offset);
  7348. }
  7349. }
  7350. abstract class CActiveRecord extends CModel
  7351. {
  7352. const BELONGS_TO='CBelongsToRelation';
  7353. const HAS_ONE='CHasOneRelation';
  7354. const HAS_MANY='CHasManyRelation';
  7355. const MANY_MANY='CManyManyRelation';
  7356. const STAT='CStatRelation';
  7357. public static $db;
  7358. private static $_models=array(); // class name => model
  7359. private static $_md=array(); // class name => meta data
  7360. private $_new=false; // whether this instance is new or not
  7361. private $_attributes=array(); // attribute name => attribute value
  7362. private $_related=array(); // attribute name => related objects
  7363. private $_c; // query criteria (used by finder only)
  7364. private $_pk; // old primary key value
  7365. private $_alias='t'; // the table alias being used for query
  7366. public function __construct($scenario='insert')
  7367. {
  7368. if($scenario===null) // internally used by populateRecord() and model()
  7369. return;
  7370. $this->setScenario($scenario);
  7371. $this->setIsNewRecord(true);
  7372. $this->_attributes=$this->getMetaData()->attributeDefaults;
  7373. $this->init();
  7374. $this->attachBehaviors($this->behaviors());
  7375. $this->afterConstruct();
  7376. }
  7377. public function init()
  7378. {
  7379. }
  7380. public function cache($duration, $dependency=null, $queryCount=1)
  7381. {
  7382. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  7383. return $this;
  7384. }
  7385. public function __sleep()
  7386. {
  7387. return array_keys((array)$this);
  7388. }
  7389. public function __get($name)
  7390. {
  7391. if(isset($this->_attributes[$name]))
  7392. return $this->_attributes[$name];
  7393. elseif(isset($this->getMetaData()->columns[$name]))
  7394. return null;
  7395. elseif(isset($this->_related[$name]))
  7396. return $this->_related[$name];
  7397. elseif(isset($this->getMetaData()->relations[$name]))
  7398. return $this->getRelated($name);
  7399. else
  7400. return parent::__get($name);
  7401. }
  7402. public function __set($name,$value)
  7403. {
  7404. if($this->setAttribute($name,$value)===false)
  7405. {
  7406. if(isset($this->getMetaData()->relations[$name]))
  7407. $this->_related[$name]=$value;
  7408. else
  7409. parent::__set($name,$value);
  7410. }
  7411. }
  7412. public function __isset($name)
  7413. {
  7414. if(isset($this->_attributes[$name]))
  7415. return true;
  7416. elseif(isset($this->getMetaData()->columns[$name]))
  7417. return false;
  7418. elseif(isset($this->_related[$name]))
  7419. return true;
  7420. elseif(isset($this->getMetaData()->relations[$name]))
  7421. return $this->getRelated($name)!==null;
  7422. else
  7423. return parent::__isset($name);
  7424. }
  7425. public function __unset($name)
  7426. {
  7427. if(isset($this->getMetaData()->columns[$name]))
  7428. unset($this->_attributes[$name]);
  7429. elseif(isset($this->getMetaData()->relations[$name]))
  7430. unset($this->_related[$name]);
  7431. else
  7432. parent::__unset($name);
  7433. }
  7434. public function __call($name,$parameters)
  7435. {
  7436. if(isset($this->getMetaData()->relations[$name]))
  7437. {
  7438. if(empty($parameters))
  7439. return $this->getRelated($name,false);
  7440. else
  7441. return $this->getRelated($name,false,$parameters[0]);
  7442. }
  7443. $scopes=$this->scopes();
  7444. if(isset($scopes[$name]))
  7445. {
  7446. $this->getDbCriteria()->mergeWith($scopes[$name]);
  7447. return $this;
  7448. }
  7449. return parent::__call($name,$parameters);
  7450. }
  7451. public function getRelated($name,$refresh=false,$params=array())
  7452. {
  7453. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  7454. return $this->_related[$name];
  7455. $md=$this->getMetaData();
  7456. if(!isset($md->relations[$name]))
  7457. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  7458. array('{class}'=>get_class($this), '{name}'=>$name)));
  7459. $relation=$md->relations[$name];
  7460. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  7461. return $relation instanceof CHasOneRelation ? null : array();
  7462. if($params!==array()) // dynamic query
  7463. {
  7464. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7465. if($exists)
  7466. $save=$this->_related[$name];
  7467. if($params instanceof CDbCriteria)
  7468. $params = $params->toArray();
  7469. $r=array($name=>$params);
  7470. }
  7471. else
  7472. $r=$name;
  7473. unset($this->_related[$name]);
  7474. $finder=$this->getActiveFinder($r);
  7475. $finder->lazyFind($this);
  7476. if(!isset($this->_related[$name]))
  7477. {
  7478. if($relation instanceof CHasManyRelation)
  7479. $this->_related[$name]=array();
  7480. elseif($relation instanceof CStatRelation)
  7481. $this->_related[$name]=$relation->defaultValue;
  7482. else
  7483. $this->_related[$name]=null;
  7484. }
  7485. if($params!==array())
  7486. {
  7487. $results=$this->_related[$name];
  7488. if($exists)
  7489. $this->_related[$name]=$save;
  7490. else
  7491. unset($this->_related[$name]);
  7492. return $results;
  7493. }
  7494. else
  7495. return $this->_related[$name];
  7496. }
  7497. public function hasRelated($name)
  7498. {
  7499. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  7500. }
  7501. public function getDbCriteria($createIfNull=true)
  7502. {
  7503. if($this->_c===null)
  7504. {
  7505. if(($c=$this->defaultScope())!==array() || $createIfNull)
  7506. $this->_c=new CDbCriteria($c);
  7507. }
  7508. return $this->_c;
  7509. }
  7510. public function setDbCriteria($criteria)
  7511. {
  7512. $this->_c=$criteria;
  7513. }
  7514. public function defaultScope()
  7515. {
  7516. return array();
  7517. }
  7518. public function resetScope($resetDefault=true)
  7519. {
  7520. if($resetDefault)
  7521. $this->_c=new CDbCriteria();
  7522. else
  7523. $this->_c=null;
  7524. return $this;
  7525. }
  7526. public static function model($className=__CLASS__)
  7527. {
  7528. if(isset(self::$_models[$className]))
  7529. return self::$_models[$className];
  7530. else
  7531. {
  7532. $model=self::$_models[$className]=new $className(null);
  7533. $model->attachBehaviors($model->behaviors());
  7534. return $model;
  7535. }
  7536. }
  7537. public function getMetaData()
  7538. {
  7539. $className=get_class($this);
  7540. if(!array_key_exists($className,self::$_md))
  7541. {
  7542. self::$_md[$className]=null; // preventing recursive invokes of {@link getMetaData()} via {@link __get()}
  7543. self::$_md[$className]=new CActiveRecordMetaData($this);
  7544. }
  7545. return self::$_md[$className];
  7546. }
  7547. public function refreshMetaData()
  7548. {
  7549. $className=get_class($this);
  7550. if(array_key_exists($className,self::$_md))
  7551. unset(self::$_md[$className]);
  7552. }
  7553. public function tableName()
  7554. {
  7555. $tableName = get_class($this);
  7556. if(($pos=strrpos($tableName,'\\')) !== false)
  7557. return substr($tableName,$pos+1);
  7558. return $tableName;
  7559. }
  7560. public function primaryKey()
  7561. {
  7562. }
  7563. public function relations()
  7564. {
  7565. return array();
  7566. }
  7567. public function scopes()
  7568. {
  7569. return array();
  7570. }
  7571. public function attributeNames()
  7572. {
  7573. return array_keys($this->getMetaData()->columns);
  7574. }
  7575. public function getAttributeLabel($attribute)
  7576. {
  7577. $labels=$this->attributeLabels();
  7578. if(isset($labels[$attribute]))
  7579. return $labels[$attribute];
  7580. elseif(strpos($attribute,'.')!==false)
  7581. {
  7582. $segs=explode('.',$attribute);
  7583. $name=array_pop($segs);
  7584. $model=$this;
  7585. foreach($segs as $seg)
  7586. {
  7587. $relations=$model->getMetaData()->relations;
  7588. if(isset($relations[$seg]))
  7589. $model=CActiveRecord::model($relations[$seg]->className);
  7590. else
  7591. break;
  7592. }
  7593. return $model->getAttributeLabel($name);
  7594. }
  7595. else
  7596. return $this->generateAttributeLabel($attribute);
  7597. }
  7598. public function getDbConnection()
  7599. {
  7600. if(self::$db!==null)
  7601. return self::$db;
  7602. else
  7603. {
  7604. self::$db=Yii::app()->getDb();
  7605. if(self::$db instanceof CDbConnection)
  7606. return self::$db;
  7607. else
  7608. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  7609. }
  7610. }
  7611. public function getActiveRelation($name)
  7612. {
  7613. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  7614. }
  7615. public function getTableSchema()
  7616. {
  7617. return $this->getMetaData()->tableSchema;
  7618. }
  7619. public function getCommandBuilder()
  7620. {
  7621. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  7622. }
  7623. public function hasAttribute($name)
  7624. {
  7625. return isset($this->getMetaData()->columns[$name]);
  7626. }
  7627. public function getAttribute($name)
  7628. {
  7629. if(property_exists($this,$name))
  7630. return $this->$name;
  7631. elseif(isset($this->_attributes[$name]))
  7632. return $this->_attributes[$name];
  7633. }
  7634. public function setAttribute($name,$value)
  7635. {
  7636. if(property_exists($this,$name))
  7637. $this->$name=$value;
  7638. elseif(isset($this->getMetaData()->columns[$name]))
  7639. $this->_attributes[$name]=$value;
  7640. else
  7641. return false;
  7642. return true;
  7643. }
  7644. public function addRelatedRecord($name,$record,$index)
  7645. {
  7646. if($index!==false)
  7647. {
  7648. if(!isset($this->_related[$name]))
  7649. $this->_related[$name]=array();
  7650. if($record instanceof CActiveRecord)
  7651. {
  7652. if($index===true)
  7653. $this->_related[$name][]=$record;
  7654. else
  7655. $this->_related[$name][$index]=$record;
  7656. }
  7657. }
  7658. elseif(!isset($this->_related[$name]))
  7659. $this->_related[$name]=$record;
  7660. }
  7661. public function getAttributes($names=true)
  7662. {
  7663. $attributes=$this->_attributes;
  7664. foreach($this->getMetaData()->columns as $name=>$column)
  7665. {
  7666. if(property_exists($this,$name))
  7667. $attributes[$name]=$this->$name;
  7668. elseif($names===true && !isset($attributes[$name]))
  7669. $attributes[$name]=null;
  7670. }
  7671. if(is_array($names))
  7672. {
  7673. $attrs=array();
  7674. foreach($names as $name)
  7675. {
  7676. if(property_exists($this,$name))
  7677. $attrs[$name]=$this->$name;
  7678. else
  7679. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  7680. }
  7681. return $attrs;
  7682. }
  7683. else
  7684. return $attributes;
  7685. }
  7686. public function save($runValidation=true,$attributes=null)
  7687. {
  7688. if(!$runValidation || $this->validate($attributes))
  7689. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  7690. else
  7691. return false;
  7692. }
  7693. public function getIsNewRecord()
  7694. {
  7695. return $this->_new;
  7696. }
  7697. public function setIsNewRecord($value)
  7698. {
  7699. $this->_new=$value;
  7700. }
  7701. public function onBeforeSave($event)
  7702. {
  7703. $this->raiseEvent('onBeforeSave',$event);
  7704. }
  7705. public function onAfterSave($event)
  7706. {
  7707. $this->raiseEvent('onAfterSave',$event);
  7708. }
  7709. public function onBeforeDelete($event)
  7710. {
  7711. $this->raiseEvent('onBeforeDelete',$event);
  7712. }
  7713. public function onAfterDelete($event)
  7714. {
  7715. $this->raiseEvent('onAfterDelete',$event);
  7716. }
  7717. public function onBeforeFind($event)
  7718. {
  7719. $this->raiseEvent('onBeforeFind',$event);
  7720. }
  7721. public function onAfterFind($event)
  7722. {
  7723. $this->raiseEvent('onAfterFind',$event);
  7724. }
  7725. public function getActiveFinder($with)
  7726. {
  7727. return new CActiveFinder($this,$with);
  7728. }
  7729. public function onBeforeCount($event)
  7730. {
  7731. $this->raiseEvent('onBeforeCount',$event);
  7732. }
  7733. protected function beforeSave()
  7734. {
  7735. if($this->hasEventHandler('onBeforeSave'))
  7736. {
  7737. $event=new CModelEvent($this);
  7738. $this->onBeforeSave($event);
  7739. return $event->isValid;
  7740. }
  7741. else
  7742. return true;
  7743. }
  7744. protected function afterSave()
  7745. {
  7746. if($this->hasEventHandler('onAfterSave'))
  7747. $this->onAfterSave(new CEvent($this));
  7748. }
  7749. protected function beforeDelete()
  7750. {
  7751. if($this->hasEventHandler('onBeforeDelete'))
  7752. {
  7753. $event=new CModelEvent($this);
  7754. $this->onBeforeDelete($event);
  7755. return $event->isValid;
  7756. }
  7757. else
  7758. return true;
  7759. }
  7760. protected function afterDelete()
  7761. {
  7762. if($this->hasEventHandler('onAfterDelete'))
  7763. $this->onAfterDelete(new CEvent($this));
  7764. }
  7765. protected function beforeFind()
  7766. {
  7767. if($this->hasEventHandler('onBeforeFind'))
  7768. {
  7769. $event=new CModelEvent($this);
  7770. $this->onBeforeFind($event);
  7771. }
  7772. }
  7773. protected function beforeCount()
  7774. {
  7775. if($this->hasEventHandler('onBeforeCount'))
  7776. $this->onBeforeCount(new CEvent($this));
  7777. }
  7778. protected function afterFind()
  7779. {
  7780. if($this->hasEventHandler('onAfterFind'))
  7781. $this->onAfterFind(new CEvent($this));
  7782. }
  7783. public function beforeFindInternal()
  7784. {
  7785. $this->beforeFind();
  7786. }
  7787. public function afterFindInternal()
  7788. {
  7789. $this->afterFind();
  7790. }
  7791. public function insert($attributes=null)
  7792. {
  7793. if(!$this->getIsNewRecord())
  7794. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  7795. if($this->beforeSave())
  7796. {
  7797. $builder=$this->getCommandBuilder();
  7798. $table=$this->getTableSchema();
  7799. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  7800. if($command->execute())
  7801. {
  7802. $primaryKey=$table->primaryKey;
  7803. if($table->sequenceName!==null)
  7804. {
  7805. if(is_string($primaryKey) && $this->$primaryKey===null)
  7806. $this->$primaryKey=$builder->getLastInsertID($table);
  7807. elseif(is_array($primaryKey))
  7808. {
  7809. foreach($primaryKey as $pk)
  7810. {
  7811. if($this->$pk===null)
  7812. {
  7813. $this->$pk=$builder->getLastInsertID($table);
  7814. break;
  7815. }
  7816. }
  7817. }
  7818. }
  7819. $this->_pk=$this->getPrimaryKey();
  7820. $this->afterSave();
  7821. $this->setIsNewRecord(false);
  7822. $this->setScenario('update');
  7823. return true;
  7824. }
  7825. }
  7826. return false;
  7827. }
  7828. public function update($attributes=null)
  7829. {
  7830. if($this->getIsNewRecord())
  7831. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7832. if($this->beforeSave())
  7833. {
  7834. if($this->_pk===null)
  7835. $this->_pk=$this->getPrimaryKey();
  7836. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  7837. $this->_pk=$this->getPrimaryKey();
  7838. $this->afterSave();
  7839. return true;
  7840. }
  7841. else
  7842. return false;
  7843. }
  7844. public function saveAttributes($attributes)
  7845. {
  7846. if(!$this->getIsNewRecord())
  7847. {
  7848. $values=array();
  7849. foreach($attributes as $name=>$value)
  7850. {
  7851. if(is_integer($name))
  7852. $values[$value]=$this->$value;
  7853. else
  7854. $values[$name]=$this->$name=$value;
  7855. }
  7856. if($this->_pk===null)
  7857. $this->_pk=$this->getPrimaryKey();
  7858. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  7859. {
  7860. $this->_pk=$this->getPrimaryKey();
  7861. return true;
  7862. }
  7863. else
  7864. return false;
  7865. }
  7866. else
  7867. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  7868. }
  7869. public function saveCounters($counters)
  7870. {
  7871. $builder=$this->getCommandBuilder();
  7872. $table=$this->getTableSchema();
  7873. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  7874. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  7875. if($command->execute())
  7876. {
  7877. foreach($counters as $name=>$value)
  7878. $this->$name=$this->$name+$value;
  7879. return true;
  7880. }
  7881. else
  7882. return false;
  7883. }
  7884. public function delete()
  7885. {
  7886. if(!$this->getIsNewRecord())
  7887. {
  7888. if($this->beforeDelete())
  7889. {
  7890. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  7891. $this->afterDelete();
  7892. return $result;
  7893. }
  7894. else
  7895. return false;
  7896. }
  7897. else
  7898. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  7899. }
  7900. public function refresh()
  7901. {
  7902. if(($record=$this->findByPk($this->getPrimaryKey()))!==null)
  7903. {
  7904. $this->_attributes=array();
  7905. $this->_related=array();
  7906. foreach($this->getMetaData()->columns as $name=>$column)
  7907. {
  7908. if(property_exists($this,$name))
  7909. $this->$name=$record->$name;
  7910. else
  7911. $this->_attributes[$name]=$record->$name;
  7912. }
  7913. return true;
  7914. }
  7915. else
  7916. return false;
  7917. }
  7918. public function equals($record)
  7919. {
  7920. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  7921. }
  7922. public function getPrimaryKey()
  7923. {
  7924. $table=$this->getTableSchema();
  7925. if(is_string($table->primaryKey))
  7926. return $this->{$table->primaryKey};
  7927. elseif(is_array($table->primaryKey))
  7928. {
  7929. $values=array();
  7930. foreach($table->primaryKey as $name)
  7931. $values[$name]=$this->$name;
  7932. return $values;
  7933. }
  7934. else
  7935. return null;
  7936. }
  7937. public function setPrimaryKey($value)
  7938. {
  7939. $this->_pk=$this->getPrimaryKey();
  7940. $table=$this->getTableSchema();
  7941. if(is_string($table->primaryKey))
  7942. $this->{$table->primaryKey}=$value;
  7943. elseif(is_array($table->primaryKey))
  7944. {
  7945. foreach($table->primaryKey as $name)
  7946. $this->$name=$value[$name];
  7947. }
  7948. }
  7949. public function getOldPrimaryKey()
  7950. {
  7951. return $this->_pk;
  7952. }
  7953. public function setOldPrimaryKey($value)
  7954. {
  7955. $this->_pk=$value;
  7956. }
  7957. protected function query($criteria,$all=false)
  7958. {
  7959. $this->beforeFind();
  7960. $this->applyScopes($criteria);
  7961. if(empty($criteria->with))
  7962. {
  7963. if(!$all)
  7964. $criteria->limit=1;
  7965. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  7966. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  7967. }
  7968. else
  7969. {
  7970. $finder=$this->getActiveFinder($criteria->with);
  7971. return $finder->query($criteria,$all);
  7972. }
  7973. }
  7974. public function applyScopes(&$criteria)
  7975. {
  7976. if(!empty($criteria->scopes))
  7977. {
  7978. $scs=$this->scopes();
  7979. $c=$this->getDbCriteria();
  7980. foreach((array)$criteria->scopes as $k=>$v)
  7981. {
  7982. if(is_integer($k))
  7983. {
  7984. if(is_string($v))
  7985. {
  7986. if(isset($scs[$v]))
  7987. {
  7988. $c->mergeWith($scs[$v],true);
  7989. continue;
  7990. }
  7991. $scope=$v;
  7992. $params=array();
  7993. }
  7994. elseif(is_array($v))
  7995. {
  7996. $scope=key($v);
  7997. $params=current($v);
  7998. }
  7999. }
  8000. elseif(is_string($k))
  8001. {
  8002. $scope=$k;
  8003. $params=$v;
  8004. }
  8005. call_user_func_array(array($this,$scope),(array)$params);
  8006. }
  8007. }
  8008. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  8009. {
  8010. $c->mergeWith($criteria);
  8011. $criteria=$c;
  8012. $this->resetScope(false);
  8013. }
  8014. }
  8015. public function getTableAlias($quote=false, $checkScopes=true)
  8016. {
  8017. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  8018. $alias=$criteria->alias;
  8019. else
  8020. $alias=$this->_alias;
  8021. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  8022. }
  8023. public function setTableAlias($alias)
  8024. {
  8025. $this->_alias=$alias;
  8026. }
  8027. public function find($condition='',$params=array())
  8028. {
  8029. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  8030. return $this->query($criteria);
  8031. }
  8032. public function findAll($condition='',$params=array())
  8033. {
  8034. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  8035. return $this->query($criteria,true);
  8036. }
  8037. public function findByPk($pk,$condition='',$params=array())
  8038. {
  8039. $prefix=$this->getTableAlias(true).'.';
  8040. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  8041. return $this->query($criteria);
  8042. }
  8043. public function findAllByPk($pk,$condition='',$params=array())
  8044. {
  8045. $prefix=$this->getTableAlias(true).'.';
  8046. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  8047. return $this->query($criteria,true);
  8048. }
  8049. public function findByAttributes($attributes,$condition='',$params=array())
  8050. {
  8051. $prefix=$this->getTableAlias(true).'.';
  8052. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8053. return $this->query($criteria);
  8054. }
  8055. public function findAllByAttributes($attributes,$condition='',$params=array())
  8056. {
  8057. $prefix=$this->getTableAlias(true).'.';
  8058. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8059. return $this->query($criteria,true);
  8060. }
  8061. public function findBySql($sql,$params=array())
  8062. {
  8063. $this->beforeFind();
  8064. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  8065. {
  8066. $this->resetScope(false);
  8067. $finder=$this->getActiveFinder($criteria->with);
  8068. return $finder->findBySql($sql,$params);
  8069. }
  8070. else
  8071. {
  8072. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  8073. return $this->populateRecord($command->queryRow());
  8074. }
  8075. }
  8076. public function findAllBySql($sql,$params=array())
  8077. {
  8078. $this->beforeFind();
  8079. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  8080. {
  8081. $this->resetScope(false);
  8082. $finder=$this->getActiveFinder($criteria->with);
  8083. return $finder->findAllBySql($sql,$params);
  8084. }
  8085. else
  8086. {
  8087. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  8088. return $this->populateRecords($command->queryAll());
  8089. }
  8090. }
  8091. public function count($condition='',$params=array())
  8092. {
  8093. $this->beforeCount();
  8094. $builder=$this->getCommandBuilder();
  8095. $criteria=$builder->createCriteria($condition,$params);
  8096. $this->applyScopes($criteria);
  8097. if(empty($criteria->with))
  8098. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  8099. else
  8100. {
  8101. $finder=$this->getActiveFinder($criteria->with);
  8102. return $finder->count($criteria);
  8103. }
  8104. }
  8105. public function countByAttributes($attributes,$condition='',$params=array())
  8106. {
  8107. $prefix=$this->getTableAlias(true).'.';
  8108. $builder=$this->getCommandBuilder();
  8109. $this->beforeCount();
  8110. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  8111. $this->applyScopes($criteria);
  8112. if(empty($criteria->with))
  8113. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  8114. else
  8115. {
  8116. $finder=$this->getActiveFinder($criteria->with);
  8117. return $finder->count($criteria);
  8118. }
  8119. }
  8120. public function countBySql($sql,$params=array())
  8121. {
  8122. $this->beforeCount();
  8123. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  8124. }
  8125. public function exists($condition='',$params=array())
  8126. {
  8127. $builder=$this->getCommandBuilder();
  8128. $criteria=$builder->createCriteria($condition,$params);
  8129. $table=$this->getTableSchema();
  8130. $criteria->select='1';
  8131. $criteria->limit=1;
  8132. $this->applyScopes($criteria);
  8133. if(empty($criteria->with))
  8134. return $builder->createFindCommand($table,$criteria,$this->getTableAlias(false, false))->queryRow()!==false;
  8135. else
  8136. {
  8137. $criteria->select='*';
  8138. $finder=$this->getActiveFinder($criteria->with);
  8139. return $finder->count($criteria)>0;
  8140. }
  8141. }
  8142. public function with()
  8143. {
  8144. if(func_num_args()>0)
  8145. {
  8146. $with=func_get_args();
  8147. if(is_array($with[0])) // the parameter is given as an array
  8148. $with=$with[0];
  8149. if(!empty($with))
  8150. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  8151. }
  8152. return $this;
  8153. }
  8154. public function together()
  8155. {
  8156. $this->getDbCriteria()->together=true;
  8157. return $this;
  8158. }
  8159. public function updateByPk($pk,$attributes,$condition='',$params=array())
  8160. {
  8161. $builder=$this->getCommandBuilder();
  8162. $table=$this->getTableSchema();
  8163. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  8164. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  8165. return $command->execute();
  8166. }
  8167. public function updateAll($attributes,$condition='',$params=array())
  8168. {
  8169. $builder=$this->getCommandBuilder();
  8170. $criteria=$builder->createCriteria($condition,$params);
  8171. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  8172. return $command->execute();
  8173. }
  8174. public function updateCounters($counters,$condition='',$params=array())
  8175. {
  8176. $builder=$this->getCommandBuilder();
  8177. $criteria=$builder->createCriteria($condition,$params);
  8178. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  8179. return $command->execute();
  8180. }
  8181. public function deleteByPk($pk,$condition='',$params=array())
  8182. {
  8183. $builder=$this->getCommandBuilder();
  8184. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  8185. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8186. return $command->execute();
  8187. }
  8188. public function deleteAll($condition='',$params=array())
  8189. {
  8190. $builder=$this->getCommandBuilder();
  8191. $criteria=$builder->createCriteria($condition,$params);
  8192. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  8193. return $command->execute();
  8194. }
  8195. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  8196. {
  8197. $builder=$this->getCommandBuilder();
  8198. $table=$this->getTableSchema();
  8199. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  8200. $command=$builder->createDeleteCommand($table,$criteria);
  8201. return $command->execute();
  8202. }
  8203. public function populateRecord($attributes,$callAfterFind=true)
  8204. {
  8205. if($attributes!==false)
  8206. {
  8207. $record=$this->instantiate($attributes);
  8208. $record->setScenario('update');
  8209. $record->init();
  8210. $md=$record->getMetaData();
  8211. foreach($attributes as $name=>$value)
  8212. {
  8213. if(property_exists($record,$name))
  8214. $record->$name=$value;
  8215. elseif(isset($md->columns[$name]))
  8216. $record->_attributes[$name]=$value;
  8217. }
  8218. $record->_pk=$record->getPrimaryKey();
  8219. $record->attachBehaviors($record->behaviors());
  8220. if($callAfterFind)
  8221. $record->afterFind();
  8222. return $record;
  8223. }
  8224. else
  8225. return null;
  8226. }
  8227. public function populateRecords($data,$callAfterFind=true,$index=null)
  8228. {
  8229. $records=array();
  8230. foreach($data as $attributes)
  8231. {
  8232. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  8233. {
  8234. if($index===null)
  8235. $records[]=$record;
  8236. else
  8237. $records[$record->$index]=$record;
  8238. }
  8239. }
  8240. return $records;
  8241. }
  8242. protected function instantiate($attributes)
  8243. {
  8244. $class=get_class($this);
  8245. $model=new $class(null);
  8246. return $model;
  8247. }
  8248. public function offsetExists($offset)
  8249. {
  8250. return $this->__isset($offset);
  8251. }
  8252. }
  8253. class CBaseActiveRelation extends CComponent
  8254. {
  8255. public $name;
  8256. public $className;
  8257. public $foreignKey;
  8258. public $select='*';
  8259. public $condition='';
  8260. public $params=array();
  8261. public $group='';
  8262. public $join='';
  8263. public $joinOptions='';
  8264. public $having='';
  8265. public $order='';
  8266. public function __construct($name,$className,$foreignKey,$options=array())
  8267. {
  8268. $this->name=$name;
  8269. $this->className=$className;
  8270. $this->foreignKey=$foreignKey;
  8271. foreach($options as $name=>$value)
  8272. $this->$name=$value;
  8273. }
  8274. public function mergeWith($criteria,$fromScope=false)
  8275. {
  8276. if($criteria instanceof CDbCriteria)
  8277. $criteria=$criteria->toArray();
  8278. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  8279. {
  8280. if($this->select==='*')
  8281. $this->select=$criteria['select'];
  8282. elseif($criteria['select']!=='*')
  8283. {
  8284. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  8285. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  8286. $this->select=array_merge($select1,array_diff($select2,$select1));
  8287. }
  8288. }
  8289. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  8290. {
  8291. if($this->condition==='')
  8292. $this->condition=$criteria['condition'];
  8293. elseif($criteria['condition']!=='')
  8294. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  8295. }
  8296. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  8297. $this->params=array_merge($this->params,$criteria['params']);
  8298. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  8299. {
  8300. if($this->order==='')
  8301. $this->order=$criteria['order'];
  8302. elseif($criteria['order']!=='')
  8303. $this->order=$criteria['order'].', '.$this->order;
  8304. }
  8305. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  8306. {
  8307. if($this->group==='')
  8308. $this->group=$criteria['group'];
  8309. elseif($criteria['group']!=='')
  8310. $this->group.=', '.$criteria['group'];
  8311. }
  8312. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  8313. {
  8314. if($this->join==='')
  8315. $this->join=$criteria['join'];
  8316. elseif($criteria['join']!=='')
  8317. $this->join.=' '.$criteria['join'];
  8318. }
  8319. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  8320. {
  8321. if($this->having==='')
  8322. $this->having=$criteria['having'];
  8323. elseif($criteria['having']!=='')
  8324. $this->having="({$this->having}) AND ({$criteria['having']})";
  8325. }
  8326. }
  8327. }
  8328. class CStatRelation extends CBaseActiveRelation
  8329. {
  8330. public $select='COUNT(*)';
  8331. public $defaultValue=0;
  8332. public $scopes;
  8333. public function mergeWith($criteria,$fromScope=false)
  8334. {
  8335. if($criteria instanceof CDbCriteria)
  8336. $criteria=$criteria->toArray();
  8337. parent::mergeWith($criteria,$fromScope);
  8338. if(isset($criteria['defaultValue']))
  8339. $this->defaultValue=$criteria['defaultValue'];
  8340. }
  8341. }
  8342. class CActiveRelation extends CBaseActiveRelation
  8343. {
  8344. public $joinType='LEFT OUTER JOIN';
  8345. public $on='';
  8346. public $alias;
  8347. public $with=array();
  8348. public $together;
  8349. public $scopes;
  8350. public $through;
  8351. public function mergeWith($criteria,$fromScope=false)
  8352. {
  8353. if($criteria instanceof CDbCriteria)
  8354. $criteria=$criteria->toArray();
  8355. if($fromScope)
  8356. {
  8357. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  8358. {
  8359. if($this->on==='')
  8360. $this->on=$criteria['condition'];
  8361. elseif($criteria['condition']!=='')
  8362. $this->on="({$this->on}) AND ({$criteria['condition']})";
  8363. }
  8364. unset($criteria['condition']);
  8365. }
  8366. parent::mergeWith($criteria);
  8367. if(isset($criteria['joinType']))
  8368. $this->joinType=$criteria['joinType'];
  8369. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  8370. {
  8371. if($this->on==='')
  8372. $this->on=$criteria['on'];
  8373. elseif($criteria['on']!=='')
  8374. $this->on="({$this->on}) AND ({$criteria['on']})";
  8375. }
  8376. if(isset($criteria['with']))
  8377. $this->with=$criteria['with'];
  8378. if(isset($criteria['alias']))
  8379. $this->alias=$criteria['alias'];
  8380. if(isset($criteria['together']))
  8381. $this->together=$criteria['together'];
  8382. }
  8383. }
  8384. class CBelongsToRelation extends CActiveRelation
  8385. {
  8386. }
  8387. class CHasOneRelation extends CActiveRelation
  8388. {
  8389. }
  8390. class CHasManyRelation extends CActiveRelation
  8391. {
  8392. public $limit=-1;
  8393. public $offset=-1;
  8394. public $index;
  8395. public function mergeWith($criteria,$fromScope=false)
  8396. {
  8397. if($criteria instanceof CDbCriteria)
  8398. $criteria=$criteria->toArray();
  8399. parent::mergeWith($criteria,$fromScope);
  8400. if(isset($criteria['limit']) && $criteria['limit']>0)
  8401. $this->limit=$criteria['limit'];
  8402. if(isset($criteria['offset']) && $criteria['offset']>=0)
  8403. $this->offset=$criteria['offset'];
  8404. if(isset($criteria['index']))
  8405. $this->index=$criteria['index'];
  8406. }
  8407. }
  8408. class CManyManyRelation extends CHasManyRelation
  8409. {
  8410. private $_junctionTableName=null;
  8411. private $_junctionForeignKeys=null;
  8412. public function getJunctionTableName()
  8413. {
  8414. if ($this->_junctionTableName===null)
  8415. $this->initJunctionData();
  8416. return $this->_junctionTableName;
  8417. }
  8418. public function getJunctionForeignKeys()
  8419. {
  8420. if ($this->_junctionForeignKeys===null)
  8421. $this->initJunctionData();
  8422. return $this->_junctionForeignKeys;
  8423. }
  8424. private function initJunctionData()
  8425. {
  8426. if(!preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->foreignKey,$matches))
  8427. throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key. The format of the foreign key must be "joinTable(fk1,fk2,...)".',
  8428. array('{class}'=>$this->className,'{relation}'=>$this->name)));
  8429. $this->_junctionTableName=$matches[1];
  8430. $this->_junctionForeignKeys=preg_split('/\s*,\s*/',$matches[2],-1,PREG_SPLIT_NO_EMPTY);
  8431. }
  8432. }
  8433. class CActiveRecordMetaData
  8434. {
  8435. public $tableSchema;
  8436. public $columns;
  8437. public $relations=array();
  8438. public $attributeDefaults=array();
  8439. private $_modelClassName;
  8440. public function __construct($model)
  8441. {
  8442. $this->_modelClassName=get_class($model);
  8443. $tableName=$model->tableName();
  8444. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  8445. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  8446. array('{class}'=>$this->_modelClassName,'{table}'=>$tableName)));
  8447. if(($modelPk=$model->primaryKey())!==null || $table->primaryKey===null)
  8448. {
  8449. $table->primaryKey=$modelPk;
  8450. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  8451. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  8452. elseif(is_array($table->primaryKey))
  8453. {
  8454. foreach($table->primaryKey as $name)
  8455. {
  8456. if(isset($table->columns[$name]))
  8457. $table->columns[$name]->isPrimaryKey=true;
  8458. }
  8459. }
  8460. }
  8461. $this->tableSchema=$table;
  8462. $this->columns=$table->columns;
  8463. foreach($table->columns as $name=>$column)
  8464. {
  8465. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  8466. $this->attributeDefaults[$name]=$column->defaultValue;
  8467. }
  8468. foreach($model->relations() as $name=>$config)
  8469. {
  8470. $this->addRelation($name,$config);
  8471. }
  8472. }
  8473. public function addRelation($name,$config)
  8474. {
  8475. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  8476. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  8477. else
  8478. throw new CDbException(Yii::t('yii','Active record "{class}" has an invalid configuration for relation "{relation}". It must specify the relation type, the related active record class and the foreign key.', array('{class}'=>$this->_modelClassName,'{relation}'=>$name)));
  8479. }
  8480. public function hasRelation($name)
  8481. {
  8482. return isset($this->relations[$name]);
  8483. }
  8484. public function removeRelation($name)
  8485. {
  8486. unset($this->relations[$name]);
  8487. }
  8488. }
  8489. class CDbConnection extends CApplicationComponent
  8490. {
  8491. public $connectionString;
  8492. public $username='';
  8493. public $password='';
  8494. public $schemaCachingDuration=0;
  8495. public $schemaCachingExclude=array();
  8496. public $schemaCacheID='cache';
  8497. public $queryCachingDuration=0;
  8498. public $queryCachingDependency;
  8499. public $queryCachingCount=0;
  8500. public $queryCacheID='cache';
  8501. public $autoConnect=true;
  8502. public $charset;
  8503. public $emulatePrepare;
  8504. public $enableParamLogging=false;
  8505. public $enableProfiling=false;
  8506. public $tablePrefix;
  8507. public $initSQLs;
  8508. public $driverMap=array(
  8509. 'cubrid'=>'CCubridSchema', // CUBRID
  8510. 'pgsql'=>'CPgsqlSchema', // PostgreSQL
  8511. 'mysqli'=>'CMysqlSchema', // MySQL
  8512. 'mysql'=>'CMysqlSchema', // MySQL,MariaDB
  8513. 'sqlite'=>'CSqliteSchema', // sqlite 3
  8514. 'sqlite2'=>'CSqliteSchema', // sqlite 2
  8515. 'mssql'=>'CMssqlSchema', // Mssql driver on windows hosts
  8516. 'dblib'=>'CMssqlSchema', // dblib drivers on linux (and maybe others os) hosts
  8517. 'sqlsrv'=>'CMssqlSchema', // Mssql
  8518. 'oci'=>'COciSchema', // Oracle driver
  8519. );
  8520. public $pdoClass = 'PDO';
  8521. private $_driverName;
  8522. private $_attributes=array();
  8523. private $_active=false;
  8524. private $_pdo;
  8525. private $_transaction;
  8526. private $_schema;
  8527. public function __construct($dsn='',$username='',$password='')
  8528. {
  8529. $this->connectionString=$dsn;
  8530. $this->username=$username;
  8531. $this->password=$password;
  8532. }
  8533. public function __sleep()
  8534. {
  8535. $this->close();
  8536. return array_keys(get_object_vars($this));
  8537. }
  8538. public static function getAvailableDrivers()
  8539. {
  8540. return PDO::getAvailableDrivers();
  8541. }
  8542. public function init()
  8543. {
  8544. parent::init();
  8545. if($this->autoConnect)
  8546. $this->setActive(true);
  8547. }
  8548. public function getActive()
  8549. {
  8550. return $this->_active;
  8551. }
  8552. public function setActive($value)
  8553. {
  8554. if($value!=$this->_active)
  8555. {
  8556. if($value)
  8557. $this->open();
  8558. else
  8559. $this->close();
  8560. }
  8561. }
  8562. public function cache($duration, $dependency=null, $queryCount=1)
  8563. {
  8564. $this->queryCachingDuration=$duration;
  8565. $this->queryCachingDependency=$dependency;
  8566. $this->queryCachingCount=$queryCount;
  8567. return $this;
  8568. }
  8569. protected function open()
  8570. {
  8571. if($this->_pdo===null)
  8572. {
  8573. if(empty($this->connectionString))
  8574. throw new CDbException('CDbConnection.connectionString cannot be empty.');
  8575. try
  8576. {
  8577. $this->_pdo=$this->createPdoInstance();
  8578. $this->initConnection($this->_pdo);
  8579. $this->_active=true;
  8580. }
  8581. catch(PDOException $e)
  8582. {
  8583. if(YII_DEBUG)
  8584. {
  8585. throw new CDbException('CDbConnection failed to open the DB connection: '.
  8586. $e->getMessage(),(int)$e->getCode(),$e->errorInfo);
  8587. }
  8588. else
  8589. {
  8590. Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
  8591. throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo);
  8592. }
  8593. }
  8594. }
  8595. }
  8596. protected function close()
  8597. {
  8598. $this->_pdo=null;
  8599. $this->_active=false;
  8600. $this->_schema=null;
  8601. }
  8602. protected function createPdoInstance()
  8603. {
  8604. $pdoClass=$this->pdoClass;
  8605. if(($driver=$this->getDriverName())!==null)
  8606. {
  8607. if($driver==='mssql' || $driver==='dblib')
  8608. $pdoClass='CMssqlPdoAdapter';
  8609. elseif($driver==='sqlsrv')
  8610. $pdoClass='CMssqlSqlsrvPdoAdapter';
  8611. }
  8612. if(!class_exists($pdoClass))
  8613. throw new CDbException(Yii::t('yii','CDbConnection is unable to find PDO class "{className}". Make sure PDO is installed correctly.',
  8614. array('{className}'=>$pdoClass)));
  8615. @$instance=new $pdoClass($this->connectionString,$this->username,$this->password,$this->_attributes);
  8616. if(!$instance)
  8617. throw new CDbException(Yii::t('yii','CDbConnection failed to open the DB connection.'));
  8618. return $instance;
  8619. }
  8620. protected function initConnection($pdo)
  8621. {
  8622. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  8623. if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))
  8624. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,$this->emulatePrepare);
  8625. if($this->charset!==null)
  8626. {
  8627. $driver=strtolower($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
  8628. if(in_array($driver,array('pgsql','mysql','mysqli')))
  8629. $pdo->exec('SET NAMES '.$pdo->quote($this->charset));
  8630. }
  8631. if($this->initSQLs!==null)
  8632. {
  8633. foreach($this->initSQLs as $sql)
  8634. $pdo->exec($sql);
  8635. }
  8636. }
  8637. public function getPdoInstance()
  8638. {
  8639. return $this->_pdo;
  8640. }
  8641. public function createCommand($query=null)
  8642. {
  8643. $this->setActive(true);
  8644. return new CDbCommand($this,$query);
  8645. }
  8646. public function getCurrentTransaction()
  8647. {
  8648. if($this->_transaction!==null)
  8649. {
  8650. if($this->_transaction->getActive())
  8651. return $this->_transaction;
  8652. }
  8653. return null;
  8654. }
  8655. public function beginTransaction()
  8656. {
  8657. $this->setActive(true);
  8658. $this->_pdo->beginTransaction();
  8659. return $this->_transaction=new CDbTransaction($this);
  8660. }
  8661. public function getSchema()
  8662. {
  8663. if($this->_schema!==null)
  8664. return $this->_schema;
  8665. else
  8666. {
  8667. $driver=$this->getDriverName();
  8668. if(isset($this->driverMap[$driver]))
  8669. return $this->_schema=Yii::createComponent($this->driverMap[$driver], $this);
  8670. else
  8671. throw new CDbException(Yii::t('yii','CDbConnection does not support reading schema for {driver} database.',
  8672. array('{driver}'=>$driver)));
  8673. }
  8674. }
  8675. public function getCommandBuilder()
  8676. {
  8677. return $this->getSchema()->getCommandBuilder();
  8678. }
  8679. public function getLastInsertID($sequenceName='')
  8680. {
  8681. $this->setActive(true);
  8682. return $this->_pdo->lastInsertId($sequenceName);
  8683. }
  8684. public function quoteValue($str)
  8685. {
  8686. if(is_int($str) || is_float($str))
  8687. return $str;
  8688. $this->setActive(true);
  8689. if(($value=$this->_pdo->quote($str))!==false)
  8690. return $value;
  8691. else // the driver doesn't support quote (e.g. oci)
  8692. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  8693. }
  8694. public function quoteTableName($name)
  8695. {
  8696. return $this->getSchema()->quoteTableName($name);
  8697. }
  8698. public function quoteColumnName($name)
  8699. {
  8700. return $this->getSchema()->quoteColumnName($name);
  8701. }
  8702. public function getPdoType($type)
  8703. {
  8704. static $map=array
  8705. (
  8706. 'boolean'=>PDO::PARAM_BOOL,
  8707. 'integer'=>PDO::PARAM_INT,
  8708. 'string'=>PDO::PARAM_STR,
  8709. 'resource'=>PDO::PARAM_LOB,
  8710. 'NULL'=>PDO::PARAM_NULL,
  8711. );
  8712. return isset($map[$type]) ? $map[$type] : PDO::PARAM_STR;
  8713. }
  8714. public function getColumnCase()
  8715. {
  8716. return $this->getAttribute(PDO::ATTR_CASE);
  8717. }
  8718. public function setColumnCase($value)
  8719. {
  8720. $this->setAttribute(PDO::ATTR_CASE,$value);
  8721. }
  8722. public function getNullConversion()
  8723. {
  8724. return $this->getAttribute(PDO::ATTR_ORACLE_NULLS);
  8725. }
  8726. public function setNullConversion($value)
  8727. {
  8728. $this->setAttribute(PDO::ATTR_ORACLE_NULLS,$value);
  8729. }
  8730. public function getAutoCommit()
  8731. {
  8732. return $this->getAttribute(PDO::ATTR_AUTOCOMMIT);
  8733. }
  8734. public function setAutoCommit($value)
  8735. {
  8736. $this->setAttribute(PDO::ATTR_AUTOCOMMIT,$value);
  8737. }
  8738. public function getPersistent()
  8739. {
  8740. return $this->getAttribute(PDO::ATTR_PERSISTENT);
  8741. }
  8742. public function setPersistent($value)
  8743. {
  8744. return $this->setAttribute(PDO::ATTR_PERSISTENT,$value);
  8745. }
  8746. public function getDriverName()
  8747. {
  8748. if($this->_driverName!==null)
  8749. return $this->_driverName;
  8750. elseif(($pos=strpos($this->connectionString,':'))!==false)
  8751. return $this->_driverName=strtolower(substr($this->connectionString,0,$pos));
  8752. //return $this->getAttribute(PDO::ATTR_DRIVER_NAME);
  8753. }
  8754. public function setDriverName($driverName)
  8755. {
  8756. $this->_driverName=strtolower($driverName);
  8757. }
  8758. public function getClientVersion()
  8759. {
  8760. return $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
  8761. }
  8762. public function getConnectionStatus()
  8763. {
  8764. return $this->getAttribute(PDO::ATTR_CONNECTION_STATUS);
  8765. }
  8766. public function getPrefetch()
  8767. {
  8768. return $this->getAttribute(PDO::ATTR_PREFETCH);
  8769. }
  8770. public function getServerInfo()
  8771. {
  8772. return $this->getAttribute(PDO::ATTR_SERVER_INFO);
  8773. }
  8774. public function getServerVersion()
  8775. {
  8776. return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
  8777. }
  8778. public function getTimeout()
  8779. {
  8780. return $this->getAttribute(PDO::ATTR_TIMEOUT);
  8781. }
  8782. public function getAttribute($name)
  8783. {
  8784. $this->setActive(true);
  8785. return $this->_pdo->getAttribute($name);
  8786. }
  8787. public function setAttribute($name,$value)
  8788. {
  8789. if($this->_pdo instanceof PDO)
  8790. $this->_pdo->setAttribute($name,$value);
  8791. else
  8792. $this->_attributes[$name]=$value;
  8793. }
  8794. public function getAttributes()
  8795. {
  8796. return $this->_attributes;
  8797. }
  8798. public function setAttributes($values)
  8799. {
  8800. foreach($values as $name=>$value)
  8801. $this->_attributes[$name]=$value;
  8802. }
  8803. public function getStats()
  8804. {
  8805. $logger=Yii::getLogger();
  8806. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.query');
  8807. $count=count($timings);
  8808. $time=array_sum($timings);
  8809. $timings=$logger->getProfilingResults(null,'system.db.CDbCommand.execute');
  8810. $count+=count($timings);
  8811. $time+=array_sum($timings);
  8812. return array($count,$time);
  8813. }
  8814. }
  8815. abstract class CDbSchema extends CComponent
  8816. {
  8817. public $columnTypes=array();
  8818. private $_tableNames=array();
  8819. private $_tables=array();
  8820. private $_connection;
  8821. private $_builder;
  8822. private $_cacheExclude=array();
  8823. abstract protected function loadTable($name);
  8824. public function __construct($conn)
  8825. {
  8826. $this->_connection=$conn;
  8827. foreach($conn->schemaCachingExclude as $name)
  8828. $this->_cacheExclude[$name]=true;
  8829. }
  8830. public function getDbConnection()
  8831. {
  8832. return $this->_connection;
  8833. }
  8834. public function getTable($name,$refresh=false)
  8835. {
  8836. if($refresh===false && isset($this->_tables[$name]))
  8837. return $this->_tables[$name];
  8838. else
  8839. {
  8840. if($this->_connection->tablePrefix!==null && strpos($name,'{{')!==false)
  8841. $realName=preg_replace('/\{\{(.*?)\}\}/',$this->_connection->tablePrefix.'$1',$name);
  8842. else
  8843. $realName=$name;
  8844. // temporarily disable query caching
  8845. if($this->_connection->queryCachingDuration>0)
  8846. {
  8847. $qcDuration=$this->_connection->queryCachingDuration;
  8848. $this->_connection->queryCachingDuration=0;
  8849. }
  8850. if(!isset($this->_cacheExclude[$name]) && ($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8851. {
  8852. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8853. $table=$cache->get($key);
  8854. if($refresh===true || $table===false)
  8855. {
  8856. $table=$this->loadTable($realName);
  8857. if($table!==null)
  8858. $cache->set($key,$table,$duration);
  8859. }
  8860. $this->_tables[$name]=$table;
  8861. }
  8862. else
  8863. $this->_tables[$name]=$table=$this->loadTable($realName);
  8864. if(isset($qcDuration)) // re-enable query caching
  8865. $this->_connection->queryCachingDuration=$qcDuration;
  8866. return $table;
  8867. }
  8868. }
  8869. public function getTables($schema='')
  8870. {
  8871. $tables=array();
  8872. foreach($this->getTableNames($schema) as $name)
  8873. {
  8874. if(($table=$this->getTable($name))!==null)
  8875. $tables[$name]=$table;
  8876. }
  8877. return $tables;
  8878. }
  8879. public function getTableNames($schema='')
  8880. {
  8881. if(!isset($this->_tableNames[$schema]))
  8882. $this->_tableNames[$schema]=$this->findTableNames($schema);
  8883. return $this->_tableNames[$schema];
  8884. }
  8885. public function getCommandBuilder()
  8886. {
  8887. if($this->_builder!==null)
  8888. return $this->_builder;
  8889. else
  8890. return $this->_builder=$this->createCommandBuilder();
  8891. }
  8892. public function refresh()
  8893. {
  8894. if(($duration=$this->_connection->schemaCachingDuration)>0 && $this->_connection->schemaCacheID!==false && ($cache=Yii::app()->getComponent($this->_connection->schemaCacheID))!==null)
  8895. {
  8896. foreach(array_keys($this->_tables) as $name)
  8897. {
  8898. if(!isset($this->_cacheExclude[$name]))
  8899. {
  8900. $key='yii:dbschema'.$this->_connection->connectionString.':'.$this->_connection->username.':'.$name;
  8901. $cache->delete($key);
  8902. }
  8903. }
  8904. }
  8905. $this->_tables=array();
  8906. $this->_tableNames=array();
  8907. $this->_builder=null;
  8908. }
  8909. public function quoteTableName($name)
  8910. {
  8911. if(strpos($name,'.')===false)
  8912. return $this->quoteSimpleTableName($name);
  8913. $parts=explode('.',$name);
  8914. foreach($parts as $i=>$part)
  8915. $parts[$i]=$this->quoteSimpleTableName($part);
  8916. return implode('.',$parts);
  8917. }
  8918. public function quoteSimpleTableName($name)
  8919. {
  8920. return "'".$name."'";
  8921. }
  8922. public function quoteColumnName($name)
  8923. {
  8924. if(($pos=strrpos($name,'.'))!==false)
  8925. {
  8926. $prefix=$this->quoteTableName(substr($name,0,$pos)).'.';
  8927. $name=substr($name,$pos+1);
  8928. }
  8929. else
  8930. $prefix='';
  8931. return $prefix . ($name==='*' ? $name : $this->quoteSimpleColumnName($name));
  8932. }
  8933. public function quoteSimpleColumnName($name)
  8934. {
  8935. return '"'.$name.'"';
  8936. }
  8937. public function compareTableNames($name1,$name2)
  8938. {
  8939. $name1=str_replace(array('"','`',"'"),'',$name1);
  8940. $name2=str_replace(array('"','`',"'"),'',$name2);
  8941. if(($pos=strrpos($name1,'.'))!==false)
  8942. $name1=substr($name1,$pos+1);
  8943. if(($pos=strrpos($name2,'.'))!==false)
  8944. $name2=substr($name2,$pos+1);
  8945. if($this->_connection->tablePrefix!==null)
  8946. {
  8947. if(strpos($name1,'{')!==false)
  8948. $name1=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name1);
  8949. if(strpos($name2,'{')!==false)
  8950. $name2=$this->_connection->tablePrefix.str_replace(array('{','}'),'',$name2);
  8951. }
  8952. return $name1===$name2;
  8953. }
  8954. public function resetSequence($table,$value=null)
  8955. {
  8956. }
  8957. public function checkIntegrity($check=true,$schema='')
  8958. {
  8959. }
  8960. protected function createCommandBuilder()
  8961. {
  8962. return new CDbCommandBuilder($this);
  8963. }
  8964. protected function findTableNames($schema='')
  8965. {
  8966. throw new CDbException(Yii::t('yii','{class} does not support fetching all table names.',
  8967. array('{class}'=>get_class($this))));
  8968. }
  8969. public function getColumnType($type)
  8970. {
  8971. if(isset($this->columnTypes[$type]))
  8972. return $this->columnTypes[$type];
  8973. elseif(($pos=strpos($type,' '))!==false)
  8974. {
  8975. $t=substr($type,0,$pos);
  8976. return (isset($this->columnTypes[$t]) ? $this->columnTypes[$t] : $t).substr($type,$pos);
  8977. }
  8978. else
  8979. return $type;
  8980. }
  8981. public function createTable($table,$columns,$options=null)
  8982. {
  8983. $cols=array();
  8984. foreach($columns as $name=>$type)
  8985. {
  8986. if(is_string($name))
  8987. $cols[]="\t".$this->quoteColumnName($name).' '.$this->getColumnType($type);
  8988. else
  8989. $cols[]="\t".$type;
  8990. }
  8991. $sql="CREATE TABLE ".$this->quoteTableName($table)." (\n".implode(",\n",$cols)."\n)";
  8992. return $options===null ? $sql : $sql.' '.$options;
  8993. }
  8994. public function renameTable($table,$newName)
  8995. {
  8996. return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
  8997. }
  8998. public function dropTable($table)
  8999. {
  9000. return "DROP TABLE ".$this->quoteTableName($table);
  9001. }
  9002. public function truncateTable($table)
  9003. {
  9004. return "TRUNCATE TABLE ".$this->quoteTableName($table);
  9005. }
  9006. public function addColumn($table,$column,$type)
  9007. {
  9008. return 'ALTER TABLE ' . $this->quoteTableName($table)
  9009. . ' ADD ' . $this->quoteColumnName($column) . ' '
  9010. . $this->getColumnType($type);
  9011. }
  9012. public function dropColumn($table,$column)
  9013. {
  9014. return "ALTER TABLE ".$this->quoteTableName($table)
  9015. ." DROP COLUMN ".$this->quoteColumnName($column);
  9016. }
  9017. public function renameColumn($table,$name,$newName)
  9018. {
  9019. return "ALTER TABLE ".$this->quoteTableName($table)
  9020. . " RENAME COLUMN ".$this->quoteColumnName($name)
  9021. . " TO ".$this->quoteColumnName($newName);
  9022. }
  9023. public function alterColumn($table,$column,$type)
  9024. {
  9025. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
  9026. . $this->quoteColumnName($column) . ' '
  9027. . $this->quoteColumnName($column) . ' '
  9028. . $this->getColumnType($type);
  9029. }
  9030. public function addForeignKey($name,$table,$columns,$refTable,$refColumns,$delete=null,$update=null)
  9031. {
  9032. if(is_string($columns))
  9033. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9034. foreach($columns as $i=>$col)
  9035. $columns[$i]=$this->quoteColumnName($col);
  9036. if(is_string($refColumns))
  9037. $refColumns=preg_split('/\s*,\s*/',$refColumns,-1,PREG_SPLIT_NO_EMPTY);
  9038. foreach($refColumns as $i=>$col)
  9039. $refColumns[$i]=$this->quoteColumnName($col);
  9040. $sql='ALTER TABLE '.$this->quoteTableName($table)
  9041. .' ADD CONSTRAINT '.$this->quoteColumnName($name)
  9042. .' FOREIGN KEY ('.implode(', ',$columns).')'
  9043. .' REFERENCES '.$this->quoteTableName($refTable)
  9044. .' ('.implode(', ',$refColumns).')';
  9045. if($delete!==null)
  9046. $sql.=' ON DELETE '.$delete;
  9047. if($update!==null)
  9048. $sql.=' ON UPDATE '.$update;
  9049. return $sql;
  9050. }
  9051. public function dropForeignKey($name,$table)
  9052. {
  9053. return 'ALTER TABLE '.$this->quoteTableName($table)
  9054. .' DROP CONSTRAINT '.$this->quoteColumnName($name);
  9055. }
  9056. public function createIndex($name,$table,$columns,$unique=false)
  9057. {
  9058. $cols=array();
  9059. if(is_string($columns))
  9060. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9061. foreach($columns as $col)
  9062. {
  9063. if(strpos($col,'(')!==false)
  9064. $cols[]=$col;
  9065. else
  9066. $cols[]=$this->quoteColumnName($col);
  9067. }
  9068. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  9069. . $this->quoteTableName($name).' ON '
  9070. . $this->quoteTableName($table).' ('.implode(', ',$cols).')';
  9071. }
  9072. public function dropIndex($name,$table)
  9073. {
  9074. return 'DROP INDEX '.$this->quoteTableName($name).' ON '.$this->quoteTableName($table);
  9075. }
  9076. public function addPrimaryKey($name,$table,$columns)
  9077. {
  9078. if(is_string($columns))
  9079. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  9080. foreach($columns as $i=>$col)
  9081. $columns[$i]=$this->quoteColumnName($col);
  9082. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' ADD CONSTRAINT '
  9083. . $this->quoteColumnName($name) . ' PRIMARY KEY ('
  9084. . implode(', ',$columns). ' )';
  9085. }
  9086. public function dropPrimaryKey($name,$table)
  9087. {
  9088. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' DROP CONSTRAINT '
  9089. . $this->quoteColumnName($name);
  9090. }
  9091. }
  9092. class CSqliteSchema extends CDbSchema
  9093. {
  9094. public $columnTypes=array(
  9095. 'pk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  9096. 'bigpk' => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  9097. 'string' => 'varchar(255)',
  9098. 'text' => 'text',
  9099. 'integer' => 'integer',
  9100. 'bigint' => 'integer',
  9101. 'float' => 'float',
  9102. 'decimal' => 'decimal',
  9103. 'datetime' => 'datetime',
  9104. 'timestamp' => 'timestamp',
  9105. 'time' => 'time',
  9106. 'date' => 'date',
  9107. 'binary' => 'blob',
  9108. 'boolean' => 'tinyint(1)',
  9109. 'money' => 'decimal(19,4)',
  9110. );
  9111. public function resetSequence($table,$value=null)
  9112. {
  9113. if($table->sequenceName===null)
  9114. return;
  9115. if($value!==null)
  9116. $value=(int)($value)-1;
  9117. else
  9118. $value=(int)$this->getDbConnection()
  9119. ->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")
  9120. ->queryScalar();
  9121. try
  9122. {
  9123. // it's possible that 'sqlite_sequence' does not exist
  9124. $this->getDbConnection()
  9125. ->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")
  9126. ->execute();
  9127. }
  9128. catch(Exception $e)
  9129. {
  9130. }
  9131. }
  9132. public function checkIntegrity($check=true,$schema='')
  9133. {
  9134. $this->getDbConnection()->createCommand('PRAGMA foreign_keys='.(int)$check)->execute();
  9135. }
  9136. protected function findTableNames($schema='')
  9137. {
  9138. $sql="SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence'";
  9139. return $this->getDbConnection()->createCommand($sql)->queryColumn();
  9140. }
  9141. protected function createCommandBuilder()
  9142. {
  9143. return new CSqliteCommandBuilder($this);
  9144. }
  9145. protected function loadTable($name)
  9146. {
  9147. $table=new CDbTableSchema;
  9148. $table->name=$name;
  9149. $table->rawName=$this->quoteTableName($name);
  9150. if($this->findColumns($table))
  9151. {
  9152. $this->findConstraints($table);
  9153. return $table;
  9154. }
  9155. else
  9156. return null;
  9157. }
  9158. protected function findColumns($table)
  9159. {
  9160. $sql="PRAGMA table_info({$table->rawName})";
  9161. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  9162. if(empty($columns))
  9163. return false;
  9164. foreach($columns as $column)
  9165. {
  9166. $c=$this->createColumn($column);
  9167. $table->columns[$c->name]=$c;
  9168. if($c->isPrimaryKey)
  9169. {
  9170. if($table->primaryKey===null)
  9171. $table->primaryKey=$c->name;
  9172. elseif(is_string($table->primaryKey))
  9173. $table->primaryKey=array($table->primaryKey,$c->name);
  9174. else
  9175. $table->primaryKey[]=$c->name;
  9176. }
  9177. }
  9178. if(is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType,'int',3))
  9179. {
  9180. $table->sequenceName='';
  9181. $table->columns[$table->primaryKey]->autoIncrement=true;
  9182. }
  9183. return true;
  9184. }
  9185. protected function findConstraints($table)
  9186. {
  9187. $foreignKeys=array();
  9188. $sql="PRAGMA foreign_key_list({$table->rawName})";
  9189. $keys=$this->getDbConnection()->createCommand($sql)->queryAll();
  9190. foreach($keys as $key)
  9191. {
  9192. $column=$table->columns[$key['from']];
  9193. $column->isForeignKey=true;
  9194. $foreignKeys[$key['from']]=array($key['table'],$key['to']);
  9195. }
  9196. $table->foreignKeys=$foreignKeys;
  9197. }
  9198. protected function createColumn($column)
  9199. {
  9200. $c=new CSqliteColumnSchema;
  9201. $c->name=$column['name'];
  9202. $c->rawName=$this->quoteColumnName($c->name);
  9203. $c->allowNull=!$column['notnull'];
  9204. $c->isPrimaryKey=$column['pk']!=0;
  9205. $c->isForeignKey=false;
  9206. $c->comment=null; // SQLite does not support column comments at all
  9207. $c->init(strtolower($column['type']),$column['dflt_value']);
  9208. return $c;
  9209. }
  9210. public function renameTable($table, $newName)
  9211. {
  9212. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' RENAME TO ' . $this->quoteTableName($newName);
  9213. }
  9214. public function truncateTable($table)
  9215. {
  9216. return "DELETE FROM ".$this->quoteTableName($table);
  9217. }
  9218. public function dropColumn($table, $column)
  9219. {
  9220. throw new CDbException(Yii::t('yii', 'Dropping DB column is not supported by SQLite.'));
  9221. }
  9222. public function renameColumn($table, $name, $newName)
  9223. {
  9224. throw new CDbException(Yii::t('yii', 'Renaming a DB column is not supported by SQLite.'));
  9225. }
  9226. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9227. {
  9228. throw new CDbException(Yii::t('yii', 'Adding a foreign key constraint to an existing table is not supported by SQLite.'));
  9229. }
  9230. public function dropForeignKey($name, $table)
  9231. {
  9232. throw new CDbException(Yii::t('yii', 'Dropping a foreign key constraint is not supported by SQLite.'));
  9233. }
  9234. public function alterColumn($table, $column, $type)
  9235. {
  9236. throw new CDbException(Yii::t('yii', 'Altering a DB column is not supported by SQLite.'));
  9237. }
  9238. public function dropIndex($name, $table)
  9239. {
  9240. return 'DROP INDEX '.$this->quoteTableName($name);
  9241. }
  9242. public function addPrimaryKey($name,$table,$columns)
  9243. {
  9244. throw new CDbException(Yii::t('yii', 'Adding a primary key after table has been created is not supported by SQLite.'));
  9245. }
  9246. public function dropPrimaryKey($name,$table)
  9247. {
  9248. throw new CDbException(Yii::t('yii', 'Removing a primary key after table has been created is not supported by SQLite.'));
  9249. }
  9250. }
  9251. class CDbTableSchema extends CComponent
  9252. {
  9253. public $name;
  9254. public $rawName;
  9255. public $primaryKey;
  9256. public $sequenceName;
  9257. public $foreignKeys=array();
  9258. public $columns=array();
  9259. public function getColumn($name)
  9260. {
  9261. return isset($this->columns[$name]) ? $this->columns[$name] : null;
  9262. }
  9263. public function getColumnNames()
  9264. {
  9265. return array_keys($this->columns);
  9266. }
  9267. }
  9268. class CDbCommand extends CComponent
  9269. {
  9270. public $params=array();
  9271. private $_connection;
  9272. private $_text;
  9273. private $_statement;
  9274. private $_paramLog=array();
  9275. private $_query;
  9276. private $_fetchMode = array(PDO::FETCH_ASSOC);
  9277. public function __construct(CDbConnection $connection,$query=null)
  9278. {
  9279. $this->_connection=$connection;
  9280. if(is_array($query))
  9281. {
  9282. foreach($query as $name=>$value)
  9283. $this->$name=$value;
  9284. }
  9285. else
  9286. $this->setText($query);
  9287. }
  9288. public function __sleep()
  9289. {
  9290. $this->_statement=null;
  9291. return array_keys(get_object_vars($this));
  9292. }
  9293. public function setFetchMode($mode)
  9294. {
  9295. $params=func_get_args();
  9296. $this->_fetchMode = $params;
  9297. return $this;
  9298. }
  9299. public function reset()
  9300. {
  9301. $this->_text=null;
  9302. $this->_query=null;
  9303. $this->_statement=null;
  9304. $this->_paramLog=array();
  9305. $this->params=array();
  9306. return $this;
  9307. }
  9308. public function getText()
  9309. {
  9310. if($this->_text=='' && !empty($this->_query))
  9311. $this->setText($this->buildQuery($this->_query));
  9312. return $this->_text;
  9313. }
  9314. public function setText($value)
  9315. {
  9316. if($this->_connection->tablePrefix!==null && $value!='')
  9317. $this->_text=preg_replace('/{{(.*?)}}/',$this->_connection->tablePrefix.'\1',$value);
  9318. else
  9319. $this->_text=$value;
  9320. $this->cancel();
  9321. return $this;
  9322. }
  9323. public function getConnection()
  9324. {
  9325. return $this->_connection;
  9326. }
  9327. public function getPdoStatement()
  9328. {
  9329. return $this->_statement;
  9330. }
  9331. public function prepare()
  9332. {
  9333. if($this->_statement==null)
  9334. {
  9335. try
  9336. {
  9337. $this->_statement=$this->getConnection()->getPdoInstance()->prepare($this->getText());
  9338. $this->_paramLog=array();
  9339. }
  9340. catch(Exception $e)
  9341. {
  9342. Yii::log('Error in preparing SQL: '.$this->getText(),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9343. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9344. throw new CDbException(Yii::t('yii','CDbCommand failed to prepare the SQL statement: {error}',
  9345. array('{error}'=>$e->getMessage())),(int)$e->getCode(),$errorInfo);
  9346. }
  9347. }
  9348. }
  9349. public function cancel()
  9350. {
  9351. $this->_statement=null;
  9352. }
  9353. public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
  9354. {
  9355. $this->prepare();
  9356. if($dataType===null)
  9357. $this->_statement->bindParam($name,$value,$this->_connection->getPdoType(gettype($value)));
  9358. elseif($length===null)
  9359. $this->_statement->bindParam($name,$value,$dataType);
  9360. elseif($driverOptions===null)
  9361. $this->_statement->bindParam($name,$value,$dataType,$length);
  9362. else
  9363. $this->_statement->bindParam($name,$value,$dataType,$length,$driverOptions);
  9364. $this->_paramLog[$name]=&$value;
  9365. return $this;
  9366. }
  9367. public function bindValue($name, $value, $dataType=null)
  9368. {
  9369. $this->prepare();
  9370. if($dataType===null)
  9371. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9372. else
  9373. $this->_statement->bindValue($name,$value,$dataType);
  9374. $this->_paramLog[$name]=$value;
  9375. return $this;
  9376. }
  9377. public function bindValues($values)
  9378. {
  9379. $this->prepare();
  9380. foreach($values as $name=>$value)
  9381. {
  9382. $this->_statement->bindValue($name,$value,$this->_connection->getPdoType(gettype($value)));
  9383. $this->_paramLog[$name]=$value;
  9384. }
  9385. return $this;
  9386. }
  9387. public function execute($params=array())
  9388. {
  9389. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9390. {
  9391. $p=array();
  9392. foreach($pars as $name=>$value)
  9393. $p[$name]=$name.'='.var_export($value,true);
  9394. $par='. Bound with ' .implode(', ',$p);
  9395. }
  9396. else
  9397. $par='';
  9398. try
  9399. {
  9400. if($this->_connection->enableProfiling)
  9401. Yii::beginProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9402. $this->prepare();
  9403. if($params===array())
  9404. $this->_statement->execute();
  9405. else
  9406. $this->_statement->execute($params);
  9407. $n=$this->_statement->rowCount();
  9408. if($this->_connection->enableProfiling)
  9409. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9410. return $n;
  9411. }
  9412. catch(Exception $e)
  9413. {
  9414. if($this->_connection->enableProfiling)
  9415. Yii::endProfile('system.db.CDbCommand.execute('.$this->getText().$par.')','system.db.CDbCommand.execute');
  9416. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9417. $message=$e->getMessage();
  9418. Yii::log(Yii::t('yii','CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.',
  9419. array('{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9420. if(YII_DEBUG)
  9421. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9422. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9423. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9424. }
  9425. }
  9426. public function query($params=array())
  9427. {
  9428. return $this->queryInternal('',0,$params);
  9429. }
  9430. public function queryAll($fetchAssociative=true,$params=array())
  9431. {
  9432. return $this->queryInternal('fetchAll',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9433. }
  9434. public function queryRow($fetchAssociative=true,$params=array())
  9435. {
  9436. return $this->queryInternal('fetch',$fetchAssociative ? $this->_fetchMode : PDO::FETCH_NUM, $params);
  9437. }
  9438. public function queryScalar($params=array())
  9439. {
  9440. $result=$this->queryInternal('fetchColumn',0,$params);
  9441. if(is_resource($result) && get_resource_type($result)==='stream')
  9442. return stream_get_contents($result);
  9443. else
  9444. return $result;
  9445. }
  9446. public function queryColumn($params=array())
  9447. {
  9448. return $this->queryInternal('fetchAll',array(PDO::FETCH_COLUMN, 0),$params);
  9449. }
  9450. private function queryInternal($method,$mode,$params=array())
  9451. {
  9452. $params=array_merge($this->params,$params);
  9453. if($this->_connection->enableParamLogging && ($pars=array_merge($this->_paramLog,$params))!==array())
  9454. {
  9455. $p=array();
  9456. foreach($pars as $name=>$value)
  9457. $p[$name]=$name.'='.var_export($value,true);
  9458. $par='. Bound with '.implode(', ',$p);
  9459. }
  9460. else
  9461. $par='';
  9462. if($this->_connection->queryCachingCount>0 && $method!==''
  9463. && $this->_connection->queryCachingDuration>0
  9464. && $this->_connection->queryCacheID!==false
  9465. && ($cache=Yii::app()->getComponent($this->_connection->queryCacheID))!==null)
  9466. {
  9467. $this->_connection->queryCachingCount--;
  9468. $cacheKey='yii:dbquery'.':'.$method.':'.$this->_connection->connectionString.':'.$this->_connection->username;
  9469. $cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
  9470. if(($result=$cache->get($cacheKey))!==false)
  9471. {
  9472. return $result[0];
  9473. }
  9474. }
  9475. try
  9476. {
  9477. if($this->_connection->enableProfiling)
  9478. Yii::beginProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9479. $this->prepare();
  9480. if($params===array())
  9481. $this->_statement->execute();
  9482. else
  9483. $this->_statement->execute($params);
  9484. if($method==='')
  9485. $result=new CDbDataReader($this);
  9486. else
  9487. {
  9488. $mode=(array)$mode;
  9489. call_user_func_array(array($this->_statement, 'setFetchMode'), $mode);
  9490. $result=$this->_statement->$method();
  9491. $this->_statement->closeCursor();
  9492. }
  9493. if($this->_connection->enableProfiling)
  9494. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9495. if(isset($cache,$cacheKey))
  9496. $cache->set($cacheKey, array($result), $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);
  9497. return $result;
  9498. }
  9499. catch(Exception $e)
  9500. {
  9501. if($this->_connection->enableProfiling)
  9502. Yii::endProfile('system.db.CDbCommand.query('.$this->getText().$par.')','system.db.CDbCommand.query');
  9503. $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
  9504. $message=$e->getMessage();
  9505. Yii::log(Yii::t('yii','CDbCommand::{method}() failed: {error}. The SQL statement executed was: {sql}.',
  9506. array('{method}'=>$method, '{error}'=>$message, '{sql}'=>$this->getText().$par)),CLogger::LEVEL_ERROR,'system.db.CDbCommand');
  9507. if(YII_DEBUG)
  9508. $message.='. The SQL statement executed was: '.$this->getText().$par;
  9509. throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
  9510. array('{error}'=>$message)),(int)$e->getCode(),$errorInfo);
  9511. }
  9512. }
  9513. public function buildQuery($query)
  9514. {
  9515. $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
  9516. $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');
  9517. if(!empty($query['from']))
  9518. $sql.="\nFROM ".$query['from'];
  9519. if(!empty($query['join']))
  9520. $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);
  9521. if(!empty($query['where']))
  9522. $sql.="\nWHERE ".$query['where'];
  9523. if(!empty($query['group']))
  9524. $sql.="\nGROUP BY ".$query['group'];
  9525. if(!empty($query['having']))
  9526. $sql.="\nHAVING ".$query['having'];
  9527. if(!empty($query['union']))
  9528. $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';
  9529. if(!empty($query['order']))
  9530. $sql.="\nORDER BY ".$query['order'];
  9531. $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
  9532. $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
  9533. if($limit>=0 || $offset>0)
  9534. $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);
  9535. return $sql;
  9536. }
  9537. public function select($columns='*', $option='')
  9538. {
  9539. if(is_string($columns) && strpos($columns,'(')!==false)
  9540. $this->_query['select']=$columns;
  9541. else
  9542. {
  9543. if(!is_array($columns))
  9544. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9545. foreach($columns as $i=>$column)
  9546. {
  9547. if(is_object($column))
  9548. $columns[$i]=(string)$column;
  9549. elseif(strpos($column,'(')===false)
  9550. {
  9551. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
  9552. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
  9553. else
  9554. $columns[$i]=$this->_connection->quoteColumnName($column);
  9555. }
  9556. }
  9557. $this->_query['select']=implode(', ',$columns);
  9558. }
  9559. if($option!='')
  9560. $this->_query['select']=$option.' '.$this->_query['select'];
  9561. return $this;
  9562. }
  9563. public function getSelect()
  9564. {
  9565. return isset($this->_query['select']) ? $this->_query['select'] : '';
  9566. }
  9567. public function setSelect($value)
  9568. {
  9569. $this->select($value);
  9570. }
  9571. public function selectDistinct($columns='*')
  9572. {
  9573. $this->_query['distinct']=true;
  9574. return $this->select($columns);
  9575. }
  9576. public function getDistinct()
  9577. {
  9578. return isset($this->_query['distinct']) ? $this->_query['distinct'] : false;
  9579. }
  9580. public function setDistinct($value)
  9581. {
  9582. $this->_query['distinct']=$value;
  9583. }
  9584. public function from($tables)
  9585. {
  9586. if(is_string($tables) && strpos($tables,'(')!==false)
  9587. $this->_query['from']=$tables;
  9588. else
  9589. {
  9590. if(!is_array($tables))
  9591. $tables=preg_split('/\s*,\s*/',trim($tables),-1,PREG_SPLIT_NO_EMPTY);
  9592. foreach($tables as $i=>$table)
  9593. {
  9594. if(strpos($table,'(')===false)
  9595. {
  9596. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9597. $tables[$i]=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9598. else
  9599. $tables[$i]=$this->_connection->quoteTableName($table);
  9600. }
  9601. }
  9602. $this->_query['from']=implode(', ',$tables);
  9603. }
  9604. return $this;
  9605. }
  9606. public function getFrom()
  9607. {
  9608. return isset($this->_query['from']) ? $this->_query['from'] : '';
  9609. }
  9610. public function setFrom($value)
  9611. {
  9612. $this->from($value);
  9613. }
  9614. public function where($conditions, $params=array())
  9615. {
  9616. $this->_query['where']=$this->processConditions($conditions);
  9617. foreach($params as $name=>$value)
  9618. $this->params[$name]=$value;
  9619. return $this;
  9620. }
  9621. public function andWhere($conditions,$params=array())
  9622. {
  9623. if(isset($this->_query['where']))
  9624. $this->_query['where']=$this->processConditions(array('AND',$this->_query['where'],$conditions));
  9625. else
  9626. $this->_query['where']=$this->processConditions($conditions);
  9627. foreach($params as $name=>$value)
  9628. $this->params[$name]=$value;
  9629. return $this;
  9630. }
  9631. public function orWhere($conditions,$params=array())
  9632. {
  9633. if(isset($this->_query['where']))
  9634. $this->_query['where']=$this->processConditions(array('OR',$this->_query['where'],$conditions));
  9635. else
  9636. $this->_query['where']=$this->processConditions($conditions);
  9637. foreach($params as $name=>$value)
  9638. $this->params[$name]=$value;
  9639. return $this;
  9640. }
  9641. public function getWhere()
  9642. {
  9643. return isset($this->_query['where']) ? $this->_query['where'] : '';
  9644. }
  9645. public function setWhere($value)
  9646. {
  9647. $this->where($value);
  9648. }
  9649. public function join($table, $conditions, $params=array())
  9650. {
  9651. return $this->joinInternal('join', $table, $conditions, $params);
  9652. }
  9653. public function getJoin()
  9654. {
  9655. return isset($this->_query['join']) ? $this->_query['join'] : '';
  9656. }
  9657. public function setJoin($value)
  9658. {
  9659. $this->_query['join']=$value;
  9660. }
  9661. public function leftJoin($table, $conditions, $params=array())
  9662. {
  9663. return $this->joinInternal('left join', $table, $conditions, $params);
  9664. }
  9665. public function rightJoin($table, $conditions, $params=array())
  9666. {
  9667. return $this->joinInternal('right join', $table, $conditions, $params);
  9668. }
  9669. public function crossJoin($table)
  9670. {
  9671. return $this->joinInternal('cross join', $table);
  9672. }
  9673. public function naturalJoin($table)
  9674. {
  9675. return $this->joinInternal('natural join', $table);
  9676. }
  9677. public function naturalLeftJoin($table)
  9678. {
  9679. return $this->joinInternal('natural left join', $table);
  9680. }
  9681. public function naturalRightJoin($table)
  9682. {
  9683. return $this->joinInternal('natural right join', $table);
  9684. }
  9685. public function group($columns)
  9686. {
  9687. if(is_string($columns) && strpos($columns,'(')!==false)
  9688. $this->_query['group']=$columns;
  9689. else
  9690. {
  9691. if(!is_array($columns))
  9692. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9693. foreach($columns as $i=>$column)
  9694. {
  9695. if(is_object($column))
  9696. $columns[$i]=(string)$column;
  9697. elseif(strpos($column,'(')===false)
  9698. $columns[$i]=$this->_connection->quoteColumnName($column);
  9699. }
  9700. $this->_query['group']=implode(', ',$columns);
  9701. }
  9702. return $this;
  9703. }
  9704. public function getGroup()
  9705. {
  9706. return isset($this->_query['group']) ? $this->_query['group'] : '';
  9707. }
  9708. public function setGroup($value)
  9709. {
  9710. $this->group($value);
  9711. }
  9712. public function having($conditions, $params=array())
  9713. {
  9714. $this->_query['having']=$this->processConditions($conditions);
  9715. foreach($params as $name=>$value)
  9716. $this->params[$name]=$value;
  9717. return $this;
  9718. }
  9719. public function getHaving()
  9720. {
  9721. return isset($this->_query['having']) ? $this->_query['having'] : '';
  9722. }
  9723. public function setHaving($value)
  9724. {
  9725. $this->having($value);
  9726. }
  9727. public function order($columns)
  9728. {
  9729. if(is_string($columns) && strpos($columns,'(')!==false)
  9730. $this->_query['order']=$columns;
  9731. else
  9732. {
  9733. if(!is_array($columns))
  9734. $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);
  9735. foreach($columns as $i=>$column)
  9736. {
  9737. if(is_object($column))
  9738. $columns[$i]=(string)$column;
  9739. elseif(strpos($column,'(')===false)
  9740. {
  9741. if(preg_match('/^(.*?)\s+(asc|desc)$/i',$column,$matches))
  9742. $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' '.strtoupper($matches[2]);
  9743. else
  9744. $columns[$i]=$this->_connection->quoteColumnName($column);
  9745. }
  9746. }
  9747. $this->_query['order']=implode(', ',$columns);
  9748. }
  9749. return $this;
  9750. }
  9751. public function getOrder()
  9752. {
  9753. return isset($this->_query['order']) ? $this->_query['order'] : '';
  9754. }
  9755. public function setOrder($value)
  9756. {
  9757. $this->order($value);
  9758. }
  9759. public function limit($limit, $offset=null)
  9760. {
  9761. $this->_query['limit']=(int)$limit;
  9762. if($offset!==null)
  9763. $this->offset($offset);
  9764. return $this;
  9765. }
  9766. public function getLimit()
  9767. {
  9768. return isset($this->_query['limit']) ? $this->_query['limit'] : -1;
  9769. }
  9770. public function setLimit($value)
  9771. {
  9772. $this->limit($value);
  9773. }
  9774. public function offset($offset)
  9775. {
  9776. $this->_query['offset']=(int)$offset;
  9777. return $this;
  9778. }
  9779. public function getOffset()
  9780. {
  9781. return isset($this->_query['offset']) ? $this->_query['offset'] : -1;
  9782. }
  9783. public function setOffset($value)
  9784. {
  9785. $this->offset($value);
  9786. }
  9787. public function union($sql)
  9788. {
  9789. if(isset($this->_query['union']) && is_string($this->_query['union']))
  9790. $this->_query['union']=array($this->_query['union']);
  9791. $this->_query['union'][]=$sql;
  9792. return $this;
  9793. }
  9794. public function getUnion()
  9795. {
  9796. return isset($this->_query['union']) ? $this->_query['union'] : '';
  9797. }
  9798. public function setUnion($value)
  9799. {
  9800. $this->_query['union']=$value;
  9801. }
  9802. public function insert($table, $columns)
  9803. {
  9804. $params=array();
  9805. $names=array();
  9806. $placeholders=array();
  9807. foreach($columns as $name=>$value)
  9808. {
  9809. $names[]=$this->_connection->quoteColumnName($name);
  9810. if($value instanceof CDbExpression)
  9811. {
  9812. $placeholders[] = $value->expression;
  9813. foreach($value->params as $n => $v)
  9814. $params[$n] = $v;
  9815. }
  9816. else
  9817. {
  9818. $placeholders[] = ':' . $name;
  9819. $params[':' . $name] = $value;
  9820. }
  9821. }
  9822. $sql='INSERT INTO ' . $this->_connection->quoteTableName($table)
  9823. . ' (' . implode(', ',$names) . ') VALUES ('
  9824. . implode(', ', $placeholders) . ')';
  9825. return $this->setText($sql)->execute($params);
  9826. }
  9827. public function update($table, $columns, $conditions='', $params=array())
  9828. {
  9829. $lines=array();
  9830. foreach($columns as $name=>$value)
  9831. {
  9832. if($value instanceof CDbExpression)
  9833. {
  9834. $lines[]=$this->_connection->quoteColumnName($name) . '=' . $value->expression;
  9835. foreach($value->params as $n => $v)
  9836. $params[$n] = $v;
  9837. }
  9838. else
  9839. {
  9840. $lines[]=$this->_connection->quoteColumnName($name) . '=:' . $name;
  9841. $params[':' . $name]=$value;
  9842. }
  9843. }
  9844. $sql='UPDATE ' . $this->_connection->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  9845. if(($where=$this->processConditions($conditions))!='')
  9846. $sql.=' WHERE '.$where;
  9847. return $this->setText($sql)->execute($params);
  9848. }
  9849. public function delete($table, $conditions='', $params=array())
  9850. {
  9851. $sql='DELETE FROM ' . $this->_connection->quoteTableName($table);
  9852. if(($where=$this->processConditions($conditions))!='')
  9853. $sql.=' WHERE '.$where;
  9854. return $this->setText($sql)->execute($params);
  9855. }
  9856. public function createTable($table, $columns, $options=null)
  9857. {
  9858. return $this->setText($this->getConnection()->getSchema()->createTable($table, $columns, $options))->execute();
  9859. }
  9860. public function renameTable($table, $newName)
  9861. {
  9862. return $this->setText($this->getConnection()->getSchema()->renameTable($table, $newName))->execute();
  9863. }
  9864. public function dropTable($table)
  9865. {
  9866. return $this->setText($this->getConnection()->getSchema()->dropTable($table))->execute();
  9867. }
  9868. public function truncateTable($table)
  9869. {
  9870. $schema=$this->getConnection()->getSchema();
  9871. $n=$this->setText($schema->truncateTable($table))->execute();
  9872. if(strncasecmp($this->getConnection()->getDriverName(),'sqlite',6)===0)
  9873. $schema->resetSequence($schema->getTable($table));
  9874. return $n;
  9875. }
  9876. public function addColumn($table, $column, $type)
  9877. {
  9878. return $this->setText($this->getConnection()->getSchema()->addColumn($table, $column, $type))->execute();
  9879. }
  9880. public function dropColumn($table, $column)
  9881. {
  9882. return $this->setText($this->getConnection()->getSchema()->dropColumn($table, $column))->execute();
  9883. }
  9884. public function renameColumn($table, $name, $newName)
  9885. {
  9886. return $this->setText($this->getConnection()->getSchema()->renameColumn($table, $name, $newName))->execute();
  9887. }
  9888. public function alterColumn($table, $column, $type)
  9889. {
  9890. return $this->setText($this->getConnection()->getSchema()->alterColumn($table, $column, $type))->execute();
  9891. }
  9892. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete=null, $update=null)
  9893. {
  9894. return $this->setText($this->getConnection()->getSchema()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update))->execute();
  9895. }
  9896. public function dropForeignKey($name, $table)
  9897. {
  9898. return $this->setText($this->getConnection()->getSchema()->dropForeignKey($name, $table))->execute();
  9899. }
  9900. public function createIndex($name, $table, $columns, $unique=false)
  9901. {
  9902. return $this->setText($this->getConnection()->getSchema()->createIndex($name, $table, $columns, $unique))->execute();
  9903. }
  9904. public function dropIndex($name, $table)
  9905. {
  9906. return $this->setText($this->getConnection()->getSchema()->dropIndex($name, $table))->execute();
  9907. }
  9908. private function processConditions($conditions)
  9909. {
  9910. if(!is_array($conditions))
  9911. return $conditions;
  9912. elseif($conditions===array())
  9913. return '';
  9914. $n=count($conditions);
  9915. $operator=strtoupper($conditions[0]);
  9916. if($operator==='OR' || $operator==='AND')
  9917. {
  9918. $parts=array();
  9919. for($i=1;$i<$n;++$i)
  9920. {
  9921. $condition=$this->processConditions($conditions[$i]);
  9922. if($condition!=='')
  9923. $parts[]='('.$condition.')';
  9924. }
  9925. return $parts===array() ? '' : implode(' '.$operator.' ', $parts);
  9926. }
  9927. if(!isset($conditions[1],$conditions[2]))
  9928. return '';
  9929. $column=$conditions[1];
  9930. if(strpos($column,'(')===false)
  9931. $column=$this->_connection->quoteColumnName($column);
  9932. $values=$conditions[2];
  9933. if(!is_array($values))
  9934. $values=array($values);
  9935. if($operator==='IN' || $operator==='NOT IN')
  9936. {
  9937. if($values===array())
  9938. return $operator==='IN' ? '0=1' : '';
  9939. foreach($values as $i=>$value)
  9940. {
  9941. if(is_string($value))
  9942. $values[$i]=$this->_connection->quoteValue($value);
  9943. else
  9944. $values[$i]=(string)$value;
  9945. }
  9946. return $column.' '.$operator.' ('.implode(', ',$values).')';
  9947. }
  9948. if($operator==='LIKE' || $operator==='NOT LIKE' || $operator==='OR LIKE' || $operator==='OR NOT LIKE')
  9949. {
  9950. if($values===array())
  9951. return $operator==='LIKE' || $operator==='OR LIKE' ? '0=1' : '';
  9952. if($operator==='LIKE' || $operator==='NOT LIKE')
  9953. $andor=' AND ';
  9954. else
  9955. {
  9956. $andor=' OR ';
  9957. $operator=$operator==='OR LIKE' ? 'LIKE' : 'NOT LIKE';
  9958. }
  9959. $expressions=array();
  9960. foreach($values as $value)
  9961. $expressions[]=$column.' '.$operator.' '.$this->_connection->quoteValue($value);
  9962. return implode($andor,$expressions);
  9963. }
  9964. throw new CDbException(Yii::t('yii', 'Unknown operator "{operator}".', array('{operator}'=>$operator)));
  9965. }
  9966. private function joinInternal($type, $table, $conditions='', $params=array())
  9967. {
  9968. if(strpos($table,'(')===false)
  9969. {
  9970. if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$table,$matches)) // with alias
  9971. $table=$this->_connection->quoteTableName($matches[1]).' '.$this->_connection->quoteTableName($matches[2]);
  9972. else
  9973. $table=$this->_connection->quoteTableName($table);
  9974. }
  9975. $conditions=$this->processConditions($conditions);
  9976. if($conditions!='')
  9977. $conditions=' ON '.$conditions;
  9978. if(isset($this->_query['join']) && is_string($this->_query['join']))
  9979. $this->_query['join']=array($this->_query['join']);
  9980. $this->_query['join'][]=strtoupper($type) . ' ' . $table . $conditions;
  9981. foreach($params as $name=>$value)
  9982. $this->params[$name]=$value;
  9983. return $this;
  9984. }
  9985. public function addPrimaryKey($name,$table,$columns)
  9986. {
  9987. return $this->setText($this->getConnection()->getSchema()->addPrimaryKey($name,$table,$columns))->execute();
  9988. }
  9989. public function dropPrimaryKey($name,$table)
  9990. {
  9991. return $this->setText($this->getConnection()->getSchema()->dropPrimaryKey($name,$table))->execute();
  9992. }
  9993. }
  9994. class CDbColumnSchema extends CComponent
  9995. {
  9996. public $name;
  9997. public $rawName;
  9998. public $allowNull;
  9999. public $dbType;
  10000. public $type;
  10001. public $defaultValue;
  10002. public $size;
  10003. public $precision;
  10004. public $scale;
  10005. public $isPrimaryKey;
  10006. public $isForeignKey;
  10007. public $autoIncrement=false;
  10008. public $comment='';
  10009. public function init($dbType, $defaultValue)
  10010. {
  10011. $this->dbType=$dbType;
  10012. $this->extractType($dbType);
  10013. $this->extractLimit($dbType);
  10014. if($defaultValue!==null)
  10015. $this->extractDefault($defaultValue);
  10016. }
  10017. protected function extractType($dbType)
  10018. {
  10019. if(stripos($dbType,'int')!==false && stripos($dbType,'unsigned int')===false)
  10020. $this->type='integer';
  10021. elseif(stripos($dbType,'bool')!==false)
  10022. $this->type='boolean';
  10023. elseif(preg_match('/(real|floa|doub)/i',$dbType))
  10024. $this->type='double';
  10025. else
  10026. $this->type='string';
  10027. }
  10028. protected function extractLimit($dbType)
  10029. {
  10030. if(strpos($dbType,'(') && preg_match('/\((.*)\)/',$dbType,$matches))
  10031. {
  10032. $values=explode(',',$matches[1]);
  10033. $this->size=$this->precision=(int)$values[0];
  10034. if(isset($values[1]))
  10035. $this->scale=(int)$values[1];
  10036. }
  10037. }
  10038. protected function extractDefault($defaultValue)
  10039. {
  10040. $this->defaultValue=$this->typecast($defaultValue);
  10041. }
  10042. public function typecast($value)
  10043. {
  10044. if(gettype($value)===$this->type || $value===null || $value instanceof CDbExpression)
  10045. return $value;
  10046. if($value==='' && $this->allowNull)
  10047. return $this->type==='string' ? '' : null;
  10048. switch($this->type)
  10049. {
  10050. case 'string': return (string)$value;
  10051. case 'integer': return (integer)$value;
  10052. case 'boolean': return (boolean)$value;
  10053. case 'double':
  10054. default: return $value;
  10055. }
  10056. }
  10057. }
  10058. class CSqliteColumnSchema extends CDbColumnSchema
  10059. {
  10060. protected function extractDefault($defaultValue)
  10061. {
  10062. if($this->dbType==='timestamp' && $defaultValue==='CURRENT_TIMESTAMP')
  10063. $this->defaultValue=null;
  10064. else
  10065. $this->defaultValue=$this->typecast(strcasecmp($defaultValue,'null') ? $defaultValue : null);
  10066. if($this->type==='string' && $this->defaultValue!==null) // PHP 5.2.6 adds single quotes while 5.2.0 doesn't
  10067. $this->defaultValue=trim($this->defaultValue,"'\"");
  10068. }
  10069. }
  10070. abstract class CValidator extends CComponent
  10071. {
  10072. public static $builtInValidators=array(
  10073. 'required'=>'CRequiredValidator',
  10074. 'filter'=>'CFilterValidator',
  10075. 'match'=>'CRegularExpressionValidator',
  10076. 'email'=>'CEmailValidator',
  10077. 'url'=>'CUrlValidator',
  10078. 'unique'=>'CUniqueValidator',
  10079. 'compare'=>'CCompareValidator',
  10080. 'length'=>'CStringValidator',
  10081. 'in'=>'CRangeValidator',
  10082. 'numerical'=>'CNumberValidator',
  10083. 'captcha'=>'CCaptchaValidator',
  10084. 'type'=>'CTypeValidator',
  10085. 'file'=>'CFileValidator',
  10086. 'default'=>'CDefaultValueValidator',
  10087. 'exist'=>'CExistValidator',
  10088. 'boolean'=>'CBooleanValidator',
  10089. 'safe'=>'CSafeValidator',
  10090. 'unsafe'=>'CUnsafeValidator',
  10091. 'date'=>'CDateValidator',
  10092. );
  10093. public $attributes;
  10094. public $message;
  10095. public $skipOnError=false;
  10096. public $on;
  10097. public $except;
  10098. public $safe=true;
  10099. public $enableClientValidation=true;
  10100. abstract protected function validateAttribute($object,$attribute);
  10101. public static function createValidator($name,$object,$attributes,$params=array())
  10102. {
  10103. if(is_string($attributes))
  10104. $attributes=preg_split('/\s*,\s*/',$attributes,-1,PREG_SPLIT_NO_EMPTY);
  10105. if(isset($params['on']))
  10106. {
  10107. if(is_array($params['on']))
  10108. $on=$params['on'];
  10109. else
  10110. $on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
  10111. }
  10112. else
  10113. $on=array();
  10114. if(isset($params['except']))
  10115. {
  10116. if(is_array($params['except']))
  10117. $except=$params['except'];
  10118. else
  10119. $except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
  10120. }
  10121. else
  10122. $except=array();
  10123. if(method_exists($object,$name))
  10124. {
  10125. $validator=new CInlineValidator;
  10126. $validator->attributes=$attributes;
  10127. $validator->method=$name;
  10128. if(isset($params['clientValidate']))
  10129. {
  10130. $validator->clientValidate=$params['clientValidate'];
  10131. unset($params['clientValidate']);
  10132. }
  10133. $validator->params=$params;
  10134. if(isset($params['skipOnError']))
  10135. $validator->skipOnError=$params['skipOnError'];
  10136. }
  10137. else
  10138. {
  10139. $params['attributes']=$attributes;
  10140. if(isset(self::$builtInValidators[$name]))
  10141. $className=Yii::import(self::$builtInValidators[$name],true);
  10142. else
  10143. $className=Yii::import($name,true);
  10144. $validator=new $className;
  10145. foreach($params as $name=>$value)
  10146. $validator->$name=$value;
  10147. }
  10148. $validator->on=empty($on) ? array() : array_combine($on,$on);
  10149. $validator->except=empty($except) ? array() : array_combine($except,$except);
  10150. return $validator;
  10151. }
  10152. public function validate($object,$attributes=null)
  10153. {
  10154. if(is_array($attributes))
  10155. $attributes=array_intersect($this->attributes,$attributes);
  10156. else
  10157. $attributes=$this->attributes;
  10158. foreach($attributes as $attribute)
  10159. {
  10160. if(!$this->skipOnError || !$object->hasErrors($attribute))
  10161. $this->validateAttribute($object,$attribute);
  10162. }
  10163. }
  10164. public function clientValidateAttribute($object,$attribute)
  10165. {
  10166. }
  10167. public function applyTo($scenario)
  10168. {
  10169. if(isset($this->except[$scenario]))
  10170. return false;
  10171. return empty($this->on) || isset($this->on[$scenario]);
  10172. }
  10173. protected function addError($object,$attribute,$message,$params=array())
  10174. {
  10175. $params['{attribute}']=$object->getAttributeLabel($attribute);
  10176. $object->addError($attribute,strtr($message,$params));
  10177. }
  10178. protected function isEmpty($value,$trim=false)
  10179. {
  10180. return $value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
  10181. }
  10182. }
  10183. class CStringValidator extends CValidator
  10184. {
  10185. public $max;
  10186. public $min;
  10187. public $is;
  10188. public $tooShort;
  10189. public $tooLong;
  10190. public $allowEmpty=true;
  10191. public $encoding;
  10192. protected function validateAttribute($object,$attribute)
  10193. {
  10194. $value=$object->$attribute;
  10195. if($this->allowEmpty && $this->isEmpty($value))
  10196. return;
  10197. if(is_array($value))
  10198. {
  10199. // https://github.com/yiisoft/yii/issues/1955
  10200. $this->addError($object,$attribute,Yii::t('yii','{attribute} is invalid.'));
  10201. return;
  10202. }
  10203. if(function_exists('mb_strlen') && $this->encoding!==false)
  10204. $length=mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
  10205. else
  10206. $length=strlen($value);
  10207. if($this->min!==null && $length<$this->min)
  10208. {
  10209. $message=$this->tooShort!==null?$this->tooShort:Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10210. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10211. }
  10212. if($this->max!==null && $length>$this->max)
  10213. {
  10214. $message=$this->tooLong!==null?$this->tooLong:Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10215. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10216. }
  10217. if($this->is!==null && $length!==$this->is)
  10218. {
  10219. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10220. $this->addError($object,$attribute,$message,array('{length}'=>$this->is));
  10221. }
  10222. }
  10223. public function clientValidateAttribute($object,$attribute)
  10224. {
  10225. $label=$object->getAttributeLabel($attribute);
  10226. if(($message=$this->message)===null)
  10227. $message=Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
  10228. $message=strtr($message, array(
  10229. '{attribute}'=>$label,
  10230. '{length}'=>$this->is,
  10231. ));
  10232. if(($tooShort=$this->tooShort)===null)
  10233. $tooShort=Yii::t('yii','{attribute} is too short (minimum is {min} characters).');
  10234. $tooShort=strtr($tooShort, array(
  10235. '{attribute}'=>$label,
  10236. '{min}'=>$this->min,
  10237. ));
  10238. if(($tooLong=$this->tooLong)===null)
  10239. $tooLong=Yii::t('yii','{attribute} is too long (maximum is {max} characters).');
  10240. $tooLong=strtr($tooLong, array(
  10241. '{attribute}'=>$label,
  10242. '{max}'=>$this->max,
  10243. ));
  10244. $js='';
  10245. if($this->min!==null)
  10246. {
  10247. $js.="
  10248. if(value.length<{$this->min}) {
  10249. messages.push(".CJSON::encode($tooShort).");
  10250. }
  10251. ";
  10252. }
  10253. if($this->max!==null)
  10254. {
  10255. $js.="
  10256. if(value.length>{$this->max}) {
  10257. messages.push(".CJSON::encode($tooLong).");
  10258. }
  10259. ";
  10260. }
  10261. if($this->is!==null)
  10262. {
  10263. $js.="
  10264. if(value.length!={$this->is}) {
  10265. messages.push(".CJSON::encode($message).");
  10266. }
  10267. ";
  10268. }
  10269. if($this->allowEmpty)
  10270. {
  10271. $js="
  10272. if(jQuery.trim(value)!='') {
  10273. $js
  10274. }
  10275. ";
  10276. }
  10277. return $js;
  10278. }
  10279. }
  10280. class CRequiredValidator extends CValidator
  10281. {
  10282. public $requiredValue;
  10283. public $strict=false;
  10284. public $trim=true;
  10285. protected function validateAttribute($object,$attribute)
  10286. {
  10287. $value=$object->$attribute;
  10288. if($this->requiredValue!==null)
  10289. {
  10290. if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue)
  10291. {
  10292. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.',
  10293. array('{value}'=>$this->requiredValue));
  10294. $this->addError($object,$attribute,$message);
  10295. }
  10296. }
  10297. elseif($this->isEmpty($value,$this->trim))
  10298. {
  10299. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.');
  10300. $this->addError($object,$attribute,$message);
  10301. }
  10302. }
  10303. public function clientValidateAttribute($object,$attribute)
  10304. {
  10305. $message=$this->message;
  10306. if($this->requiredValue!==null)
  10307. {
  10308. if($message===null)
  10309. $message=Yii::t('yii','{attribute} must be {value}.');
  10310. $message=strtr($message, array(
  10311. '{value}'=>$this->requiredValue,
  10312. '{attribute}'=>$object->getAttributeLabel($attribute),
  10313. ));
  10314. return "
  10315. if(value!=" . CJSON::encode($this->requiredValue) . ") {
  10316. messages.push(".CJSON::encode($message).");
  10317. }
  10318. ";
  10319. }
  10320. else
  10321. {
  10322. if($message===null)
  10323. $message=Yii::t('yii','{attribute} cannot be blank.');
  10324. $message=strtr($message, array(
  10325. '{attribute}'=>$object->getAttributeLabel($attribute),
  10326. ));
  10327. if($this->trim)
  10328. $emptyCondition = "jQuery.trim(value)==''";
  10329. else
  10330. $emptyCondition = "value==''";
  10331. return "
  10332. if({$emptyCondition}) {
  10333. messages.push(".CJSON::encode($message).");
  10334. }
  10335. ";
  10336. }
  10337. }
  10338. }
  10339. class CNumberValidator extends CValidator
  10340. {
  10341. public $integerOnly=false;
  10342. public $allowEmpty=true;
  10343. public $max;
  10344. public $min;
  10345. public $tooBig;
  10346. public $tooSmall;
  10347. public $integerPattern='/^\s*[+-]?\d+\s*$/';
  10348. public $numberPattern='/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
  10349. protected function validateAttribute($object,$attribute)
  10350. {
  10351. $value=$object->$attribute;
  10352. if($this->allowEmpty && $this->isEmpty($value))
  10353. return;
  10354. if(!is_numeric($value))
  10355. {
  10356. // https://github.com/yiisoft/yii/issues/1955
  10357. // https://github.com/yiisoft/yii/issues/1669
  10358. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10359. $this->addError($object,$attribute,$message);
  10360. return;
  10361. }
  10362. if($this->integerOnly)
  10363. {
  10364. if(!preg_match($this->integerPattern,"$value"))
  10365. {
  10366. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be an integer.');
  10367. $this->addError($object,$attribute,$message);
  10368. }
  10369. }
  10370. else
  10371. {
  10372. if(!preg_match($this->numberPattern,"$value"))
  10373. {
  10374. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be a number.');
  10375. $this->addError($object,$attribute,$message);
  10376. }
  10377. }
  10378. if($this->min!==null && $value<$this->min)
  10379. {
  10380. $message=$this->tooSmall!==null?$this->tooSmall:Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10381. $this->addError($object,$attribute,$message,array('{min}'=>$this->min));
  10382. }
  10383. if($this->max!==null && $value>$this->max)
  10384. {
  10385. $message=$this->tooBig!==null?$this->tooBig:Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10386. $this->addError($object,$attribute,$message,array('{max}'=>$this->max));
  10387. }
  10388. }
  10389. public function clientValidateAttribute($object,$attribute)
  10390. {
  10391. $label=$object->getAttributeLabel($attribute);
  10392. if(($message=$this->message)===null)
  10393. $message=$this->integerOnly ? Yii::t('yii','{attribute} must be an integer.') : Yii::t('yii','{attribute} must be a number.');
  10394. $message=strtr($message, array(
  10395. '{attribute}'=>$label,
  10396. ));
  10397. if(($tooBig=$this->tooBig)===null)
  10398. $tooBig=Yii::t('yii','{attribute} is too big (maximum is {max}).');
  10399. $tooBig=strtr($tooBig, array(
  10400. '{attribute}'=>$label,
  10401. '{max}'=>$this->max,
  10402. ));
  10403. if(($tooSmall=$this->tooSmall)===null)
  10404. $tooSmall=Yii::t('yii','{attribute} is too small (minimum is {min}).');
  10405. $tooSmall=strtr($tooSmall, array(
  10406. '{attribute}'=>$label,
  10407. '{min}'=>$this->min,
  10408. ));
  10409. $pattern=$this->integerOnly ? $this->integerPattern : $this->numberPattern;
  10410. $js="
  10411. if(!value.match($pattern)) {
  10412. messages.push(".CJSON::encode($message).");
  10413. }
  10414. ";
  10415. if($this->min!==null)
  10416. {
  10417. $js.="
  10418. if(value<{$this->min}) {
  10419. messages.push(".CJSON::encode($tooSmall).");
  10420. }
  10421. ";
  10422. }
  10423. if($this->max!==null)
  10424. {
  10425. $js.="
  10426. if(value>{$this->max}) {
  10427. messages.push(".CJSON::encode($tooBig).");
  10428. }
  10429. ";
  10430. }
  10431. if($this->allowEmpty)
  10432. {
  10433. $js="
  10434. if(jQuery.trim(value)!='') {
  10435. $js
  10436. }
  10437. ";
  10438. }
  10439. return $js;
  10440. }
  10441. }
  10442. class CListIterator implements Iterator
  10443. {
  10444. private $_d;
  10445. private $_i;
  10446. private $_c;
  10447. public function __construct(&$data)
  10448. {
  10449. $this->_d=&$data;
  10450. $this->_i=0;
  10451. $this->_c=count($this->_d);
  10452. }
  10453. public function rewind()
  10454. {
  10455. $this->_i=0;
  10456. }
  10457. public function key()
  10458. {
  10459. return $this->_i;
  10460. }
  10461. public function current()
  10462. {
  10463. return $this->_d[$this->_i];
  10464. }
  10465. public function next()
  10466. {
  10467. $this->_i++;
  10468. }
  10469. public function valid()
  10470. {
  10471. return $this->_i<$this->_c;
  10472. }
  10473. }
  10474. interface IApplicationComponent
  10475. {
  10476. public function init();
  10477. public function getIsInitialized();
  10478. }
  10479. interface ICache
  10480. {
  10481. public function get($id);
  10482. public function mget($ids);
  10483. public function set($id,$value,$expire=0,$dependency=null);
  10484. public function add($id,$value,$expire=0,$dependency=null);
  10485. public function delete($id);
  10486. public function flush();
  10487. }
  10488. interface ICacheDependency
  10489. {
  10490. public function evaluateDependency();
  10491. public function getHasChanged();
  10492. }
  10493. interface IStatePersister
  10494. {
  10495. public function load();
  10496. public function save($state);
  10497. }
  10498. interface IFilter
  10499. {
  10500. public function filter($filterChain);
  10501. }
  10502. interface IAction
  10503. {
  10504. public function getId();
  10505. public function getController();
  10506. }
  10507. interface IWebServiceProvider
  10508. {
  10509. public function beforeWebMethod($service);
  10510. public function afterWebMethod($service);
  10511. }
  10512. interface IViewRenderer
  10513. {
  10514. public function renderFile($context,$file,$data,$return);
  10515. }
  10516. interface IUserIdentity
  10517. {
  10518. public function authenticate();
  10519. public function getIsAuthenticated();
  10520. public function getId();
  10521. public function getName();
  10522. public function getPersistentStates();
  10523. }
  10524. interface IWebUser
  10525. {
  10526. public function getId();
  10527. public function getName();
  10528. public function getIsGuest();
  10529. public function checkAccess($operation,$params=array());
  10530. public function loginRequired();
  10531. }
  10532. interface IAuthManager
  10533. {
  10534. public function checkAccess($itemName,$userId,$params=array());
  10535. public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null);
  10536. public function removeAuthItem($name);
  10537. public function getAuthItems($type=null,$userId=null);
  10538. public function getAuthItem($name);
  10539. public function saveAuthItem($item,$oldName=null);
  10540. public function addItemChild($itemName,$childName);
  10541. public function removeItemChild($itemName,$childName);
  10542. public function hasItemChild($itemName,$childName);
  10543. public function getItemChildren($itemName);
  10544. public function assign($itemName,$userId,$bizRule=null,$data=null);
  10545. public function revoke($itemName,$userId);
  10546. public function isAssigned($itemName,$userId);
  10547. public function getAuthAssignment($itemName,$userId);
  10548. public function getAuthAssignments($userId);
  10549. public function saveAuthAssignment($assignment);
  10550. public function clearAll();
  10551. public function clearAuthAssignments();
  10552. public function save();
  10553. public function executeBizRule($bizRule,$params,$data);
  10554. }
  10555. interface IBehavior
  10556. {
  10557. public function attach($component);
  10558. public function detach($component);
  10559. public function getEnabled();
  10560. public function setEnabled($value);
  10561. }
  10562. interface IWidgetFactory
  10563. {
  10564. public function createWidget($owner,$className,$properties=array());
  10565. }
  10566. interface IDataProvider
  10567. {
  10568. public function getId();
  10569. public function getItemCount($refresh=false);
  10570. public function getTotalItemCount($refresh=false);
  10571. public function getData($refresh=false);
  10572. public function getKeys($refresh=false);
  10573. public function getSort();
  10574. public function getPagination();
  10575. }
  10576. interface ILogFilter
  10577. {
  10578. public function filter(&$logs);
  10579. }
  10580. ?>