rb.php 226 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257
  1. <?php
  2. /**
  3. REDBEANPHP 3.4
  4. --------------
  5. RedBeanPHP Database Objects -
  6. Written by Gabor de Mooij (c) copyright 2009-2013 and the RedBeanPHP community
  7. RedBeanPHP is DUAL Licensed BSD and GPLv2. You may choose the license that fits
  8. best for your project.
  9. */
  10. interface RedBean_Driver {
  11. /**
  12. * Runs a query and fetches results as a multi dimensional array.
  13. *
  14. * @param string $sql SQL to be executed
  15. *
  16. * @return array $results result
  17. */
  18. public function GetAll($sql, $aValues = array());
  19. /**
  20. * Runs a query and fetches results as a column.
  21. *
  22. * @param string $sql SQL Code to execute
  23. *
  24. * @return array $results Resultset
  25. */
  26. public function GetCol($sql, $aValues = array());
  27. /**
  28. * Runs a query and returns results as a single cell.
  29. *
  30. * @param string $sql SQL to execute
  31. *
  32. * @return mixed $cellvalue result cell
  33. */
  34. public function GetCell($sql, $aValues = array());
  35. /**
  36. * Runs a query and returns a flat array containing the values of
  37. * one row.
  38. *
  39. * @param string $sql SQL to execute
  40. *
  41. * @return array $row result row
  42. */
  43. public function GetRow($sql, $aValues = array());
  44. /**
  45. * Executes SQL code and allows key-value binding.
  46. * This function allows you to provide an array with values to bind
  47. * to query parameters. For instance you can bind values to question
  48. * marks in the query. Each value in the array corresponds to the
  49. * question mark in the query that matches the position of the value in the
  50. * array. You can also bind values using explicit keys, for instance
  51. * array(":key"=>123) will bind the integer 123 to the key :key in the
  52. * SQL. This method has no return value.
  53. *
  54. * @param string $sql SQL Code to execute
  55. * @param array $aValues Values to bind to SQL query
  56. *
  57. * @return void
  58. */
  59. public function Execute($sql, $aValues = array());
  60. /**
  61. * Returns the latest insert ID if driver does support this
  62. * feature.
  63. *
  64. * @return integer $id primary key ID
  65. */
  66. public function GetInsertID();
  67. /**
  68. * Returns the number of rows affected by the most recent query
  69. * if the currently selected driver driver supports this feature.
  70. *
  71. * @return integer $numOfRows number of rows affected
  72. */
  73. public function Affected_Rows();
  74. /**
  75. * Toggles debug mode. In debug mode the driver will print all
  76. * SQL to the screen together with some information about the
  77. * results. All SQL code that passes through the driver will be
  78. * passes on to the screen for inspection.
  79. * This method has no return value.
  80. *
  81. * @param boolean $trueFalse turn on/off
  82. *
  83. * @return void
  84. */
  85. public function setDebugMode($tf);
  86. /**
  87. * Starts a transaction.
  88. * @return void
  89. */
  90. public function CommitTrans();
  91. /**
  92. * Commits a transaction.
  93. * @return void
  94. */
  95. public function StartTrans();
  96. /**
  97. * Rolls back a transaction.
  98. * @return void
  99. */
  100. public function FailTrans();
  101. }
  102. class RedBean_Driver_PDO implements RedBean_Driver {
  103. /**
  104. * @var string
  105. */
  106. protected $dsn;
  107. /**
  108. * @var boolean
  109. */
  110. protected $debug = false;
  111. /**
  112. * @var RedBean_Logger
  113. */
  114. protected $logger = NULL;
  115. /**
  116. * @var PDO
  117. */
  118. protected $pdo;
  119. /**
  120. * @var integer
  121. */
  122. protected $affected_rows;
  123. /**
  124. * @var integer
  125. */
  126. protected $rs;
  127. /**
  128. * @var array
  129. */
  130. protected $connectInfo = array();
  131. /**
  132. * @var bool
  133. */
  134. public $flagUseStringOnlyBinding = false;
  135. /**
  136. * @var boolean
  137. */
  138. protected $isConnected = false;
  139. /**
  140. * Constructor. You may either specify dsn, user and password or
  141. * just give an existing PDO connection.
  142. * Examples:
  143. * $driver = new RedBean_Driver_PDO($dsn, $user, $password);
  144. * $driver = new RedBean_Driver_PDO($existingConnection);
  145. *
  146. * @param string|PDO $dsn database connection string
  147. * @param string $user optional, usename to sign in
  148. * @param string $pass optional, password for connection login
  149. *
  150. * @return void
  151. */
  152. public function __construct($dsn, $user = null, $pass = null) {
  153. if ($dsn instanceof PDO) {
  154. $this->pdo = $dsn;
  155. $this->isConnected = true;
  156. $this->pdo->setAttribute(1002, 'SET NAMES utf8');
  157. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  158. $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  159. // make sure that the dsn at least contains the type
  160. $this->dsn = $this->getDatabaseType();
  161. } else {
  162. $this->dsn = $dsn;
  163. $this->connectInfo = array('pass' => $pass, 'user' => $user);
  164. }
  165. }
  166. /**
  167. * Establishes a connection to the database using PHP PDO
  168. * functionality. If a connection has already been established this
  169. * method will simply return directly. This method also turns on
  170. * UTF8 for the database and PDO-ERRMODE-EXCEPTION as well as
  171. * PDO-FETCH-ASSOC.
  172. *
  173. * @return void
  174. */
  175. public function connect() {
  176. if ($this->isConnected) return;
  177. try {
  178. $user = $this->connectInfo['user'];
  179. $pass = $this->connectInfo['pass'];
  180. $this->pdo = new PDO(
  181. $this->dsn,
  182. $user,
  183. $pass,
  184. array(1002 => 'SET NAMES utf8',
  185. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  186. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  187. )
  188. );
  189. $this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
  190. $this->isConnected = true;
  191. } catch(PDOException $e) {
  192. throw new PDOException('Could not connect to database.');
  193. }
  194. }
  195. /**
  196. * Binds parameters. This method binds parameters to a PDOStatement for
  197. * Query Execution. This method binds parameters as NULL, INTEGER or STRING
  198. * and supports both named keys and question mark keys.
  199. *
  200. * @param PDOStatement $s PDO Statement instance
  201. * @param array $aValues values that need to get bound to the statement
  202. *
  203. * @return void
  204. */
  205. protected function bindParams($s, $aValues) {
  206. foreach($aValues as $key => &$value) {
  207. if (is_integer($key)) {
  208. if (is_null($value)){
  209. $s->bindValue($key+1, null, PDO::PARAM_NULL);
  210. } elseif (!$this->flagUseStringOnlyBinding && RedBean_QueryWriter_AQueryWriter::canBeTreatedAsInt($value) && $value < 2147483648) {
  211. $s->bindParam($key+1, $value, PDO::PARAM_INT);
  212. } else {
  213. $s->bindParam($key+1, $value, PDO::PARAM_STR);
  214. }
  215. } else {
  216. if (is_null($value)){
  217. $s->bindValue($key, null, PDO::PARAM_NULL);
  218. } elseif (!$this->flagUseStringOnlyBinding && RedBean_QueryWriter_AQueryWriter::canBeTreatedAsInt($value) && $value < 2147483648) {
  219. $s->bindParam($key, $value, PDO::PARAM_INT);
  220. } else {
  221. $s->bindParam($key, $value, PDO::PARAM_STR);
  222. }
  223. }
  224. }
  225. }
  226. /**
  227. * This method runs the actual SQL query and binds a list of parameters to the query.
  228. * slots. The result of the query will be stored in the protected property
  229. * $rs (always array). The number of rows affected (result of rowcount, if supported by database)
  230. * is stored in protected property $affected_rows. If the debug flag is set
  231. * this function will send debugging output to screen buffer.
  232. *
  233. * @throws RedBean_Exception_SQL
  234. *
  235. * @param string $sql the SQL string to be send to database server
  236. * @param array $aValues the values that need to get bound to the query slots
  237. */
  238. protected function runQuery($sql, $aValues) {
  239. $this->connect();
  240. if ($this->debug && $this->logger) {
  241. $this->logger->log($sql, $aValues);
  242. }
  243. try {
  244. if (strpos('pgsql', $this->dsn) === 0) {
  245. $s = $this->pdo->prepare($sql, array(PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT => true));
  246. } else {
  247. $s = $this->pdo->prepare($sql);
  248. }
  249. $this->bindParams($s, $aValues);
  250. $s->execute();
  251. $this->affected_rows = $s->rowCount();
  252. if ($s->columnCount()) {
  253. $this->rs = $s->fetchAll();
  254. if ($this->debug && $this->logger) $this->logger->log('resultset: '.count($this->rs).' rows');
  255. } else {
  256. $this->rs = array();
  257. }
  258. } catch(PDOException $e) {
  259. //Unfortunately the code field is supposed to be int by default (php)
  260. //So we need a property to convey the SQL State code.
  261. $err = $e->getMessage();
  262. if ($this->debug && $this->logger) $this->logger->log('An error occurred: '.$err);
  263. $x = new RedBean_Exception_SQL($err, 0);
  264. $x->setSQLState($e->getCode());
  265. throw $x;
  266. }
  267. }
  268. /**
  269. * @see RedBean_Driver::GetAll
  270. */
  271. public function GetAll($sql, $aValues = array()) {
  272. $this->runQuery($sql, $aValues);
  273. return $this->rs;
  274. }
  275. /**
  276. * @see RedBean_Driver::GetCol
  277. */
  278. public function GetCol($sql, $aValues = array()) {
  279. $rows = $this->GetAll($sql, $aValues);
  280. $cols = array();
  281. if ($rows && is_array($rows) && count($rows)>0) {
  282. foreach ($rows as $row) {
  283. $cols[] = array_shift($row);
  284. }
  285. }
  286. return $cols;
  287. }
  288. /**
  289. * @see RedBean_Driver::GetCell
  290. */
  291. public function GetCell($sql, $aValues = array()) {
  292. $arr = $this->GetAll($sql, $aValues);
  293. $row1 = array_shift($arr);
  294. $col1 = array_shift($row1);
  295. return $col1;
  296. }
  297. /**
  298. * @see RedBean_Driver::GetRow
  299. */
  300. public function GetRow($sql, $aValues = array()) {
  301. $arr = $this->GetAll($sql, $aValues);
  302. return array_shift($arr);
  303. }
  304. /**
  305. * @see RedBean_Driver::Excecute
  306. */
  307. public function Execute($sql, $aValues = array()) {
  308. $this->runQuery($sql, $aValues);
  309. return $this->affected_rows;
  310. }
  311. /**
  312. * @see RedBean_Driver::GetInsertID
  313. */
  314. public function GetInsertID() {
  315. $this->connect();
  316. return (int) $this->pdo->lastInsertId();
  317. }
  318. /**
  319. * @see RedBean_Driver::Affected_Rows
  320. */
  321. public function Affected_Rows() {
  322. $this->connect();
  323. return (int) $this->affected_rows;
  324. }
  325. /**
  326. * Toggles debug mode. In debug mode the driver will print all
  327. * SQL to the screen together with some information about the
  328. * results.
  329. *
  330. * @param boolean $trueFalse turn on/off
  331. * @param RedBean_Logger $logger
  332. *
  333. * @return void
  334. */
  335. public function setDebugMode($tf, $logger = NULL) {
  336. $this->connect();
  337. $this->debug = (bool) $tf;
  338. if ($this->debug and !$logger) $logger = new RedBean_Logger_Default();
  339. $this->setLogger($logger);
  340. }
  341. /**
  342. * Injects RedBean_Logger object.
  343. *
  344. * @param RedBean_Logger $logger
  345. */
  346. public function setLogger(RedBean_Logger $logger) {
  347. $this->logger = $logger;
  348. }
  349. /**
  350. * Gets RedBean_Logger object.
  351. *
  352. * @return RedBean_Logger
  353. */
  354. public function getLogger() {
  355. return $this->logger;
  356. }
  357. /**
  358. * @see RedBean_Driver::StartTrans
  359. */
  360. public function StartTrans() {
  361. $this->connect();
  362. $this->pdo->beginTransaction();
  363. }
  364. /**
  365. * @see RedBean_Driver::CommitTrans
  366. */
  367. public function CommitTrans() {
  368. $this->connect();
  369. $this->pdo->commit();
  370. }
  371. /**
  372. * @see RedBean_Driver::FailTrans
  373. */
  374. public function FailTrans() {
  375. $this->connect();
  376. $this->pdo->rollback();
  377. }
  378. /**
  379. * Returns the name of the database type/brand: i.e. mysql, db2 etc.
  380. *
  381. * @return string $typeName database identification
  382. */
  383. public function getDatabaseType() {
  384. $this->connect();
  385. return $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
  386. }
  387. /**
  388. * Returns the version number of the database.
  389. *
  390. * @return mixed $version version number of the database
  391. */
  392. public function getDatabaseVersion() {
  393. $this->connect();
  394. return $this->pdo->getAttribute(PDO::ATTR_CLIENT_VERSION);
  395. }
  396. /**
  397. * Returns the underlying PHP PDO instance.
  398. *
  399. * @return PDO $pdo PDO instance used by PDO wrapper
  400. */
  401. public function getPDO() {
  402. $this->connect();
  403. return $this->pdo;
  404. }
  405. /**
  406. * Closes database connection by destructing PDO.
  407. */
  408. public function close() {
  409. $this->pdo = null;
  410. $this->isConnected = false;
  411. }
  412. /**
  413. * Returns TRUE if the current PDO instance is connected.
  414. *
  415. * @return boolean $yesNO
  416. */
  417. public function isConnected() {
  418. if (!$this->isConnected && !$this->pdo) return false;
  419. return true;
  420. }
  421. }
  422. class RedBean_OODBBean implements IteratorAggregate, ArrayAccess, Countable {
  423. /**
  424. * @var boolean
  425. */
  426. private static $flagUseBeautyfulColumnnames = true;
  427. /**
  428. * @var array
  429. */
  430. private static $beautifulColumns = array();
  431. /**
  432. * @var boolean
  433. */
  434. private static $flagKeyedExport = false;
  435. /**
  436. * @var boolean
  437. */
  438. private $flagSkipBeau = false;
  439. /**
  440. * @var array $properties
  441. */
  442. private $properties = array();
  443. /**
  444. * @var array
  445. */
  446. private $__info = array();
  447. /**
  448. * @var RedBean_BeanHelper
  449. */
  450. private $beanHelper = NULL;
  451. /**
  452. * @var null
  453. */
  454. private $fetchType = NULL;
  455. /**
  456. * @var string
  457. */
  458. private $withSql = '';
  459. /**
  460. * @var array
  461. */
  462. private $withParams = array();
  463. /**
  464. * @var string
  465. */
  466. private $aliasName = NULL;
  467. /**
  468. * By default own-lists and shared-lists no longer have IDs as keys (3.3+),
  469. * this is because exportAll also does not offer this feature and we want the
  470. * ORM to be more consistent. Also, exporting without keys makes it easier to
  471. * export lists to Javascript because unlike in PHP in JS arrays will fill up gaps.
  472. *
  473. * @var boolean $yesNo
  474. */
  475. public static function setFlagKeyedExport($flag) {
  476. self::$flagKeyedExport = (boolean) $flag;
  477. }
  478. /**
  479. * Flag indicates whether column names with CamelCase are supported and automatically
  480. * converted; example: isForSale -> is_for_sale
  481. *
  482. * @param boolean
  483. */
  484. public static function setFlagBeautifulColumnNames($flag) {
  485. self::$flagUseBeautyfulColumnnames = (boolean) $flag;
  486. }
  487. /** Returns the alias for a type
  488. *
  489. * @param $type aliased type
  490. *
  491. * @return string $type type
  492. */
  493. private function getAlias($type) {
  494. if ($this->fetchType) {
  495. $type = $this->fetchType;
  496. $this->fetchType = null;
  497. }
  498. return $type;
  499. }
  500. /**
  501. * Sets the Bean Helper. Normally the Bean Helper is set by OODB.
  502. * Here you can change the Bean Helper. The Bean Helper is an object
  503. * providing access to a toolbox for the bean necessary to retrieve
  504. * nested beans (bean lists: ownBean, sharedBean) without the need to
  505. * rely on static calls to the facade (or make this class dep. on OODB).
  506. *
  507. * @param RedBean_IBeanHelper $helper
  508. *
  509. * @return void
  510. */
  511. public function setBeanHelper(RedBean_BeanHelper $helper) {
  512. $this->beanHelper = $helper;
  513. }
  514. /**
  515. * Returns an ArrayIterator so you can treat the bean like
  516. * an array with the properties container as its contents.
  517. *
  518. * @return ArrayIterator $arrayIt an array iterator instance with $properties
  519. */
  520. public function getIterator() {
  521. return new ArrayIterator($this->properties);
  522. }
  523. /**
  524. * Imports all values from an associative array $array. Chainable.
  525. *
  526. * @param array $array what you want to import
  527. * @param string|array $selection selection of values
  528. * @param boolean $notrim if TRUE values will not be trimmed
  529. *
  530. * @return RedBean_OODBBean $this
  531. */
  532. public function import($arr, $selection = false, $notrim = false) {
  533. if (is_string($selection)) {
  534. $selection = explode(',', $selection);
  535. }
  536. if (!$notrim && is_array($selection)) foreach($selection as $k => $s){ $selection[$k] = trim($s); }
  537. foreach($arr as $k => $v) {
  538. if ($k != '__info') {
  539. if (!$selection || ($selection && in_array($k, $selection))) {
  540. $this->$k = $v;
  541. }
  542. }
  543. }
  544. return $this;
  545. }
  546. /**
  547. * Imports data from another bean. Chainable.
  548. *
  549. * @param RedBean_OODBBean $sourceBean the source bean to take properties from
  550. *
  551. * @return RedBean_OODBBean $self
  552. */
  553. public function importFrom(RedBean_OODBBean $sourceBean) {
  554. $this->__info['tainted'] = true;
  555. $array = $sourceBean->properties;
  556. $this->properties = $array;
  557. return $this;
  558. }
  559. /**
  560. * Injects the properties of another bean but keeps the original ID.
  561. * Just like import() but keeps the original ID.
  562. * Chainable.
  563. *
  564. * @param RedBean_OODBBean $otherBean the bean whose properties you would like to copy
  565. *
  566. * @return RedBean_OODBBean $self
  567. */
  568. public function inject(RedBean_OODBBean $otherBean) {
  569. $myID = $this->id;
  570. $array = $otherBean->export();
  571. $this->import($array);
  572. $this->id = $myID;
  573. return $this;
  574. }
  575. /**
  576. * Exports the bean as an array.
  577. * This function exports the contents of a bean to an array and returns
  578. * the resulting array.
  579. *
  580. * @param boolean $meta set to TRUE if you want to export meta data as well
  581. * @param boolean $parents set to TRUE if you want to export parents as well
  582. * @param boolean $onlyMe set to TRUE if you want to export only this bean
  583. * @param array $filters optional whitelist for export
  584. *
  585. * @return array $arr
  586. */
  587. public function export($meta = false, $parents = false, $onlyMe = false, $filters = array()) {
  588. $arr = array();
  589. if ($parents) {
  590. foreach($this as $k => $v) {
  591. if (substr($k, -3) == '_id') {
  592. $prop = substr($k, 0, strlen($k)-3);
  593. $this->$prop;
  594. }
  595. }
  596. }
  597. foreach($this as $k => $v) {
  598. if (!$onlyMe && is_array($v)) {
  599. $vn = array();
  600. foreach($v as $i => $b) {
  601. if (is_numeric($i) && !self::$flagKeyedExport) {
  602. $vn[] = $b->export($meta, false, false, $filters);
  603. } else {
  604. $vn[$i] = $b->export($meta, false, false, $filters);
  605. }
  606. $v = $vn;
  607. }
  608. } elseif ($v instanceof RedBean_OODBBean) {
  609. if (is_array($filters) && count($filters) && !in_array(strtolower($v->getMeta('type')), $filters)) {
  610. continue;
  611. }
  612. $v = $v->export($meta, $parents, false, $filters);
  613. }
  614. $arr[$k] = $v;
  615. }
  616. if ($meta) $arr['__info'] = $this->__info;
  617. return $arr;
  618. }
  619. /**
  620. * Exports the bean to an object.
  621. *
  622. * @param object $obj target object
  623. *
  624. * @return array $arr
  625. */
  626. public function exportToObj($obj) {
  627. foreach($this->properties as $k => $v) {
  628. if (!is_array($v) && !is_object($v))
  629. $obj->$k = $v;
  630. }
  631. }
  632. /**
  633. * Implements isset() function for use as an array.
  634. *
  635. * @param string $property name of the property you want to check
  636. *
  637. * @return boolean
  638. */
  639. public function __isset($property) {
  640. return (isset($this->properties[$property]));
  641. }
  642. /**
  643. * Returns the ID of the bean no matter what the ID field is.
  644. *
  645. * @return string $id record Identifier for bean
  646. */
  647. public function getID() {
  648. return (string) $this->id;
  649. }
  650. /**
  651. * Unsets a property. This method will load the property first using
  652. * __get.
  653. *
  654. * @param string $property property
  655. *
  656. * @return void
  657. */
  658. public function __unset($property) {
  659. $this->__get($property);
  660. $fieldLink = $property.'_id';
  661. if (isset($this->$fieldLink)) {
  662. //wanna unset a bean reference?
  663. $this->$fieldLink = null;
  664. }
  665. if ((isset($this->properties[$property]))) {
  666. unset($this->properties[$property]);
  667. }
  668. }
  669. /**
  670. * Removes a property from the properties list without invoking
  671. * an __unset on the bean.
  672. *
  673. * @param string $property property that needs to be unset
  674. *
  675. * @return void
  676. */
  677. public function removeProperty($property) {
  678. unset($this->properties[$property]);
  679. }
  680. /**
  681. * Adds WHERE clause conditions to ownList retrieval.
  682. * For instance to get the pages that belong to a book you would
  683. * issue the following command: $book->ownPage
  684. * However, to order these pages by number use:
  685. *
  686. * $book->with(' ORDER BY `number` ASC ')->ownPage
  687. *
  688. * the additional SQL snippet will be merged into the final
  689. * query.
  690. *
  691. * @param string|RedBean_SQLHelper $sql SQL to be added to retrieval query.
  692. * @param array $params array with parameters to bind to SQL snippet
  693. *
  694. * @return RedBean_OODBBean $self
  695. */
  696. public function with($sql, $params = array()) {
  697. if ($sql instanceof RedBean_SQLHelper) {
  698. list($this->withSql, $this->withParams) = $sql->getQuery();
  699. } else {
  700. $this->withSql = $sql;
  701. $this->withParams = $params;
  702. }
  703. return $this;
  704. }
  705. /**
  706. * Just like with(). Except that this method prepends the SQL query snippet
  707. * with AND which makes it slightly more comfortable to use a conditional
  708. * SQL snippet. For instance to filter an own-list with pages (belonging to
  709. * a book) on specific chapters you can use:
  710. *
  711. * $book->withCondition(' chapter = 3 ')->ownPage
  712. *
  713. * This will return in the own list only the pages having 'chapter == 3'.
  714. *
  715. * @param string|RedBean_SQLHelper $sql SQL to be added to retrieval query (prefixed by AND)
  716. * @param array $params array with parameters to bind to SQL snippet
  717. *
  718. * @return RedBean_OODBBean $self
  719. */
  720. public function withCondition($sql, $params = array()) {
  721. if ($sql instanceof RedBean_SQLHelper) {
  722. list($sql, $params) = $sql->getQuery();
  723. }
  724. $this->withSql = ' AND '.$sql;
  725. $this->withParams = $params;
  726. return $this;
  727. }
  728. /**
  729. * Prepares an own-list to use an alias. This is best explained using
  730. * an example. Imagine a project and a person. The project always involves
  731. * two persons: a teacher and a student. The person beans have been aliased in this
  732. * case, so to the project has a teacher_id pointing to a person, and a student_id
  733. * also pointing to a person. Given a project, we obtain the teacher like this:
  734. *
  735. * $project->fetchAs('person')->teacher;
  736. *
  737. * Now, if we want all projects of a teacher we cant say:
  738. *
  739. * $teacher->ownProject
  740. *
  741. * because the $teacher is a bean of type 'person' and no project has been
  742. * assigned to a person. Instead we use the alias() method like this:
  743. *
  744. * $teacher->alias('teacher')->ownProject
  745. *
  746. * now we get the projects associated with the person bean aliased as
  747. * a teacher.
  748. *
  749. * @param string $aliasName the alias name to use
  750. *
  751. * @return RedBean_OODBBean
  752. */
  753. public function alias($aliasName) {
  754. $this->aliasName = $aliasName;
  755. return $this;
  756. }
  757. /**
  758. * Turns a camelcase property name into an underscored property name.
  759. * Examples:
  760. * oneACLRoute -> one_acl_route
  761. * camelCase -> camel_case
  762. *
  763. * Also caches the result to improve performance.
  764. *
  765. * @param string $property
  766. *
  767. * @return string
  768. */
  769. public function beau($property) {
  770. if (strpos($property, 'own') !== 0 && strpos($property, 'shared') !== 0) {
  771. if (isset(self::$beautifulColumns[$property])) {
  772. $propertyBeau = self::$beautifulColumns[$property];
  773. } else {
  774. $propertyBeau = strtolower(preg_replace('/(?<=[a-z])([A-Z])|([A-Z])(?=[a-z])/', '_$1$2', $property));
  775. self::$beautifulColumns[$property] = $propertyBeau;
  776. }
  777. return $propertyBeau;
  778. } else {
  779. return $property;
  780. }
  781. }
  782. /**
  783. * Magic Getter. Gets the value for a specific property in the bean.
  784. * If the property does not exist this getter will make sure no error
  785. * occurs. This is because RedBean allows you to query (probe) for
  786. * properties. If the property can not be found this method will
  787. * return NULL instead.
  788. * @param string $property
  789. * @return mixed $value
  790. */
  791. public function &__get($property) {
  792. if (self::$flagUseBeautyfulColumnnames && !$this->flagSkipBeau) {
  793. $property = $this->beau($property);
  794. }
  795. if ($this->beanHelper) {
  796. $toolbox = $this->beanHelper->getToolbox();
  797. $redbean = $toolbox->getRedBean();
  798. }
  799. if ($this->withSql !== '') {
  800. if (strpos($property, 'own') === 0) {
  801. unset($this->properties[$property]);
  802. }
  803. }
  804. if (!isset($this->properties[$property])) {
  805. $fieldLink = $property.'_id';
  806. if (isset($this->$fieldLink) && $fieldLink !== $this->getMeta('sys.idfield')) {
  807. $this->__info['tainted'] = true;
  808. $bean = $this->getMeta('sys.parentcache.'.$property);
  809. if (!$bean) {
  810. $type = $this->getAlias($property);
  811. $targetType = $this->properties[$fieldLink];
  812. $bean = $redbean->load($type, $targetType);
  813. }
  814. $this->properties[$property] = $bean;
  815. return $this->properties[$property];
  816. }
  817. elseif (strpos($property, 'own') === 0 && ctype_upper(substr($property, 3, 1))) {
  818. $type = lcfirst(substr($property, 3));
  819. if (self::$flagUseBeautyfulColumnnames) {
  820. $type = $this->beau($type);
  821. }
  822. if ($this->aliasName) {
  823. $parentField = $this->aliasName;
  824. $myFieldLink = $this->aliasName.'_id';
  825. $this->__info['sys.alias.'.$type] = $this->aliasName;
  826. $this->aliasName = null;
  827. } else {
  828. $myFieldLink = $this->__info['type'].'_id';
  829. $parentField = $this->__info['type'];
  830. }
  831. $beans = array();
  832. if ($this->getID()>0) {
  833. $params = array_merge(array($this->getID()), $this->withParams);
  834. $beans = $redbean->find($type, array(), array(" $myFieldLink = ? ".$this->withSql, $params));
  835. }
  836. $this->withSql = '';
  837. $this->withParams = array();
  838. foreach($beans as $b) {
  839. $b->__info['sys.parentcache.'.$parentField] = $this;
  840. }
  841. $this->properties[$property] = $beans;
  842. $this->__info['sys.shadow.'.$property] = $beans;
  843. $this->__info['tainted'] = true;
  844. return $this->properties[$property];
  845. }
  846. elseif (strpos($property, 'shared') === 0 && ctype_upper(substr($property, 6, 1))) {
  847. $type = lcfirst(substr($property, 6));
  848. if (self::$flagUseBeautyfulColumnnames ) {
  849. $type = $this->beau($type);
  850. }
  851. $keys = $redbean->getAssociationManager()->related($this, $type);
  852. if (!count($keys)) $beans = array(); else
  853. if (trim($this->withSql) !== '') {
  854. $beans = $redbean->find($type, array('id' => $keys), array($this->withSql, $this->withParams), true);
  855. } else {
  856. $beans = $redbean->batch($type, $keys);
  857. }
  858. $this->withSql = '';
  859. $this->withParams = array();
  860. $this->properties[$property] = $beans;
  861. $this->__info['sys.shadow.'.$property] = $beans;
  862. $this->__info['tainted'] = true;
  863. return $this->properties[$property];
  864. } else {
  865. $null = null;
  866. return $null;
  867. }
  868. } else {
  869. return $this->properties[$property];
  870. }
  871. }
  872. /**
  873. * Magic Setter. Sets the value for a specific property.
  874. * This setter acts as a hook for OODB to mark beans as tainted.
  875. * The tainted meta property can be retrieved using getMeta("tainted").
  876. * The tainted meta property indicates whether a bean has been modified and
  877. * can be used in various caching mechanisms.
  878. * @param string $property
  879. * @param mixed $value
  880. */
  881. public function __set($property, $value) {
  882. if (self::$flagUseBeautyfulColumnnames) {
  883. $property = $this->beau($property);
  884. }
  885. $this->flagSkipBeau = true;
  886. $this->__get($property);
  887. $this->flagSkipBeau = false;
  888. $this->setMeta('tainted', true);
  889. $linkField = $property.'_id';
  890. if (isset($this->properties[$linkField]) && !($value instanceof RedBean_OODBBean)) {
  891. if (is_null($value) || $value === false) {
  892. return $this->__unset($property);
  893. } else {
  894. throw new RedBean_Exception_Security('Cannot cast to bean.');
  895. }
  896. }
  897. if ($value === false) {
  898. $value = '0';
  899. } elseif ($value === true) {
  900. $value = '1';
  901. } elseif ($value instanceof DateTime) {
  902. $value = $value->format('Y-m-d H:i:s');
  903. }
  904. $this->properties[$property] = $value;
  905. }
  906. /**
  907. * Sets a property directly, for internal use only.
  908. *
  909. * @param string $property property
  910. * @param mixed $value value
  911. */
  912. public function setProperty($property, $value) {
  913. $this->properties[$property] = $value;
  914. }
  915. /**
  916. * Returns the value of a meta property. A meta property
  917. * contains extra information about the bean object that will not
  918. * get stored in the database. Meta information is used to instruct
  919. * RedBean as well as other systems how to deal with the bean.
  920. * For instance: $bean->setMeta("buildcommand.unique", array(
  921. * array("column1", "column2", "column3") ) );
  922. * Will add a UNIQUE constaint for the bean on columns: column1, column2 and
  923. * column 3.
  924. * To access a Meta property we use a dot separated notation.
  925. * If the property cannot be found this getter will return NULL instead.
  926. *
  927. * @param string $path path
  928. * @param mixed $default default value
  929. *
  930. * @return mixed $value
  931. */
  932. public function getMeta($path, $default = NULL) {
  933. return (isset($this->__info[$path])) ? $this->__info[$path] : $default;
  934. }
  935. /**
  936. * Stores a value in the specified Meta information property. $value contains
  937. * the value you want to store in the Meta section of the bean and $path
  938. * specifies the dot separated path to the property. For instance "my.meta.property".
  939. * If "my" and "meta" do not exist they will be created automatically.
  940. *
  941. * @param string $path path
  942. * @param mixed $value value
  943. */
  944. public function setMeta($path, $value) {
  945. $this->__info[$path] = $value;
  946. }
  947. /**
  948. * Copies the meta information of the specified bean
  949. * This is a convenience method to enable you to
  950. * exchange meta information easily.
  951. *
  952. * @param RedBean_OODBBean $bean
  953. *
  954. * @return RedBean_OODBBean
  955. */
  956. public function copyMetaFrom(RedBean_OODBBean $bean) {
  957. $this->__info = $bean->__info;
  958. return $this;
  959. }
  960. /**
  961. * Reroutes a call to Model if exists. (new fuse)
  962. *
  963. * @param string $method
  964. * @param array $args
  965. *
  966. * @return mixed $mixed
  967. */
  968. public function __call($method, $args) {
  969. if (!isset($this->__info['model'])) {
  970. $model = $this->beanHelper->getModelForBean($this);
  971. if (!$model) return;
  972. $this->__info['model'] = $model;
  973. }
  974. if (!method_exists($this->__info['model'], $method)) return null;
  975. return call_user_func_array(array($this->__info['model'], $method), $args);
  976. }
  977. /**
  978. * Implementation of __toString Method
  979. * Routes call to Model.
  980. *
  981. * @return string $string
  982. */
  983. public function __toString() {
  984. $string = $this->__call('__toString', array());
  985. if ($string === null) {
  986. return json_encode($this->properties);
  987. } else {
  988. return $string;
  989. }
  990. }
  991. /**
  992. * Implementation of Array Access Interface, you can access bean objects
  993. * like an array.
  994. * Call gets routed to __set.
  995. *
  996. * @param mixed $offset offset string
  997. * @param mixed $value value
  998. *
  999. * @return void
  1000. */
  1001. public function offsetSet($offset, $value) {
  1002. $this->__set($offset, $value);
  1003. }
  1004. /**
  1005. * Implementation of Array Access Interface, you can access bean objects
  1006. * like an array.
  1007. *
  1008. * @param mixed $offset property
  1009. *
  1010. * @return
  1011. */
  1012. public function offsetExists($offset) {
  1013. return isset($this->properties[$offset]);
  1014. }
  1015. /**
  1016. * Implementation of Array Access Interface, you can access bean objects
  1017. * like an array.
  1018. * Unsets a value from the array/bean.
  1019. *
  1020. * @param mixed $offset property
  1021. *
  1022. * @return
  1023. */
  1024. public function offsetUnset($offset) {
  1025. unset($this->properties[$offset]);
  1026. }
  1027. /**
  1028. * Implementation of Array Access Interface, you can access bean objects
  1029. * like an array.
  1030. * Returns value of a property.
  1031. *
  1032. * @param mixed $offset property
  1033. *
  1034. * @return
  1035. */
  1036. public function offsetGet($offset) {
  1037. return $this->__get($offset);
  1038. }
  1039. /**
  1040. * Chainable method to cast a certain ID to a bean; for instance:
  1041. * $person = $club->fetchAs('person')->member;
  1042. * This will load a bean of type person using member_id as ID.
  1043. *
  1044. * @param string $type preferred fetch type
  1045. *
  1046. * @return RedBean_OODBBean
  1047. */
  1048. public function fetchAs($type) {
  1049. $this->fetchType = $type;
  1050. return $this;
  1051. }
  1052. /**
  1053. * For polymorphic bean relations.
  1054. * Same as fetchAs but uses a column instead of a direct value.
  1055. *
  1056. * @param string $column
  1057. *
  1058. * @return RedBean_OODBean
  1059. *
  1060. */
  1061. public function poly($field) {
  1062. return $this->fetchAs($this->$field);
  1063. }
  1064. /**
  1065. * Implementation of Countable interface. Makes it possible to use
  1066. * count() function on a bean.
  1067. *
  1068. * @return integer $numberOfProperties number of properties in the bean.
  1069. */
  1070. public function count() {
  1071. return count($this->properties);
  1072. }
  1073. /**
  1074. * Checks wether a bean is empty or not.
  1075. * A bean is empty if it has no other properties than the id field OR
  1076. * if all the other property are empty().
  1077. *
  1078. * @return boolean
  1079. */
  1080. public function isEmpty() {
  1081. $empty = true;
  1082. foreach($this->properties as $key => $value) {
  1083. if ($key == 'id') continue;
  1084. if (!empty($value)) {
  1085. $empty = false;
  1086. }
  1087. }
  1088. return $empty;
  1089. }
  1090. /**
  1091. * Chainable setter.
  1092. *
  1093. * @param string $property the property of the bean
  1094. * @param mixed $value the value you want to set
  1095. *
  1096. * @return RedBean_OODBBean the bean
  1097. */
  1098. public function setAttr($property, $value) {
  1099. $this->$property = $value;
  1100. return $this;
  1101. }
  1102. /**
  1103. * Comfort method.
  1104. * Unsets all properties in array.
  1105. *
  1106. * @param array $properties properties you want to unset.
  1107. *
  1108. * @return RedBean_OODBBean
  1109. */
  1110. public function unsetAll($properties) {
  1111. foreach($properties as $prop) {
  1112. if (isset($this->properties[$prop])) {
  1113. unset($this->properties[$prop]);
  1114. }
  1115. }
  1116. return $this;
  1117. }
  1118. /**
  1119. * Returns original (old) value of a property.
  1120. * You can use this method to see what has changed in a
  1121. * bean.
  1122. *
  1123. * @param string $property name of the property you want the old value of
  1124. *
  1125. * @return mixed
  1126. */
  1127. public function old($property) {
  1128. $old = $this->getMeta('sys.orig', array());
  1129. if (isset($old[$property])) {
  1130. return $old[$property];
  1131. }
  1132. }
  1133. /**
  1134. * Convenience method.
  1135. * Returns true if the bean has been changed, or false otherwise.
  1136. * Same as $bean->getMeta('tainted');
  1137. * Note that a bean becomes tainted as soon as you retrieve a list from
  1138. * the bean. This is because the bean lists are arrays and the bean cannot
  1139. * determine whether you have made modifications to a list so RedBeanPHP
  1140. * will mark the whole bean as tainted.
  1141. *
  1142. * @return boolean
  1143. */
  1144. public function isTainted() {
  1145. return $this->getMeta('tainted');
  1146. }
  1147. /**
  1148. * Returns TRUE if the value of a certain property of the bean has been changed and
  1149. * FALSE otherwise.
  1150. *
  1151. * @param string $property name of the property you want the change-status of
  1152. *
  1153. * @return boolean
  1154. */
  1155. public function hasChanged($property) {
  1156. if (!isset($this->properties[$property])) return false;
  1157. return ($this->old($property) != $this->properties[$property]);
  1158. }
  1159. /**
  1160. * Creates a N-M relation by linking an intermediate bean.
  1161. * This method can be used to quickly connect beans using indirect
  1162. * relations. For instance, given an album and a song you can connect the two
  1163. * using a track with a number like this:
  1164. *
  1165. * Usage:
  1166. *
  1167. * $album->link('track', array('number'=>1))->song = $song;
  1168. *
  1169. * or:
  1170. *
  1171. * $album->link($trackBean)->song = $song;
  1172. *
  1173. * What this method does is adding the link bean to the own-list, in this case
  1174. * ownTrack. If the first argument is a string and the second is an array or
  1175. * a JSON string then the linking bean gets dispensed on-the-fly as seen in
  1176. * example #1. After preparing the linking bean, the bean is returned thus
  1177. * allowing the chained setter: ->song = $song.
  1178. *
  1179. * @param string|RedBean_OODBBean $type type of bean to dispense or the full bean
  1180. * @param string|array $qualification JSON string or array (optional)
  1181. */
  1182. public function link($typeOrBean, $qualification = array()) {
  1183. if (is_string($typeOrBean)) {
  1184. $bean = $this->beanHelper->getToolBox()->getRedBean()->dispense($typeOrBean);
  1185. if (is_string($qualification)) {
  1186. $data = json_decode($qualification, true);
  1187. } else {
  1188. $data = $qualification;
  1189. }
  1190. foreach($data as $key => $value) {
  1191. $bean->$key = $value;
  1192. }
  1193. } else {
  1194. $bean = $typeOrBean;
  1195. }
  1196. $list = 'own'.ucfirst($bean->getMeta('type'));
  1197. array_push($this->$list, $bean);
  1198. return $bean;
  1199. }
  1200. }
  1201. abstract class RedBean_Observable {
  1202. /**
  1203. * @var array
  1204. */
  1205. private $observers = array();
  1206. /**
  1207. * Implementation of the Observer Pattern.
  1208. *
  1209. * @param string $eventname event
  1210. * @param RedBean_Observer $observer observer
  1211. *
  1212. * @return void
  1213. */
  1214. public function addEventListener($eventname, RedBean_Observer $observer) {
  1215. if (!isset($this->observers[$eventname])) {
  1216. $this->observers[$eventname] = array();
  1217. }
  1218. foreach($this->observers[$eventname] as $o) if ($o == $observer) return;
  1219. $this->observers[$eventname][] = $observer;
  1220. }
  1221. /**
  1222. * Notifies listeners.
  1223. *
  1224. * @param string $eventname eventname
  1225. * @param mixed $info info
  1226. * @return unknown_ty
  1227. */
  1228. public function signal($eventname, $info) {
  1229. if (!isset($this->observers[ $eventname ])) $this->observers[$eventname] = array();
  1230. foreach($this->observers[$eventname] as $observer) $observer->onEvent($eventname, $info);
  1231. }
  1232. }
  1233. interface RedBean_Observer {
  1234. /**
  1235. * @param string $eventname
  1236. * @param RedBean_OODBBean mixed $info
  1237. */
  1238. public function onEvent($eventname, $bean);
  1239. }
  1240. interface RedBean_Adapter {
  1241. /**
  1242. * Returns the latest SQL statement
  1243. *
  1244. * @return string $SQLString SQLString
  1245. */
  1246. public function getSQL();
  1247. /**
  1248. * Executes an SQL Statement using an array of values to bind
  1249. * If $noevent is TRUE then this function will not signal its
  1250. * observers to notify about the SQL execution; this to prevent
  1251. * infinite recursion when using observers.
  1252. *
  1253. * @param string $sql SQL
  1254. * @param array $aValues values
  1255. * @param boolean $noevent no event firing
  1256. */
  1257. public function exec($sql , $aValues = array(), $noevent = false);
  1258. /**
  1259. * Executes an SQL Query and returns a resultset.
  1260. * This method returns a multi dimensional resultset similar to getAll
  1261. * The values array can be used to bind values to the place holders in the
  1262. * SQL query.
  1263. *
  1264. * @param string $sql SQL
  1265. * @param array $aValues values
  1266. */
  1267. public function get($sql, $aValues = array());
  1268. /**
  1269. * Executes an SQL Query and returns a resultset.
  1270. * This method returns a single row (one array) resultset.
  1271. * The values array can be used to bind values to the place holders in the
  1272. * SQL query.
  1273. *
  1274. * @param string $sql SQL
  1275. * @param array $aValues values to bind
  1276. *
  1277. * @return array $aMultiDimArray row
  1278. */
  1279. public function getRow($sql, $aValues = array());
  1280. /**
  1281. * Executes an SQL Query and returns a resultset.
  1282. * This method returns a single column (one array) resultset.
  1283. * The values array can be used to bind values to the place holders in the
  1284. * SQL query.
  1285. *
  1286. * @param string $sql SQL
  1287. * @param array $aValues values to bind
  1288. *
  1289. * @return array $aSingleDimArray column
  1290. */
  1291. public function getCol($sql, $aValues = array());
  1292. /**
  1293. * Executes an SQL Query and returns a resultset.
  1294. * This method returns a single cell, a scalar value as the resultset.
  1295. * The values array can be used to bind values to the place holders in the
  1296. * SQL query.
  1297. *
  1298. * @param string $sql SQL
  1299. * @param array $aValues values to bind
  1300. *
  1301. * @return string $sSingleValue value from cell
  1302. */
  1303. public function getCell($sql, $aValues = array());
  1304. /**
  1305. * Executes the SQL query specified in $sql and takes
  1306. * the first two columns of the resultset. This function transforms the
  1307. * resultset into an associative array. Values from the the first column will
  1308. * serve as keys while the values of the second column will be used as values.
  1309. * The values array can be used to bind values to the place holders in the
  1310. * SQL query.
  1311. *
  1312. * @param string $sql SQL
  1313. * @param array $values values to bind
  1314. *
  1315. * @return array $associativeArray associative array result set
  1316. */
  1317. public function getAssoc($sql, $values = array());
  1318. /**
  1319. * Returns the latest insert ID.
  1320. *
  1321. * @return integer $id primary key ID
  1322. */
  1323. public function getInsertID();
  1324. /**
  1325. * Returns the number of rows that have been
  1326. * affected by the last update statement.
  1327. *
  1328. * @return integer $count number of rows affected
  1329. */
  1330. public function getAffectedRows();
  1331. /**
  1332. * Returns the original database resource. This is useful if you want to
  1333. * perform operations on the driver directly instead of working with the
  1334. * adapter. RedBean will only access the adapter and never to talk
  1335. * directly to the driver though.
  1336. *
  1337. * @return object $driver driver
  1338. */
  1339. public function getDatabase();
  1340. /**
  1341. * This method is part of the RedBean Transaction Management
  1342. * mechanisms.
  1343. * Starts a transaction.
  1344. */
  1345. public function startTransaction();
  1346. /**
  1347. * This method is part of the RedBean Transaction Management
  1348. * mechanisms.
  1349. * Commits the transaction.
  1350. */
  1351. public function commit();
  1352. /**
  1353. * This method is part of the RedBean Transaction Management
  1354. * mechanisms.
  1355. * Rolls back the transaction.
  1356. */
  1357. public function rollback();
  1358. /**
  1359. * Closes database connection.
  1360. */
  1361. public function close();
  1362. }
  1363. class RedBean_Adapter_DBAdapter extends RedBean_Observable implements RedBean_Adapter {
  1364. private $db = null;
  1365. private $sql = '';
  1366. /**
  1367. * Constructor.
  1368. * Creates an instance of the RedBean Adapter Class.
  1369. * This class provides an interface for RedBean to work
  1370. * with ADO compatible DB instances.
  1371. *
  1372. * @param RedBean_Driver $database ADO Compatible DB Instance
  1373. */
  1374. public function __construct($database) {
  1375. $this->db = $database;
  1376. }
  1377. /**
  1378. * @see RedBean_Adapter::getSQL
  1379. */
  1380. public function getSQL() {
  1381. return $this->sql;
  1382. }
  1383. /**
  1384. * @see RedBean_Adapter::exec
  1385. */
  1386. public function exec($sql, $aValues = array(), $noevent = false) {
  1387. if (!$noevent) {
  1388. $this->sql = $sql;
  1389. $this->signal('sql_exec', $this);
  1390. }
  1391. return $this->db->Execute($sql, $aValues);
  1392. }
  1393. /**
  1394. * @see RedBean_Adapter::get
  1395. */
  1396. public function get($sql, $aValues = array()) {
  1397. $this->sql = $sql;
  1398. $this->signal('sql_exec', $this);
  1399. return $this->db->GetAll($sql, $aValues);
  1400. }
  1401. /**
  1402. * @see RedBean_Adapter::getRow
  1403. */
  1404. public function getRow($sql, $aValues = array()) {
  1405. $this->sql = $sql;
  1406. $this->signal('sql_exec', $this);
  1407. return $this->db->GetRow($sql, $aValues);
  1408. }
  1409. /**
  1410. * @see RedBean_Adapter::getCol
  1411. */
  1412. public function getCol($sql, $aValues = array()) {
  1413. $this->sql = $sql;
  1414. $this->signal('sql_exec', $this);
  1415. return $this->db->GetCol($sql, $aValues);
  1416. }
  1417. /**
  1418. * @see RedBean_Adapter::getAssoc
  1419. */
  1420. public function getAssoc($sql, $aValues = array()) {
  1421. $this->sql = $sql;
  1422. $this->signal('sql_exec', $this);
  1423. $rows = $this->db->GetAll($sql, $aValues);
  1424. $assoc = array();
  1425. if ($rows) {
  1426. foreach($rows as $row) {
  1427. if (is_array($row) && count($row)>0) {
  1428. if (count($row)>1) {
  1429. $key = array_shift($row);
  1430. $value = array_shift($row);
  1431. }
  1432. elseif (count($row) == 1) {
  1433. $key = array_shift($row);
  1434. $value = $key;
  1435. }
  1436. $assoc[$key] = $value;
  1437. }
  1438. }
  1439. }
  1440. return $assoc;
  1441. }
  1442. /**
  1443. * @see RedBean_Adapter::getCell
  1444. */
  1445. public function getCell($sql, $aValues = array(), $noSignal = null) {
  1446. $this->sql = $sql;
  1447. if (!$noSignal) $this->signal('sql_exec', $this);
  1448. $arr = $this->db->getCol($sql, $aValues);
  1449. if ($arr && is_array($arr)) return ($arr[0]); else return false;
  1450. }
  1451. /**
  1452. * @see RedBean_Adapter::getInsertID
  1453. */
  1454. public function getInsertID() {
  1455. return $this->db->getInsertID();
  1456. }
  1457. /**
  1458. * @see RedBean_Adapter::getAffectedRows
  1459. */
  1460. public function getAffectedRows() {
  1461. return $this->db->Affected_Rows();
  1462. }
  1463. /**
  1464. * @see RedBean_Adapter::getDatabase
  1465. */
  1466. public function getDatabase() {
  1467. return $this->db;
  1468. }
  1469. /**
  1470. * @see RedBean_Adapter::startTransaction
  1471. */
  1472. public function startTransaction() {
  1473. return $this->db->StartTrans();
  1474. }
  1475. /**
  1476. * @see RedBean_Adapter::commit
  1477. */
  1478. public function commit() {
  1479. return $this->db->CommitTrans();
  1480. }
  1481. /**
  1482. * @see RedBean_Adapter::rollback
  1483. */
  1484. public function rollback() {
  1485. return $this->db->FailTrans();
  1486. }
  1487. /**
  1488. * @see RedBean_Adapter::close.
  1489. */
  1490. public function close() {
  1491. $this->db->close();
  1492. }
  1493. }
  1494. interface RedBean_QueryWriter {
  1495. /**
  1496. * Query Writer constants.
  1497. */
  1498. const C_SQLSTATE_NO_SUCH_TABLE = 1;
  1499. const C_SQLSTATE_NO_SUCH_COLUMN = 2;
  1500. const C_SQLSTATE_INTEGRITY_CONSTRAINT_VIOLATION = 3;
  1501. /**
  1502. * Returns the tables that are in the database.
  1503. *
  1504. * @return array $arrayOfTables list of tables
  1505. */
  1506. public function getTables();
  1507. /**
  1508. * This method will create a table for the bean.
  1509. * This methods accepts a type and infers the corresponding table name.
  1510. *
  1511. * @param string $type type of bean you want to create a table for
  1512. *
  1513. * @return void
  1514. */
  1515. public function createTable($type);
  1516. /**
  1517. * Returns an array containing all the columns of the specified type.
  1518. * The format of the return array looks like this:
  1519. * $field => $type where $field is the name of the column and $type
  1520. * is a database specific description of the datatype.
  1521. *
  1522. * This methods accepts a type and infers the corresponding table name.
  1523. *
  1524. * @param string $type type of bean you want to obtain a column list of
  1525. *
  1526. * @return array $listOfColumns list of columns ($field=>$type)
  1527. */
  1528. public function getColumns($type);
  1529. /**
  1530. * Returns the Column Type Code (integer) that corresponds
  1531. * to the given value type. This method is used to determine the minimum
  1532. * column type required to represent the given value.
  1533. *
  1534. * @param string $value value
  1535. *
  1536. * @return integer $type type
  1537. */
  1538. public function scanType($value, $alsoScanSpecialForTypes = false);
  1539. /**
  1540. * This method will add a column to a table.
  1541. * This methods accepts a type and infers the corresponding table name.
  1542. *
  1543. * @param string $type name of the table
  1544. * @param string $column name of the column
  1545. * @param integer $field data type for field
  1546. *
  1547. * @return void
  1548. *
  1549. */
  1550. public function addColumn($type, $column, $field);
  1551. /**
  1552. * Returns the Type Code for a Column Description.
  1553. * Given an SQL column description this method will return the corresponding
  1554. * code for the writer. If the include specials flag is set it will also
  1555. * return codes for special columns. Otherwise special columns will be identified
  1556. * as specified columns.
  1557. *
  1558. * @param string $typedescription description
  1559. * @param boolean $includeSpecials whether you want to get codes for special columns as well
  1560. *
  1561. * @return integer $typecode code
  1562. */
  1563. public function code($typedescription, $includeSpecials = false);
  1564. /**
  1565. * This method will widen the column to the specified data type.
  1566. * This methods accepts a type and infers the corresponding table name.
  1567. *
  1568. * @param string $type type / table that needs to be adjusted
  1569. * @param string $column column that needs to be altered
  1570. * @param integer $datatype target data type
  1571. *
  1572. * @return void
  1573. */
  1574. public function widenColumn($type, $column, $datatype);
  1575. /**
  1576. * This method should update (or insert a record), it takes
  1577. * a table name, a list of update values ( $field => $value ) and an
  1578. * primary key ID (optional). If no primary key ID is provided, an
  1579. * INSERT will take place.
  1580. * Returns the new ID.
  1581. * This methods accepts a type and infers the corresponding table name.
  1582. *
  1583. * @param string $type name of the table to update
  1584. * @param array $updatevalues list of update values
  1585. * @param integer $id optional primary key ID value
  1586. *
  1587. * @return integer $id the primary key ID value of the new record
  1588. */
  1589. public function updateRecord($type, $updatevalues, $id = null);
  1590. /**
  1591. * This method selects a record. You can provide a
  1592. * collection of conditions using the following format:
  1593. * array( $field1 => array($possibleValue1, $possibleValue2,... $possibleValueN ),
  1594. * ...$fieldN=>array(...));
  1595. * Also, additional SQL can be provided. This SQL snippet will be appended to the
  1596. * query string. If the $delete parameter is set to TRUE instead of selecting the
  1597. * records they will be deleted.
  1598. * This methods accepts a type and infers the corresponding table name.
  1599. *
  1600. * @throws Exception
  1601. * @param string $type type of bean to select records from
  1602. * @param array $cond conditions using the specified format
  1603. * @param string $asql additional sql
  1604. * @param boolean $delete IF TRUE delete records (optional)
  1605. * @param boolean $inverse IF TRUE inverse the selection (optional)
  1606. * @param boolean $all IF TRUE suppress WHERE keyword, omitting WHERE clause
  1607. *
  1608. * @return array $records selected records
  1609. */
  1610. public function selectRecord($type, $conditions, $addSql = null, $delete = false, $inverse = false);
  1611. /**
  1612. * This method will add a UNIQUE constraint index to a table on columns $columns.
  1613. * This methods accepts a type and infers the corresponding table name.
  1614. *
  1615. * @param string $type type
  1616. * @param array $columnsPartOfIndex columns to include in index
  1617. *
  1618. * @return void
  1619. */
  1620. public function addUniqueIndex($type, $columns);
  1621. /**
  1622. * This method will check whether the SQL state is in the list of specified states
  1623. * and returns true if it does appear in this list or false if it
  1624. * does not. The purpose of this method is to translate the database specific state to
  1625. * a one of the constants defined in this class and then check whether it is in the list
  1626. * of standard states provided.
  1627. *
  1628. * @param string $state sql state
  1629. * @param array $list list
  1630. *
  1631. * @return boolean $isInList
  1632. */
  1633. public function sqlStateIn($state, $list);
  1634. /**
  1635. * This method will remove all beans of a certain type.
  1636. * This methods accepts a type and infers the corresponding table name.
  1637. *
  1638. * @param string $type bean type
  1639. *
  1640. * @return void
  1641. */
  1642. public function wipe($type);
  1643. /**
  1644. * This method will count the number of beans of the given type.
  1645. * This methods accepts a type and infers the corresponding table name.
  1646. *
  1647. * @param string $type type of bean to count
  1648. *
  1649. * @return integer $numOfBeans number of beans found
  1650. */
  1651. public function count($type);
  1652. /**
  1653. * This method will add a constraint. If one of the beans gets trashed
  1654. * the other, related bean will be removed as well.
  1655. *
  1656. * @param RedBean_OODBBean $bean1 first bean
  1657. * @param RedBean_OODBBean $bean2 second bean
  1658. *
  1659. * @return void
  1660. */
  1661. public function addConstraint(RedBean_OODBBean $bean1, RedBean_OODBBean $bean2);
  1662. /**
  1663. * This method will add a foreign key from type and field to
  1664. * target type and target field.
  1665. * The foreign key is created without an action. On delete/update
  1666. * no action will be triggered. The FK is only used to allow database
  1667. * tools to generate pretty diagrams and to make it easy to add actions
  1668. * later on.
  1669. * This methods accepts a type and infers the corresponding table name.
  1670. *
  1671. *
  1672. * @param string $type type that will have a foreign key field
  1673. * @param string $targetType points to this type
  1674. * @param string $field field that contains the foreign key value
  1675. * @param string $targetField field where the fk points to
  1676. *
  1677. * @return void
  1678. */
  1679. public function addFK($type, $targetType, $field, $targetField);
  1680. /**
  1681. * This method will add an index to a type and field with name
  1682. * $name.
  1683. * This methods accepts a type and infers the corresponding table name.
  1684. *
  1685. * @param $type type to add index to
  1686. * @param $name name of the new index
  1687. * @param $column field to index
  1688. *
  1689. * @return void
  1690. */
  1691. public function addIndex($type, $name, $column);
  1692. /**
  1693. * Checks and filters a database structure element like a table of column
  1694. * for safe use in a query. A database structure has to conform to the
  1695. * RedBeanPHP DB security policy which basically means only alphanumeric
  1696. * symbols are allowed. This security policy is more strict than conventional
  1697. * SQL policies and does therefore not require database specific escaping rules.
  1698. *
  1699. * @param string $databaseStructure name of the column/table to check
  1700. * @param boolean $noQuotes TRUE to NOT put backticks or quotes around the string
  1701. *
  1702. * @return string
  1703. */
  1704. public function esc($databaseStructure, $dontQuote = false);
  1705. /**
  1706. * Removes all tables and views from the database.
  1707. */
  1708. public function wipeAll();
  1709. }
  1710. abstract class RedBean_QueryWriter_AQueryWriter {
  1711. /**
  1712. * @var array
  1713. */
  1714. public $typeno_sqltype = array();
  1715. /**
  1716. * @var RedBean_Adapter_DBAdapter
  1717. */
  1718. protected $adapter;
  1719. /**
  1720. * @var string
  1721. */
  1722. protected $defaultValue = 'NULL';
  1723. /**
  1724. * @var string
  1725. */
  1726. protected $quoteCharacter = '';
  1727. /**
  1728. * @var boolean
  1729. */
  1730. protected $flagUseCache = false;
  1731. /**
  1732. * @var array
  1733. */
  1734. protected $cache = array();
  1735. /**
  1736. * @var array
  1737. */
  1738. protected static $renames = array();
  1739. /**
  1740. * Returns the sql that should follow an insert statement.
  1741. *
  1742. * @param string $table name
  1743. *
  1744. * @return string sql
  1745. */
  1746. protected function getInsertSuffix ($table) {
  1747. return '';
  1748. }
  1749. /**
  1750. * @see RedBean_QueryWriter::esc
  1751. */
  1752. public function esc($dbStructure, $dontQuote = false) {
  1753. $this->check($dbStructure);
  1754. return ($dontQuote) ? $dbStructure : $this->quoteCharacter.$dbStructure.$this->quoteCharacter;
  1755. }
  1756. /**
  1757. * Checks table name or column name.
  1758. *
  1759. * @param string $table table string
  1760. *
  1761. * @return string $table escaped string
  1762. */
  1763. protected function check($struct) {
  1764. if (!preg_match('/^[a-zA-Z0-9_]+$/', $struct)) {
  1765. throw new RedBean_Exception_Security('Identifier does not conform to RedBeanPHP security policies.');
  1766. }
  1767. return $struct;
  1768. }
  1769. /**
  1770. * @see RedBean_QueryWriter::addColumn
  1771. */
  1772. public function addColumn($type, $column, $field) {
  1773. $table = $type;
  1774. $type = $field;
  1775. $table = $this->esc($table);
  1776. $column = $this->esc($column);
  1777. $type = (isset($this->typeno_sqltype[$type])) ? $this->typeno_sqltype[$type] : '';
  1778. $sql = "ALTER TABLE $table ADD $column $type ";
  1779. $this->adapter->exec($sql);
  1780. }
  1781. /**
  1782. * @see RedBean_QueryWriter::updateRecord
  1783. */
  1784. public function updateRecord($type, $updatevalues, $id = null) {
  1785. $table = $type;
  1786. if (!$id) {
  1787. $insertcolumns = $insertvalues = array();
  1788. foreach($updatevalues as $pair) {
  1789. $insertcolumns[] = $pair['property'];
  1790. $insertvalues[] = $pair['value'];
  1791. }
  1792. return $this->insertRecord($table, $insertcolumns, array($insertvalues));
  1793. }
  1794. if ($id && !count($updatevalues)) return $id;
  1795. $table = $this->esc($table);
  1796. $sql = "UPDATE $table SET ";
  1797. $p = $v = array();
  1798. foreach($updatevalues as $uv) {
  1799. $p[] = " {$this->esc($uv["property"])} = ? ";
  1800. $v[] = $uv['value'];
  1801. }
  1802. $sql .= implode(',', $p).' WHERE id = '.intval($id);
  1803. $this->adapter->exec($sql, $v);
  1804. return $id;
  1805. }
  1806. /**
  1807. * Inserts a record into the database using a series of insert columns
  1808. * and corresponding insertvalues. Returns the insert id.
  1809. *
  1810. * @param string $table table to perform query on
  1811. * @param array $insertcolumns columns to be inserted
  1812. * @param array $insertvalues values to be inserted
  1813. *
  1814. * @return integer $insertid insert id from driver, new record id
  1815. */
  1816. protected function insertRecord($table, $insertcolumns, $insertvalues) {
  1817. $default = $this->defaultValue;
  1818. $suffix = $this->getInsertSuffix($table);
  1819. $table = $this->esc($table);
  1820. if (count($insertvalues)>0 && is_array($insertvalues[0]) && count($insertvalues[0])>0) {
  1821. foreach($insertcolumns as $k => $v) {
  1822. $insertcolumns[$k] = $this->esc($v);
  1823. }
  1824. $insertSQL = "INSERT INTO $table ( id, ".implode(',', $insertcolumns)." ) VALUES
  1825. ( $default, ". implode(',', array_fill(0, count($insertcolumns), ' ? '))." ) $suffix";
  1826. foreach($insertvalues as $i => $insertvalue) {
  1827. $ids[] = $this->adapter->getCell($insertSQL, $insertvalue, $i);
  1828. }
  1829. $result = count($ids) === 1 ? array_pop($ids) : $ids;
  1830. } else {
  1831. $result = $this->adapter->getCell("INSERT INTO $table (id) VALUES($default) $suffix");
  1832. }
  1833. if ($suffix) return $result;
  1834. $last_id = $this->adapter->getInsertID();
  1835. return $last_id;
  1836. }
  1837. /**
  1838. * @see RedBean_QueryWriter::selectRecord
  1839. */
  1840. public function selectRecord($type, $conditions, $addSql = null, $delete = null, $inverse = false, $all = false) {
  1841. if (!is_array($conditions)) throw new Exception('Conditions must be an array');
  1842. if (!$delete && $this->flagUseCache) {
  1843. $key = serialize(array($type, $conditions, $addSql, $inverse, $all));
  1844. $sql = $this->adapter->getSQL();
  1845. if (strpos($sql, '-- keep-cache') !== strlen($sql)-13) {
  1846. //If SQL has been taken place outside of this method then something else then
  1847. //a select query might have happened! (or instruct to keep cache)
  1848. $this->cache = array();
  1849. } else {
  1850. if (isset($this->cache[$key])) return $this->cache[$key];
  1851. }
  1852. }
  1853. $table = $this->esc($type);
  1854. $sqlConditions = array();
  1855. $bindings = array();
  1856. foreach($conditions as $column => $values) {
  1857. if (!count($values)) continue;
  1858. $sql = $this->esc($column);
  1859. $sql .= ' '.($inverse ? ' NOT ':'').' IN ( ';
  1860. //If its safe to not use bindings please do... (fixes SQLite PDO issue limit 256 bindings)
  1861. if (is_array($conditions)
  1862. && count($conditions) === 1
  1863. && isset($conditions['id'])
  1864. && is_array($values)
  1865. && preg_match('/^\d+$/', implode('', $values))) {
  1866. $sql .= implode(',', $values).') ';
  1867. $sqlConditions[] = $sql;
  1868. } else {
  1869. $sql .= implode(',', array_fill(0, count($values), '?')).') ';
  1870. $sqlConditions[] = $sql;
  1871. if (!is_array($values)) $values = array($values);
  1872. foreach($values as $k => $v) {
  1873. $values[$k] = strval($v);
  1874. }
  1875. $bindings = array_merge($bindings, $values);
  1876. }
  1877. }
  1878. if (is_array($addSql)) {
  1879. if (count($addSql)>1) {
  1880. $bindings = array_merge($bindings, $addSql[1]);
  1881. } else {
  1882. $bindings = array();
  1883. }
  1884. $addSql = $addSql[0];
  1885. }
  1886. $sql = '';
  1887. if (is_array($sqlConditions) && count($sqlConditions)>0) {
  1888. $sql = implode(' AND ', $sqlConditions);
  1889. $sql = " WHERE ( $sql ) ";
  1890. if ($addSql) $sql .= ($all ? '': ' AND ') . " $addSql ";
  1891. }
  1892. elseif ($addSql) {
  1893. if ($all) {
  1894. $sql = " $addSql ";
  1895. } else {
  1896. $sql = " WHERE $addSql ";
  1897. }
  1898. }
  1899. $sql = (($delete) ? 'DELETE FROM ' : 'SELECT * FROM ').$table.$sql;
  1900. $rows = $this->adapter->get($sql.(($delete) ? '' : ' -- keep-cache'), $bindings);
  1901. if (!$delete && $this->flagUseCache) {
  1902. $this->cache[$key] = $rows;
  1903. }
  1904. return $rows;
  1905. }
  1906. /**
  1907. * @see RedBean_QueryWriter::wipe
  1908. */
  1909. public function wipe($type) {
  1910. $table = $this->esc($type);
  1911. $this->adapter->exec("TRUNCATE $table ");
  1912. }
  1913. /**
  1914. * @see RedBean_QueryWriter::count
  1915. */
  1916. public function count($beanType, $addSQL = '', $params = array()) {
  1917. $sql = "SELECT count(*) FROM {$this->esc($beanType)} ";
  1918. if ($addSQL != '') $addSQL = ' WHERE '.$addSQL;
  1919. return (int) $this->adapter->getCell($sql.$addSQL, $params);
  1920. }
  1921. /**
  1922. * Checks whether a number can be treated like an int.
  1923. *
  1924. * @param string $value string representation of a certain value
  1925. *
  1926. * @return boolean $value boolean result of analysis
  1927. */
  1928. public static function canBeTreatedAsInt($value) {
  1929. return (boolean) (ctype_digit(strval($value)) && strval($value) === strval(intval($value)));
  1930. }
  1931. /**
  1932. * @see RedBean_QueryWriter::addFK
  1933. */
  1934. public function addFK($type, $targetType, $field, $targetField, $isDependent = false) {
  1935. $table = $this->esc($type);
  1936. $tableNoQ = $this->esc($type, true);
  1937. $targetTable = $this->esc($targetType);
  1938. $column = $this->esc($field);
  1939. $columnNoQ = $this->esc($field, true);
  1940. $targetColumn = $this->esc($targetField);
  1941. $targetColumnNoQ = $this->esc($targetField, true);
  1942. $db = $this->adapter->getCell('select database()');
  1943. $fkName = 'fk_'.$tableNoQ.'_'.$columnNoQ.'_'.$targetColumnNoQ.($isDependent ? '_casc':'');
  1944. $cName = 'cons_'.$fkName;
  1945. $cfks = $this->adapter->getCell("
  1946. SELECT CONSTRAINT_NAME
  1947. FROM information_schema.KEY_COLUMN_USAGE
  1948. WHERE TABLE_SCHEMA ='$db' AND TABLE_NAME = '$tableNoQ' AND COLUMN_NAME = '$columnNoQ' AND
  1949. CONSTRAINT_NAME <>'PRIMARY' AND REFERENCED_TABLE_NAME is not null
  1950. ");
  1951. $flagAddKey = false;
  1952. try{
  1953. //No keys
  1954. if (!$cfks) {
  1955. $flagAddKey = true; //go get a new key
  1956. }
  1957. //has fk, but different setting, --remove
  1958. if ($cfks && $cfks != $cName) {
  1959. $this->adapter->exec("ALTER TABLE $table DROP FOREIGN KEY $cfks ");
  1960. $flagAddKey = true; //go get a new key.
  1961. }
  1962. if ($flagAddKey) {
  1963. $this->adapter->exec("ALTER TABLE $table
  1964. ADD CONSTRAINT $cName FOREIGN KEY $fkName ( $column ) REFERENCES $targetTable (
  1965. $targetColumn) ON DELETE ".($isDependent ? 'CASCADE':'SET NULL').' ON UPDATE SET NULL ;');
  1966. }
  1967. } catch(Exception $e) {} //Failure of fk-constraints is not a problem
  1968. }
  1969. /**
  1970. * Renames an association. For instance if you would like to refer to
  1971. * album_song as: track you can specify this by calling this method like:
  1972. *
  1973. * renameAssociation('album_song','track')
  1974. *
  1975. * This allows:
  1976. *
  1977. * $album->sharedSong
  1978. *
  1979. * to add/retrieve beans from track instead of album_song.
  1980. * Also works for exportAll().
  1981. *
  1982. * This method also accepts a single associative array as
  1983. * its first argument.
  1984. *
  1985. * @param string|array $from
  1986. * @param string $to (optional)
  1987. *
  1988. * @return void
  1989. */
  1990. public static function renameAssociation($from, $to = null) {
  1991. if (is_array($from)) {
  1992. foreach($from as $key => $value) self::$renames[$key] = $value;
  1993. return;
  1994. }
  1995. self::$renames[$from] = $to;
  1996. }
  1997. /**
  1998. * Returns the format for link tables.
  1999. * Given an array containing two type names this method returns the
  2000. * name of the link table to be used to store and retrieve
  2001. * association records.
  2002. *
  2003. * @param array $types two types array($type1, $type2)
  2004. *
  2005. * @return string $linktable name of the link table
  2006. */
  2007. public static function getAssocTableFormat($types) {
  2008. sort($types);
  2009. $assoc = (implode('_', $types));
  2010. return (isset(self::$renames[$assoc])) ? self::$renames[$assoc] : $assoc;
  2011. }
  2012. /**
  2013. * @see RedBean_QueryWriter::addConstraint
  2014. */
  2015. public function addConstraint(RedBean_OODBBean $bean1, RedBean_OODBBean $bean2) {
  2016. $table1 = $bean1->getMeta('type');
  2017. $table2 = $bean2->getMeta('type');
  2018. $writer = $this;
  2019. $adapter = $this->adapter;
  2020. $table = RedBean_QueryWriter_AQueryWriter::getAssocTableFormat(array($table1, $table2));
  2021. $property1 = $bean1->getMeta('type') . '_id';
  2022. $property2 = $bean2->getMeta('type') . '_id';
  2023. if ($property1 == $property2) $property2 = $bean2->getMeta('type').'2_id';
  2024. $table = $this->esc($table, true);
  2025. $table1 = $this->esc($table1, true);
  2026. $table2 = $this->esc($table2, true);
  2027. $property1 = $this->esc($property1, true);
  2028. $property2 = $this->esc($property2, true);
  2029. //Dispatch to right method
  2030. return $this->constrain($table, $table1, $table2, $property1, $property2);
  2031. }
  2032. /**
  2033. * Checks whether a value starts with zeros. In this case
  2034. * the value should probably be stored using a text datatype instead of a
  2035. * numerical type in order to preserve the zeros.
  2036. *
  2037. * @param string $value value to be checked.
  2038. */
  2039. protected function startsWithZeros($value) {
  2040. $value = strval($value);
  2041. if (strlen($value)>1 && strpos($value, '0') === 0 && strpos($value, '0.') !==0) {
  2042. return true;
  2043. } else {
  2044. return false;
  2045. }
  2046. }
  2047. /**
  2048. * Turns caching on or off. Default: off.
  2049. * If caching is turned on retrieval queries fired after eachother will
  2050. * use a result row cache.
  2051. *
  2052. * @param boolean $yesNo
  2053. */
  2054. public function setUseCache($yesNo) {
  2055. $this->flushCache();
  2056. $this->flagUseCache = (boolean) $yesNo;
  2057. }
  2058. /**
  2059. * Flushes the Query Writer Cache.
  2060. */
  2061. public function flushCache() {
  2062. $this->cache = array();
  2063. }
  2064. /**
  2065. * @deprecated Use esc() instead.
  2066. */
  2067. public function safeColumn($a, $b = false) { return $this->esc($a, $b); }
  2068. public function safeTable($a, $b = false) { return $this->esc($a, $b); }
  2069. }
  2070. class RedBean_QueryWriter_MySQL extends RedBean_QueryWriter_AQueryWriter implements RedBean_QueryWriter {
  2071. /**
  2072. * Data types
  2073. */
  2074. const C_DATATYPE_BOOL = 0;
  2075. const C_DATATYPE_UINT8 = 1;
  2076. const C_DATATYPE_UINT32 = 2;
  2077. const C_DATATYPE_DOUBLE = 3;
  2078. const C_DATATYPE_TEXT8 = 4;
  2079. const C_DATATYPE_TEXT16 = 5;
  2080. const C_DATATYPE_TEXT32 = 6;
  2081. const C_DATATYPE_SPECIAL_DATE = 80;
  2082. const C_DATATYPE_SPECIAL_DATETIME = 81;
  2083. const C_DATATYPE_SPECIAL_POINT = 90;
  2084. const C_DATATYPE_SPECIFIED = 99;
  2085. /**
  2086. * @var RedBean_Adapter_DBAdapter
  2087. */
  2088. protected $adapter;
  2089. /**
  2090. * @var string
  2091. */
  2092. protected $quoteCharacter = '`';
  2093. /**
  2094. * Constructor
  2095. *
  2096. * @param RedBean_Adapter $adapter Database Adapter
  2097. */
  2098. public function __construct(RedBean_Adapter $adapter) {
  2099. $this->typeno_sqltype = array(
  2100. RedBean_QueryWriter_MySQL::C_DATATYPE_BOOL => ' TINYINT(1) UNSIGNED ',
  2101. RedBean_QueryWriter_MySQL::C_DATATYPE_UINT8 => ' TINYINT(3) UNSIGNED ',
  2102. RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32 => ' INT(11) UNSIGNED ',
  2103. RedBean_QueryWriter_MySQL::C_DATATYPE_DOUBLE => ' DOUBLE ',
  2104. RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT8 => ' VARCHAR(255) ',
  2105. RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT16 => ' TEXT ',
  2106. RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT32 => ' LONGTEXT ',
  2107. RedBean_QueryWriter_MySQL::C_DATATYPE_SPECIAL_DATE => ' DATE ',
  2108. RedBean_QueryWriter_MySQL::C_DATATYPE_SPECIAL_DATETIME => ' DATETIME ',
  2109. RedBean_QueryWriter_MySQL::C_DATATYPE_SPECIAL_POINT => ' POINT ',
  2110. );
  2111. $this->sqltype_typeno = array();
  2112. foreach($this->typeno_sqltype as $k => $v)
  2113. $this->sqltype_typeno[trim(strtolower($v))] = $k;
  2114. $this->adapter = $adapter;
  2115. }
  2116. /**
  2117. * This method returns the datatype to be used for primary key IDS and
  2118. * foreign keys. Returns one if the data type constants.
  2119. *
  2120. * @return integer $const data type to be used for IDS.
  2121. */
  2122. public function getTypeForID() {
  2123. return self::C_DATATYPE_UINT32;
  2124. }
  2125. /**
  2126. * @see RedBean_QueryWriter::getTables
  2127. */
  2128. public function getTables() {
  2129. return $this->adapter->getCol('show tables');
  2130. }
  2131. /**
  2132. * @see RedBean_QueryWriter::createTable
  2133. */
  2134. public function createTable($table) {
  2135. $table = $this->esc($table);
  2136. $sql = "CREATE TABLE $table (
  2137. id INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
  2138. PRIMARY KEY ( id )
  2139. ) ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
  2140. $this->adapter->exec($sql);
  2141. }
  2142. /**
  2143. * @see RedBean_QueryWriter::getColumns
  2144. */
  2145. public function getColumns($table) {
  2146. $table = $this->esc($table);
  2147. $columnsRaw = $this->adapter->get("DESCRIBE $table");
  2148. foreach($columnsRaw as $r) $columns[$r['Field']] = $r['Type'];
  2149. return $columns;
  2150. }
  2151. /**
  2152. * @see RedBean_QueryWriter::scanType
  2153. */
  2154. public function scanType($value, $flagSpecial = false) {
  2155. $this->svalue = $value;
  2156. if (is_null($value)) return RedBean_QueryWriter_MySQL::C_DATATYPE_BOOL;
  2157. if ($flagSpecial) {
  2158. if (preg_match('/^\d{4}\-\d\d-\d\d$/', $value)) {
  2159. return RedBean_QueryWriter_MySQL::C_DATATYPE_SPECIAL_DATE;
  2160. }
  2161. if (preg_match('/^\d{4}\-\d\d-\d\d\s\d\d:\d\d:\d\d$/', $value)) {
  2162. return RedBean_QueryWriter_MySQL::C_DATATYPE_SPECIAL_DATETIME;
  2163. }
  2164. }
  2165. $value = strval($value);
  2166. if (!$this->startsWithZeros($value)) {
  2167. if ($value === true || $value === false || $value === '1' || $value === '') {
  2168. return RedBean_QueryWriter_MySQL::C_DATATYPE_BOOL;
  2169. }
  2170. if (is_numeric($value) && (floor($value) == $value) && $value >= 0 && $value <= 255 ) {
  2171. return RedBean_QueryWriter_MySQL::C_DATATYPE_UINT8;
  2172. }
  2173. if (is_numeric($value) && (floor($value) == $value) && $value >= 0 && $value <= 4294967295 ) {
  2174. return RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32;
  2175. }
  2176. if (is_numeric($value)) {
  2177. return RedBean_QueryWriter_MySQL::C_DATATYPE_DOUBLE;
  2178. }
  2179. }
  2180. if (mb_strlen($value, 'UTF-8') <= 255) {
  2181. return RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT8;
  2182. }
  2183. if (mb_strlen($value, 'UTF-8') <= 65535) {
  2184. return RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT16;
  2185. }
  2186. return RedBean_QueryWriter_MySQL::C_DATATYPE_TEXT32;
  2187. }
  2188. /**
  2189. * @see RedBean_QueryWriter::code
  2190. */
  2191. public function code($typedescription, $includeSpecials = false) {
  2192. $r = ((isset($this->sqltype_typeno[$typedescription])) ? $this->sqltype_typeno[$typedescription] : self::C_DATATYPE_SPECIFIED);
  2193. if ($includeSpecials) return $r;
  2194. if ($r > self::C_DATATYPE_SPECIFIED) return self::C_DATATYPE_SPECIFIED;
  2195. return $r;
  2196. }
  2197. /**
  2198. * @see RedBean_QueryWriter::wideColumn
  2199. */
  2200. public function widenColumn($type, $column, $datatype) {
  2201. $table = $type;
  2202. $type = $datatype;
  2203. $table = $this->esc($table);
  2204. $column = $this->esc($column);
  2205. $newtype = array_key_exists($type, $this->typeno_sqltype) ? $this->typeno_sqltype[$type] : '';
  2206. $changecolumnSQL = "ALTER TABLE $table CHANGE $column $column $newtype ";
  2207. $this->adapter->exec($changecolumnSQL);
  2208. }
  2209. /**
  2210. * @see RedBean_QueryWriter::addUniqueIndex
  2211. */
  2212. public function addUniqueIndex($table, $columns) {
  2213. $table = $this->esc($table);
  2214. sort($columns); //else we get multiple indexes due to order-effects
  2215. foreach($columns as $k => $v) {
  2216. $columns[$k]= $this->esc($v);
  2217. }
  2218. $r = $this->adapter->get("SHOW INDEX FROM $table");
  2219. $name = 'UQ_'.sha1(implode(',', $columns));
  2220. if ($r) {
  2221. foreach($r as $i) {
  2222. if ($i['Key_name'] == $name) {
  2223. return;
  2224. }
  2225. }
  2226. }
  2227. $sql = "ALTER IGNORE TABLE $table
  2228. ADD UNIQUE INDEX $name (".implode(',', $columns).")";
  2229. $this->adapter->exec($sql);
  2230. }
  2231. /**
  2232. * @see RedBean_QueryWriter::addIndex
  2233. */
  2234. public function addIndex($type, $name, $column) {
  2235. $table = $type;
  2236. $table = $this->esc($table);
  2237. $name = preg_replace('/\W/', '', $name);
  2238. $column = $this->esc($column);
  2239. foreach($this->adapter->get("SHOW INDEX FROM $table ") as $ind) if ($ind['Key_name'] === $name) return;
  2240. try{ $this->adapter->exec("CREATE INDEX $name ON $table ($column) "); }catch(Exception $e){}
  2241. }
  2242. /**
  2243. * @see RedBean_QueryWriter::sqlStateIn
  2244. */
  2245. public function sqlStateIn($state, $list) {
  2246. $stateMap = array(
  2247. '42S02' => RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE,
  2248. '42S22' => RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  2249. '23000' => RedBean_QueryWriter::C_SQLSTATE_INTEGRITY_CONSTRAINT_VIOLATION
  2250. );
  2251. return in_array((isset($stateMap[$state]) ? $stateMap[$state] : '0'), $list);
  2252. }
  2253. /**
  2254. * Add the constraints for a specific database driver: MySQL.
  2255. * @todo Too many arguments; find a way to solve this in a neater way.
  2256. *
  2257. * @param string $table table
  2258. * @param string $table1 table1
  2259. * @param string $table2 table2
  2260. * @param string $property1 property1
  2261. * @param string $property2 property2
  2262. *
  2263. * @return boolean $succes whether the constraint has been applied
  2264. */
  2265. protected function constrain($table, $table1, $table2, $property1, $property2) {
  2266. try{
  2267. $db = $this->adapter->getCell('SELECT database()');
  2268. $fks = $this->adapter->getCell("
  2269. SELECT count(*)
  2270. FROM information_schema.KEY_COLUMN_USAGE
  2271. WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND
  2272. CONSTRAINT_NAME <>'PRIMARY' AND REFERENCED_TABLE_NAME IS NOT NULL
  2273. ", array($db, $table));
  2274. //already foreign keys added in this association table
  2275. if ($fks>0) return false;
  2276. $columns = $this->getColumns($table);
  2277. if ($this->code($columns[$property1]) !== RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32) {
  2278. $this->widenColumn($table, $property1, RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32);
  2279. }
  2280. if ($this->code($columns[$property2]) !== RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32) {
  2281. $this->widenColumn($table, $property2, RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32);
  2282. }
  2283. $sql = "
  2284. ALTER TABLE ".$this->esc($table)."
  2285. ADD FOREIGN KEY($property1) references `$table1`(id) ON DELETE CASCADE;
  2286. ";
  2287. $this->adapter->exec($sql);
  2288. $sql = "
  2289. ALTER TABLE ".$this->esc($table)."
  2290. ADD FOREIGN KEY($property2) references `$table2`(id) ON DELETE CASCADE
  2291. ";
  2292. $this->adapter->exec($sql);
  2293. return true;
  2294. } catch(Exception $e){ return false; }
  2295. }
  2296. /**
  2297. * @see RedBean_QueryWriter::wipeAll
  2298. */
  2299. public function wipeAll() {
  2300. $this->adapter->exec('SET FOREIGN_KEY_CHECKS = 0;');
  2301. foreach($this->getTables() as $t) {
  2302. try{
  2303. $this->adapter->exec("DROP TABLE IF EXISTS `$t`");
  2304. }
  2305. catch(Exception $e){}
  2306. try{
  2307. $this->adapter->exec("DROP VIEW IF EXISTS `$t`");
  2308. }
  2309. catch(Exception $e){}
  2310. }
  2311. $this->adapter->exec('SET FOREIGN_KEY_CHECKS = 1;');
  2312. }
  2313. }
  2314. class RedBean_QueryWriter_SQLiteT extends RedBean_QueryWriter_AQueryWriter implements RedBean_QueryWriter {
  2315. /**
  2316. * @var RedBean_Adapter_DBAdapter
  2317. */
  2318. protected $adapter;
  2319. /**
  2320. * @var string
  2321. */
  2322. protected $quoteCharacter = '`';
  2323. /**
  2324. * Data types
  2325. */
  2326. const C_DATATYPE_INTEGER = 0;
  2327. const C_DATATYPE_NUMERIC = 1;
  2328. const C_DATATYPE_TEXT = 2;
  2329. const C_DATATYPE_SPECIFIED = 99;
  2330. /**
  2331. * Constructor
  2332. *
  2333. * @param RedBean_Adapter $adapter Database Adapter
  2334. */
  2335. public function __construct(RedBean_Adapter $adapter) {
  2336. $this->typeno_sqltype = array(
  2337. RedBean_QueryWriter_SQLiteT::C_DATATYPE_INTEGER => 'INTEGER',
  2338. RedBean_QueryWriter_SQLiteT::C_DATATYPE_NUMERIC => 'NUMERIC',
  2339. RedBean_QueryWriter_SQLiteT::C_DATATYPE_TEXT => 'TEXT',
  2340. );
  2341. $this->sqltype_typeno = array();
  2342. foreach($this->typeno_sqltype as $k => $v)
  2343. $this->sqltype_typeno[$v] = $k;
  2344. $this->adapter = $adapter;
  2345. }
  2346. /**
  2347. * This method returns the datatype to be used for primary key IDS and
  2348. * foreign keys. Returns one if the data type constants.
  2349. *
  2350. * @return integer $const data type to be used for IDS.
  2351. */
  2352. public function getTypeForID() {
  2353. return self::C_DATATYPE_INTEGER;
  2354. }
  2355. /**
  2356. * @see RedBean_QueryWriter::scanType
  2357. */
  2358. public function scanType($value, $flagSpecial = false) {
  2359. $this->svalue = $value;
  2360. if ($value === false) return self::C_DATATYPE_INTEGER;
  2361. if ($value === null) return self::C_DATATYPE_INTEGER;
  2362. if ($this->startsWithZeros($value)) return self::C_DATATYPE_TEXT;
  2363. if (is_numeric($value) && (intval($value) == $value) && $value<2147483648) return self::C_DATATYPE_INTEGER;
  2364. if ((is_numeric($value) && $value < 2147483648)
  2365. || preg_match('/\d{4}\-\d\d\-\d\d/', $value)
  2366. || preg_match('/\d{4}\-\d\d\-\d\d\s\d\d:\d\d:\d\d/', $value)
  2367. ) {
  2368. return self::C_DATATYPE_NUMERIC;
  2369. }
  2370. return self::C_DATATYPE_TEXT;
  2371. }
  2372. /**
  2373. * @see RedBean_QueryWriter::addColumn
  2374. */
  2375. public function addColumn($table, $column, $type) {
  2376. $column = $this->check($column);
  2377. $table = $this->check($table);
  2378. $type = $this->typeno_sqltype[$type];
  2379. $sql = "ALTER TABLE `$table` ADD `$column` $type ";
  2380. $this->adapter->exec($sql);
  2381. }
  2382. /**
  2383. * @see RedBean_QueryWriter::code
  2384. */
  2385. public function code($typedescription, $includeSpecials = false) {
  2386. $r = ((isset($this->sqltype_typeno[$typedescription])) ? $this->sqltype_typeno[$typedescription] : 99);
  2387. if ($includeSpecials) return $r;
  2388. if ($r > self::C_DATATYPE_SPECIFIED) return self::C_DATATYPE_SPECIFIED;
  2389. return $r;
  2390. }
  2391. /**
  2392. * Gets all information about a table (from a type).
  2393. *
  2394. * Format:
  2395. * array(
  2396. * name => name of the table
  2397. * columns => array( name => datatype )
  2398. * indexes => array() raw index information rows from PRAGMA query
  2399. * keys => array() raw key information rows from PRAGMA query
  2400. * )
  2401. *
  2402. * @param string $type type you want to get info of
  2403. *
  2404. * @return array $info
  2405. */
  2406. protected function getTable($type) {
  2407. $tableName = $this->esc($type, true);
  2408. $columns = $this->getColumns($type);
  2409. $indexes = $this->getIndexes($type);
  2410. $keys = $this->getKeys($type);
  2411. $table = array('columns' => $columns, 'indexes' => $indexes, 'keys' => $keys, 'name' => $tableName);
  2412. $this->tableArchive[$tableName] = $table;
  2413. return $table;
  2414. }
  2415. /**
  2416. * Puts a table. Updates the table structure.
  2417. * In SQLite we can't change columns, drop columns, change or add foreign keys so we
  2418. * have a table-rebuild function. You simply load your table with getTable(), modify it and
  2419. * then store it with putTable()...
  2420. *
  2421. * @param array $tableMap information array
  2422. */
  2423. protected function putTable($tableMap) {
  2424. $table = $tableMap['name'];
  2425. $q = array();
  2426. $q[] = "DROP TABLE IF EXISTS tmp_backup;";
  2427. $oldColumnNames = array_keys($this->getColumns($table));
  2428. foreach($oldColumnNames as $k => $v) $oldColumnNames[$k] = "`$v`";
  2429. $q[] = "CREATE TEMPORARY TABLE tmp_backup(".implode(",", $oldColumnNames).");";
  2430. $q[] = "INSERT INTO tmp_backup SELECT * FROM `$table`;";
  2431. $q[] = "PRAGMA foreign_keys = 0 ";
  2432. $q[] = "DROP TABLE `$table`;";
  2433. $newTableDefStr = '';
  2434. foreach($tableMap['columns'] as $column => $type) {
  2435. if ($column != 'id') {
  2436. $newTableDefStr .= ",`$column` $type";
  2437. }
  2438. }
  2439. $fkDef = '';
  2440. foreach($tableMap['keys'] as $key) {
  2441. $fkDef .= ", FOREIGN KEY(`{$key['from']}`)
  2442. REFERENCES `{$key['table']}`(`{$key['to']}`)
  2443. ON DELETE {$key['on_delete']} ON UPDATE {$key['on_update']}";
  2444. }
  2445. $q[] = "CREATE TABLE `$table` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT $newTableDefStr $fkDef );";
  2446. foreach($tableMap['indexes'] as $name => $index) {
  2447. if (strpos($name, 'UQ_') === 0) {
  2448. $cols = explode('__', substr($name, strlen('UQ_'.$table)));
  2449. foreach($cols as $k => $v) $cols[$k] = "`$v`";
  2450. $q[] = "CREATE UNIQUE INDEX $name ON `$table` (".implode(',', $cols).")";
  2451. }
  2452. else $q[] = "CREATE INDEX $name ON `$table` ({$index['name']}) ";
  2453. }
  2454. $q[] = "INSERT INTO `$table` SELECT * FROM tmp_backup;";
  2455. $q[] = "DROP TABLE tmp_backup;";
  2456. $q[] = "PRAGMA foreign_keys = 1 ";
  2457. foreach($q as $sq) $this->adapter->exec($sq);
  2458. }
  2459. /**
  2460. * @see RedBean_QueryWriter::widenColumn
  2461. */
  2462. public function widenColumn($type, $column, $datatype) {
  2463. $t = $this->getTable($type);
  2464. $t['columns'][$column] = $this->typeno_sqltype[$datatype];
  2465. $this->putTable($t);
  2466. }
  2467. /**
  2468. * @see RedBean_QueryWriter::getTables();
  2469. */
  2470. public function getTables() {
  2471. return $this->adapter->getCol("SELECT name FROM sqlite_master
  2472. WHERE type='table' AND name!='sqlite_sequence';");
  2473. }
  2474. /**
  2475. * @see RedBean_QueryWriter::createTable
  2476. */
  2477. public function createTable($table) {
  2478. $table = $this->esc($table);
  2479. $sql = "CREATE TABLE $table ( id INTEGER PRIMARY KEY AUTOINCREMENT ) ";
  2480. $this->adapter->exec($sql);
  2481. }
  2482. /**
  2483. * @see RedBean_QueryWriter::getColumns
  2484. */
  2485. public function getColumns($table) {
  2486. $table = $this->esc($table, true);
  2487. $columnsRaw = $this->adapter->get("PRAGMA table_info('$table')");
  2488. $columns = array();
  2489. foreach($columnsRaw as $r) $columns[$r['name']] = $r['type'];
  2490. return $columns;
  2491. }
  2492. /**
  2493. * Returns the indexes for type $type.
  2494. *
  2495. * @param string $type
  2496. *
  2497. * @return array $indexInfo index information
  2498. */
  2499. protected function getIndexes($type) {
  2500. $table = $this->esc($type, true);
  2501. $indexes = $this->adapter->get("PRAGMA index_list('$table')");
  2502. $indexInfoList = array();
  2503. foreach($indexes as $i) {
  2504. $indexInfoList[$i['name']] = $this->adapter->getRow("PRAGMA index_info('{$i['name']}') ");
  2505. $indexInfoList[$i['name']]['unique'] = $i['unique'];
  2506. }
  2507. return $indexInfoList;
  2508. }
  2509. /**
  2510. * Returns the keys for type $type.
  2511. *
  2512. * @param string $type
  2513. *
  2514. * @return array $keysInfo keys information
  2515. */
  2516. protected function getKeys($type) {
  2517. $table = $this->esc($type, true);
  2518. $keys = $this->adapter->get("PRAGMA foreign_key_list('$table')");
  2519. $keyInfoList = array();
  2520. foreach($keys as $k) {
  2521. $keyInfoList['from_'.$k['from'].'_to_table_'.$k['table'].'_col_'.$k['to']] = $k;
  2522. }
  2523. return $keyInfoList;
  2524. }
  2525. /**
  2526. * @see RedBean_QueryWriter::addUniqueIndex
  2527. */
  2528. public function addUniqueIndex($type, $columns) {
  2529. $table = $this->esc($type, true);
  2530. $name = 'UQ_'.$table.implode('__', $columns);
  2531. $t = $this->getTable($type);
  2532. if (isset($t['indexes'][$name])) return;
  2533. $t['indexes'][$name] = array('name' => $name);
  2534. $this->putTable($t);
  2535. }
  2536. /**
  2537. * @see RedBean_QueryWriter::sqlStateIn
  2538. */
  2539. public function sqlStateIn($state, $list) {
  2540. $stateMap = array(
  2541. 'HY000' => RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE,
  2542. '23000' => RedBean_QueryWriter::C_SQLSTATE_INTEGRITY_CONSTRAINT_VIOLATION
  2543. );
  2544. return in_array((isset($stateMap[$state]) ? $stateMap[$state] : '0'), $list);
  2545. }
  2546. /**
  2547. * @see RedBean_QueryWriter::addIndex
  2548. */
  2549. public function addIndex($type, $name, $column) {
  2550. $table = $type;
  2551. $table = $this->esc($table);
  2552. $name = preg_replace('/\W/', '', $name);
  2553. $column = $this->esc($column, true);
  2554. foreach($this->adapter->get("PRAGMA INDEX_LIST($table) ") as $ind) if ($ind['name'] === $name) return;
  2555. $t = $this->getTable($type);
  2556. $t['indexes'][$name] = array('name' => $column);
  2557. return $this->putTable($t);
  2558. }
  2559. /**
  2560. * @see RedBean_QueryWriter::wipe
  2561. */
  2562. public function wipe($type) {
  2563. $table = $this->esc($type);
  2564. $this->adapter->exec("DELETE FROM $table");
  2565. }
  2566. /**
  2567. * @see RedBean_QueryWriter::addFK
  2568. */
  2569. public function addFK($type, $targetType, $field, $targetField, $isDep = false) {
  2570. return $this->buildFK($type, $targetType, $field, $targetField, $isDep);
  2571. }
  2572. /**
  2573. * Adds a foreign key to a type
  2574. *
  2575. * @param string $type type you want to modify table of
  2576. * @param string $targetType target type
  2577. * @param string $field field of the type that needs to get the fk
  2578. * @param string $targetField field where the fk needs to point to
  2579. * @param integer $buildopt 0 = NO ACTION, 1 = ON DELETE CASCADE
  2580. *
  2581. * @return boolean $didIt
  2582. *
  2583. * @note: cant put this in try-catch because that can hide the fact
  2584. * that database has been damaged.
  2585. */
  2586. protected function buildFK($type, $targetType, $field, $targetField, $constraint = false) {
  2587. $consSQL = ($constraint ? 'CASCADE' : 'SET NULL');
  2588. $t = $this->getTable($type);
  2589. $label = 'from_'.$field.'_to_table_'.$targetType.'_col_'.$targetField;
  2590. if (isset($t['keys'][$label])
  2591. && $t['keys'][$label]['table'] === $targetType
  2592. && $t['keys'][$label]['from'] === $field
  2593. && $t['keys'][$label]['to'] === $targetField
  2594. && $t['keys'][$label]['on_delete'] === $consSQL
  2595. ) return false;
  2596. $t['keys'][$label] = array(
  2597. 'table' => $targetType,
  2598. 'from' => $field,
  2599. 'to' => $targetField,
  2600. 'on_update' => 'SET NULL',
  2601. 'on_delete' => $consSQL
  2602. );
  2603. $this->putTable($t);
  2604. return true;
  2605. }
  2606. /**
  2607. * Add the constraints for a specific database driver: SQLite.
  2608. * @todo Too many arguments; find a way to solve this in a neater way.
  2609. *
  2610. * @param string $table table
  2611. * @param string $table1 table1
  2612. * @param string $table2 table2
  2613. * @param string $property1 property1
  2614. * @param string $property2 property2
  2615. *
  2616. * @return boolean $succes whether the constraint has been applied
  2617. */
  2618. protected function constrain($table, $table1, $table2, $property1, $property2) {
  2619. $writer = $this;
  2620. $adapter = $this->adapter;
  2621. $firstState = $this->buildFK($table, $table1, $property1, 'id', true);
  2622. $secondState = $this->buildFK($table, $table2, $property2, 'id', true);
  2623. return ($firstState && $secondState);
  2624. }
  2625. /**
  2626. * @see RedBean_QueryWriter::wipeAll
  2627. */
  2628. public function wipeAll() {
  2629. $this->adapter->exec('PRAGMA foreign_keys = 0 ');
  2630. foreach($this->getTables() as $t) {
  2631. try{
  2632. $this->adapter->exec("drop table if exists`$t`");
  2633. } catch(Exception $e){}
  2634. try{
  2635. $this->adapter->exec("drop view if exists`$t`");
  2636. } catch(Exception $e){}
  2637. }
  2638. $this->adapter->exec('PRAGMA foreign_keys = 1 ');
  2639. }
  2640. }
  2641. class RedBean_QueryWriter_PostgreSQL extends RedBean_QueryWriter_AQueryWriter implements RedBean_QueryWriter {
  2642. /**
  2643. * Data types
  2644. */
  2645. const C_DATATYPE_INTEGER = 0;
  2646. const C_DATATYPE_DOUBLE = 1;
  2647. const C_DATATYPE_TEXT = 3;
  2648. const C_DATATYPE_SPECIAL_DATE = 80;
  2649. const C_DATATYPE_SPECIAL_DATETIME = 81;
  2650. const C_DATATYPE_SPECIAL_POINT = 90;
  2651. const C_DATATYPE_SPECIAL_LSEG = 91;
  2652. const C_DATATYPE_SPECIAL_CIRCLE = 92;
  2653. const C_DATATYPE_SPECIAL_MONEY = 93;
  2654. const C_DATATYPE_SPECIFIED = 99;
  2655. /**
  2656. * @var RedBean_DBAdapter
  2657. */
  2658. protected $adapter;
  2659. /**
  2660. * @var string
  2661. */
  2662. protected $quoteCharacter = '"';
  2663. /**
  2664. * @var string
  2665. */
  2666. protected $defaultValue = 'DEFAULT';
  2667. /**
  2668. * This method returns the datatype to be used for primary key IDS and
  2669. * foreign keys. Returns one if the data type constants.
  2670. *
  2671. * @return integer $const data type to be used for IDS.
  2672. */
  2673. public function getTypeForID() {
  2674. return self::C_DATATYPE_INTEGER;
  2675. }
  2676. /**
  2677. * Returns the insert suffix SQL Snippet
  2678. *
  2679. * @param string $table table
  2680. *
  2681. * @return string $sql SQL Snippet
  2682. */
  2683. protected function getInsertSuffix($table) {
  2684. return 'RETURNING id ';
  2685. }
  2686. /**
  2687. * Constructor
  2688. *
  2689. * @param RedBean_Adapter $adapter Database Adapter
  2690. */
  2691. public function __construct(RedBean_Adapter $adapter) {
  2692. $this->typeno_sqltype = array(
  2693. self::C_DATATYPE_INTEGER => ' integer ',
  2694. self::C_DATATYPE_DOUBLE => ' double precision ',
  2695. self::C_DATATYPE_TEXT => ' text ',
  2696. self::C_DATATYPE_SPECIAL_DATE => ' date ',
  2697. self::C_DATATYPE_SPECIAL_DATETIME => ' timestamp without time zone ',
  2698. self::C_DATATYPE_SPECIAL_POINT => ' point ',
  2699. self::C_DATATYPE_SPECIAL_LSEG => ' lseg ',
  2700. self::C_DATATYPE_SPECIAL_CIRCLE => ' circle ',
  2701. self::C_DATATYPE_SPECIAL_MONEY => ' money ',
  2702. );
  2703. $this->sqltype_typeno = array();
  2704. foreach($this->typeno_sqltype as $k => $v)
  2705. $this->sqltype_typeno[trim(strtolower($v))] = $k;
  2706. $this->adapter = $adapter;
  2707. }
  2708. /**
  2709. * @see RedBean_QueryWriter::getTables
  2710. */
  2711. public function getTables() {
  2712. return $this->adapter->getCol("select table_name from information_schema.tables
  2713. where table_schema = 'public'");
  2714. }
  2715. /**
  2716. * @see RedBean_QueryWriter::createTable
  2717. */
  2718. public function createTable($table) {
  2719. $table = $this->esc($table);
  2720. $sql = " CREATE TABLE $table (id SERIAL PRIMARY KEY); ";
  2721. $this->adapter->exec($sql);
  2722. }
  2723. /**
  2724. * @see RedBean_QueryWriter::getColumns
  2725. */
  2726. public function getColumns($table) {
  2727. $table = $this->esc($table, true);
  2728. $columnsRaw = $this->adapter->get("select column_name, data_type from information_schema.columns where table_name='$table'");
  2729. foreach($columnsRaw as $r) {
  2730. $columns[$r['column_name']] = $r['data_type'];
  2731. }
  2732. return $columns;
  2733. }
  2734. /**
  2735. * @see RedBean_QueryWriter::scanType
  2736. */
  2737. public function scanType($value, $flagSpecial = false) {
  2738. $this->svalue = $value;
  2739. if ($flagSpecial && $value) {
  2740. if (preg_match('/^\d{4}\-\d\d-\d\d$/', $value)) {
  2741. return RedBean_QueryWriter_PostgreSQL::C_DATATYPE_SPECIAL_DATE;
  2742. }
  2743. if (preg_match('/^\d{4}\-\d\d-\d\d\s\d\d:\d\d:\d\d(\.\d{1,6})?$/', $value)) {
  2744. return RedBean_QueryWriter_PostgreSQL::C_DATATYPE_SPECIAL_DATETIME;
  2745. }
  2746. if (preg_match('/^\([\d\.]+,[\d\.]+\)$/', $value)) {
  2747. return RedBean_QueryWriter_PostgreSQL::C_DATATYPE_SPECIAL_POINT;
  2748. }
  2749. if (preg_match('/^\[\([\d\.]+,[\d\.]+\),\([\d\.]+,[\d\.]+\)\]$/', $value)) {
  2750. return RedBean_QueryWriter_PostgreSQL::C_DATATYPE_SPECIAL_LSEG;
  2751. }
  2752. if (preg_match('/^\<\([\d\.]+,[\d\.]+\),[\d\.]+\>$/', $value)) {
  2753. return RedBean_QueryWriter_PostgreSQL::C_DATATYPE_SPECIAL_CIRCLE;
  2754. }
  2755. if (preg_match('/^\-?\$\d+/', $value)) {
  2756. return RedBean_QueryWriter_PostgreSQL::C_DATATYPE_SPECIAL_MONEY;
  2757. }
  2758. }
  2759. $sz = ($this->startsWithZeros($value));
  2760. if ($sz) return self::C_DATATYPE_TEXT;
  2761. if ($value === null || ($value instanceof RedBean_Driver_PDO_NULL) ||(is_numeric($value)
  2762. && floor($value) == $value
  2763. && $value < 2147483648
  2764. && $value > -2147483648)) {
  2765. return self::C_DATATYPE_INTEGER;
  2766. }
  2767. elseif(is_numeric($value)) {
  2768. return self::C_DATATYPE_DOUBLE;
  2769. } else {
  2770. return self::C_DATATYPE_TEXT;
  2771. }
  2772. }
  2773. /**
  2774. * @see RedBean_QueryWriter::code
  2775. */
  2776. public function code($typedescription, $includeSpecials = false) {
  2777. $r = ((isset($this->sqltype_typeno[$typedescription])) ? $this->sqltype_typeno[$typedescription] : 99);
  2778. if ($includeSpecials) return $r;
  2779. if ($r > self::C_DATATYPE_SPECIFIED) return self::C_DATATYPE_SPECIFIED;
  2780. return $r;
  2781. }
  2782. /**
  2783. * @see RedBean_QueryWriter::widenColumn
  2784. */
  2785. public function widenColumn($type, $column, $datatype) {
  2786. $table = $type;
  2787. $type = $datatype;
  2788. $table = $this->esc($table);
  2789. $column = $this->esc($column);
  2790. $newtype = $this->typeno_sqltype[$type];
  2791. $changecolumnSQL = "ALTER TABLE $table \n\t ALTER COLUMN $column TYPE $newtype ";
  2792. $this->adapter->exec($changecolumnSQL);
  2793. }
  2794. /**
  2795. * @see RedBean_QueryWriter::addUniqueIndex
  2796. */
  2797. public function addUniqueIndex($table, $columns) {
  2798. $table = $this->esc($table, true);
  2799. sort($columns); //else we get multiple indexes due to order-effects
  2800. foreach($columns as $k => $v) {
  2801. $columns[$k] = $this->esc($v);
  2802. }
  2803. $r = $this->adapter->get("SELECT
  2804. i.relname as index_name
  2805. FROM
  2806. pg_class t,
  2807. pg_class i,
  2808. pg_index ix,
  2809. pg_attribute a
  2810. WHERE
  2811. t.oid = ix.indrelid
  2812. AND i.oid = ix.indexrelid
  2813. AND a.attrelid = t.oid
  2814. AND a.attnum = ANY(ix.indkey)
  2815. AND t.relkind = 'r'
  2816. AND t.relname = '$table'
  2817. ORDER BY t.relname, i.relname;");
  2818. $name = "UQ_".sha1($table.implode(',', $columns));
  2819. if ($r) {
  2820. foreach($r as $i) {
  2821. if (strtolower($i['index_name']) == strtolower($name)) {
  2822. return;
  2823. }
  2824. }
  2825. }
  2826. $sql = "ALTER TABLE \"$table\"
  2827. ADD CONSTRAINT $name UNIQUE (".implode(',', $columns).")";
  2828. $this->adapter->exec($sql);
  2829. }
  2830. /**
  2831. * @see RedBean_QueryWriter::sqlStateIn
  2832. */
  2833. public function sqlStateIn($state, $list) {
  2834. $stateMap = array(
  2835. '42P01' => RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE,
  2836. '42703' => RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  2837. '23505' => RedBean_QueryWriter::C_SQLSTATE_INTEGRITY_CONSTRAINT_VIOLATION
  2838. );
  2839. return in_array((isset($stateMap[$state]) ? $stateMap[$state] : '0'), $list);
  2840. }
  2841. /**
  2842. * @see RedBean_QueryWriter::addIndex
  2843. */
  2844. public function addIndex($type, $name, $column) {
  2845. $table = $type;
  2846. $table = $this->esc($table);
  2847. $name = preg_replace('/\W/', '', $name);
  2848. $column = $this->esc($column);
  2849. if ($this->adapter->getCell("SELECT COUNT(*) FROM pg_class WHERE relname = '$name'")) return;
  2850. try{ $this->adapter->exec("CREATE INDEX $name ON $table ($column) "); }catch(Exception $e){}
  2851. }
  2852. /**
  2853. * @see RedBean_QueryWriter::addFK
  2854. */
  2855. public function addFK($type, $targetType, $field, $targetField, $isDep = false) {
  2856. try{
  2857. $table = $this->esc($type);
  2858. $column = $this->esc($field);
  2859. $tableNoQ = $this->esc($type, true);
  2860. $columnNoQ = $this->esc($field, true);
  2861. $targetTable = $this->esc($targetType);
  2862. $targetTableNoQ = $this->esc($targetType, true);
  2863. $targetColumn = $this->esc($targetField);
  2864. $targetColumnNoQ = $this->esc($targetField, true);
  2865. $sql = "SELECT
  2866. tc.constraint_name,
  2867. tc.table_name,
  2868. kcu.column_name,
  2869. ccu.table_name AS foreign_table_name,
  2870. ccu.column_name AS foreign_column_name,
  2871. rc.delete_rule
  2872. FROM
  2873. information_schema.table_constraints AS tc
  2874. JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
  2875. JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
  2876. JOIN information_schema.referential_constraints AS rc ON ccu.constraint_name = rc.constraint_name
  2877. WHERE constraint_type = 'FOREIGN KEY' AND tc.table_catalog=current_database()
  2878. AND tc.table_name = '$tableNoQ'
  2879. AND ccu.table_name = '$targetTableNoQ'
  2880. AND kcu.column_name = '$columnNoQ'
  2881. AND ccu.column_name = '$targetColumnNoQ'
  2882. ";
  2883. $row = $this->adapter->getRow($sql);
  2884. $flagAddKey = false;
  2885. if (!$row) $flagAddKey = true;
  2886. if ($row) {
  2887. if (($row['delete_rule'] == 'SET NULL' && $isDep) ||
  2888. ($row['delete_rule'] != 'SET NULL' && !$isDep)) {
  2889. //delete old key
  2890. $flagAddKey = true; //and order a new one
  2891. $cName = $row['constraint_name'];
  2892. $sql = "ALTER TABLE $table DROP CONSTRAINT $cName ";
  2893. $this->adapter->exec($sql);
  2894. }
  2895. }
  2896. if ($flagAddKey) {
  2897. $delRule = ($isDep ? 'CASCADE' : 'SET NULL');
  2898. $this->adapter->exec("ALTER TABLE $table
  2899. ADD FOREIGN KEY ( $column ) REFERENCES $targetTable (
  2900. $targetColumn) ON DELETE $delRule ON UPDATE SET NULL DEFERRABLE ;");
  2901. return true;
  2902. }
  2903. return false;
  2904. } catch(Exception $e){ return false; }
  2905. }
  2906. /**
  2907. * Add the constraints for a specific database driver: PostgreSQL.
  2908. * @todo Too many arguments; find a way to solve this in a neater way.
  2909. *
  2910. * @param string $table table
  2911. * @param string $table1 table1
  2912. * @param string $table2 table2
  2913. * @param string $property1 property1
  2914. * @param string $property2 property2
  2915. *
  2916. * @return boolean $succes whether the constraint has been applied
  2917. */
  2918. protected function constrain($table, $table1, $table2, $property1, $property2) {
  2919. try{
  2920. $writer = $this;
  2921. $adapter = $this->adapter;
  2922. $fkCode = 'fk'.md5($table.$property1.$property2);
  2923. $sql = "
  2924. SELECT
  2925. c.oid,
  2926. n.nspname,
  2927. c.relname,
  2928. n2.nspname,
  2929. c2.relname,
  2930. cons.conname
  2931. FROM pg_class c
  2932. JOIN pg_namespace n ON n.oid = c.relnamespace
  2933. LEFT OUTER JOIN pg_constraint cons ON cons.conrelid = c.oid
  2934. LEFT OUTER JOIN pg_class c2 ON cons.confrelid = c2.oid
  2935. LEFT OUTER JOIN pg_namespace n2 ON n2.oid = c2.relnamespace
  2936. WHERE c.relkind = 'r'
  2937. AND n.nspname IN ('public')
  2938. AND (cons.contype = 'f' OR cons.contype IS NULL)
  2939. AND
  2940. ( cons.conname = '{$fkCode}a' OR cons.conname = '{$fkCode}b' )
  2941. ";
  2942. $rows = $adapter->get($sql);
  2943. if (!count($rows)) {
  2944. $sql1 = "ALTER TABLE \"$table\" ADD CONSTRAINT
  2945. {$fkCode}a FOREIGN KEY ($property1)
  2946. REFERENCES \"$table1\" (id) ON DELETE CASCADE ";
  2947. $sql2 = "ALTER TABLE \"$table\" ADD CONSTRAINT
  2948. {$fkCode}b FOREIGN KEY ($property2)
  2949. REFERENCES \"$table2\" (id) ON DELETE CASCADE ";
  2950. $adapter->exec($sql1);
  2951. $adapter->exec($sql2);
  2952. }
  2953. return true;
  2954. }
  2955. catch(Exception $e){ return false; }
  2956. }
  2957. /**
  2958. * @see RedBean_QueryWriter::wipeAll
  2959. */
  2960. public function wipeAll() {
  2961. $this->adapter->exec('SET CONSTRAINTS ALL DEFERRED');
  2962. foreach($this->getTables() as $t) {
  2963. $t = $this->esc($t);
  2964. try{
  2965. $this->adapter->exec("drop table if exists $t CASCADE ");
  2966. } catch(Exception $e){}
  2967. try{
  2968. $this->adapter->exec("drop view if exists $t CASCADE ");
  2969. } catch(Exception $e){ throw $e; }
  2970. }
  2971. $this->adapter->exec('SET CONSTRAINTS ALL IMMEDIATE');
  2972. }
  2973. /**
  2974. * @see RedBean_QueryWriter::wipe
  2975. */
  2976. public function wipe($type) {
  2977. $table = $type;
  2978. $table = $this->esc($table);
  2979. $sql = "TRUNCATE $table CASCADE";
  2980. $this->adapter->exec($sql);
  2981. }
  2982. }
  2983. class RedBean_QueryWriter_CUBRID extends RedBean_QueryWriter_AQueryWriter implements RedBean_QueryWriter {
  2984. /**
  2985. * Data types
  2986. */
  2987. const C_DATATYPE_INTEGER = 0;
  2988. const C_DATATYPE_DOUBLE = 1;
  2989. const C_DATATYPE_STRING = 2;
  2990. const C_DATATYPE_SPECIAL_DATE = 80;
  2991. const C_DATATYPE_SPECIAL_DATETIME = 81;
  2992. const C_DATATYPE_SPECIFIED = 99;
  2993. /**
  2994. * @var RedBean_Adapter_DBAdapter
  2995. */
  2996. protected $adapter;
  2997. /**
  2998. * @var string
  2999. */
  3000. protected $quoteCharacter = '`';
  3001. /**
  3002. * Constructor
  3003. *
  3004. * @param RedBean_Adapter $adapter Database Adapter
  3005. */
  3006. public function __construct(RedBean_Adapter $adapter) {
  3007. $this->typeno_sqltype = array(
  3008. RedBean_QueryWriter_CUBRID::C_DATATYPE_INTEGER => ' INTEGER ',
  3009. RedBean_QueryWriter_CUBRID::C_DATATYPE_DOUBLE => ' DOUBLE ',
  3010. RedBean_QueryWriter_CUBRID::C_DATATYPE_STRING => ' STRING ',
  3011. RedBean_QueryWriter_CUBRID::C_DATATYPE_SPECIAL_DATE => ' DATE ',
  3012. RedBean_QueryWriter_CUBRID::C_DATATYPE_SPECIAL_DATETIME => ' DATETIME ',
  3013. );
  3014. $this->sqltype_typeno = array();
  3015. foreach($this->typeno_sqltype as $k => $v)
  3016. $this->sqltype_typeno[trim(($v))] = $k;
  3017. $this->sqltype_typeno['STRING(1073741823)'] = self::C_DATATYPE_STRING;
  3018. $this->adapter = $adapter;
  3019. }
  3020. /**
  3021. * This method returns the datatype to be used for primary key IDS and
  3022. * foreign keys. Returns one if the data type constants.
  3023. *
  3024. * @return integer $const data type to be used for IDS.
  3025. */
  3026. public function getTypeForID() {
  3027. return self::C_DATATYPE_INTEGER;
  3028. }
  3029. /**
  3030. * @see RedBean_QueryWriter::getTables
  3031. */
  3032. public function getTables() {
  3033. $rows = $this->adapter->getCol("SELECT class_name FROM db_class WHERE is_system_class = 'NO';");
  3034. return $rows;
  3035. }
  3036. /**
  3037. * @see RedBean_QueryWriter::createTable
  3038. */
  3039. public function createTable($table) {
  3040. $rawTable = $this->esc($table, true);
  3041. $table = $this->esc($table);
  3042. $sql = 'CREATE TABLE '.$table.' (
  3043. "id" integer AUTO_INCREMENT,
  3044. CONSTRAINT "pk_'.$rawTable.'_id" PRIMARY KEY("id")
  3045. )';
  3046. $this->adapter->exec($sql);
  3047. }
  3048. /**
  3049. * @see RedBean_QueryWriter::getColumns
  3050. */
  3051. public function getColumns($table) {
  3052. $columns = array();
  3053. $table = $this->esc($table);
  3054. $columnsRaw = $this->adapter->get("SHOW COLUMNS FROM $table");
  3055. foreach($columnsRaw as $r) {
  3056. $columns[$r['Field']] = $r['Type'];
  3057. }
  3058. return $columns;
  3059. }
  3060. /**
  3061. * @see RedBean_QueryWriter::scanType
  3062. */
  3063. public function scanType($value, $flagSpecial = false) {
  3064. $this->svalue = $value;
  3065. if (is_null($value)) {
  3066. return self::C_DATATYPE_INTEGER;
  3067. }
  3068. if ($flagSpecial) {
  3069. if (preg_match('/^\d{4}\-\d\d-\d\d$/', $value)) {
  3070. return self::C_DATATYPE_SPECIAL_DATE;
  3071. }
  3072. if (preg_match('/^\d{4}\-\d\d-\d\d\s\d\d:\d\d:\d\d$/', $value)) {
  3073. return self::C_DATATYPE_SPECIAL_DATETIME;
  3074. }
  3075. }
  3076. $value = strval($value);
  3077. if (!$this->startsWithZeros($value)) {
  3078. if (is_numeric($value) && (floor($value) == $value) && $value >= -2147483647 && $value <= 2147483647 ) {
  3079. return self::C_DATATYPE_INTEGER;
  3080. }
  3081. if (is_numeric($value)) {
  3082. return self::C_DATATYPE_DOUBLE;
  3083. }
  3084. }
  3085. return self::C_DATATYPE_STRING;
  3086. }
  3087. /**
  3088. * @see RedBean_QueryWriter::code
  3089. */
  3090. public function code($typedescription, $includeSpecials = false) {
  3091. $r = ((isset($this->sqltype_typeno[$typedescription])) ? $this->sqltype_typeno[$typedescription] : self::C_DATATYPE_SPECIFIED);
  3092. if ($includeSpecials) return $r;
  3093. if ($r > self::C_DATATYPE_SPECIFIED) return self::C_DATATYPE_SPECIFIED;
  3094. return $r;
  3095. }
  3096. /**
  3097. * @see RedBean_QueryWriter::addColumn
  3098. *
  3099. */
  3100. public function addColumn($type, $column, $field) {
  3101. $table = $type;
  3102. $type = $field;
  3103. $table = $this->esc($table);
  3104. $column = $this->esc($column);
  3105. $type = array_key_exists($type, $this->typeno_sqltype) ? $this->typeno_sqltype[$type] : '';
  3106. $sql = "ALTER TABLE $table ADD COLUMN $column $type ";
  3107. $this->adapter->exec($sql);
  3108. }
  3109. /**
  3110. * @see RedBean_QueryWriter::widenColumn
  3111. */
  3112. public function widenColumn($type, $column, $datatype) {
  3113. $table = $type;
  3114. $type = $datatype;
  3115. $table = $this->esc($table);
  3116. $column = $this->esc($column);
  3117. $newtype = array_key_exists($type, $this->typeno_sqltype) ? $this->typeno_sqltype[$type] : '';
  3118. $changecolumnSQL = "ALTER TABLE $table CHANGE $column $column $newtype ";
  3119. $this->adapter->exec($changecolumnSQL);
  3120. }
  3121. /**
  3122. * @see RedBean_QueryWriter::addUniqueIndex
  3123. */
  3124. public function addUniqueIndex($table, $columns) {
  3125. $table = $this->esc($table);
  3126. sort($columns); //else we get multiple indexes due to order-effects
  3127. foreach($columns as $k => $v) {
  3128. $columns[$k] = $this->esc($v);
  3129. }
  3130. $r = $this->adapter->get("SHOW INDEX FROM $table");
  3131. $name = 'UQ_'.sha1(implode(',', $columns));
  3132. if ($r) {
  3133. foreach($r as $i) {
  3134. if (strtoupper($i['Key_name']) == strtoupper($name)) {
  3135. return;
  3136. }
  3137. }
  3138. }
  3139. $sql = "ALTER TABLE $table
  3140. ADD CONSTRAINT UNIQUE $name (".implode(',', $columns).")";
  3141. $this->adapter->exec($sql);
  3142. }
  3143. /**
  3144. * @see RedBean_QueryWriter::sqlStateIn
  3145. */
  3146. public function sqlStateIn($state, $list) {
  3147. return ($state == 'HY000') ? (count(array_diff(array(
  3148. RedBean_QueryWriter::C_SQLSTATE_INTEGRITY_CONSTRAINT_VIOLATION,
  3149. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  3150. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE
  3151. ), $list)) !== 3) : false;
  3152. }
  3153. /**
  3154. * @see RedBean_QueryWriter::addConstraint
  3155. */
  3156. public function addConstraint(RedBean_OODBBean $bean1, RedBean_OODBBean $bean2) {
  3157. $table1 = $bean1->getMeta('type');
  3158. $table2 = $bean2->getMeta('type');
  3159. $writer = $this;
  3160. $adapter = $this->adapter;
  3161. $table = RedBean_QueryWriter_AQueryWriter::getAssocTableFormat(array($table1, $table2));
  3162. $property1 = $bean1->getMeta('type') . '_id';
  3163. $property2 = $bean2->getMeta('type') . '_id';
  3164. if ($property1 == $property2) $property2 = $bean2->getMeta('type').'2_id';
  3165. //Dispatch to right method
  3166. return $this->constrain($table, $table1, $table2, $property1, $property2);
  3167. }
  3168. /**
  3169. * Add the constraints for a specific database driver: CUBRID
  3170. * @todo Too many arguments; find a way to solve this in a neater way.
  3171. *
  3172. * @param string $table table
  3173. * @param string $table1 table1
  3174. * @param string $table2 table2
  3175. * @param string $property1 property1
  3176. * @param string $property2 property2
  3177. *
  3178. * @return boolean $succes whether the constraint has been applied
  3179. */
  3180. protected function constrain($table, $table1, $table2, $property1, $property2) {
  3181. $writer = $this;
  3182. $adapter = $this->adapter;
  3183. $firstState = $this->buildFK($table, $table1, $property1, 'id', true);
  3184. $secondState = $this->buildFK($table, $table2, $property2, 'id', true);
  3185. return ($firstState && $secondState);
  3186. }
  3187. /**
  3188. * @see RedBean_QueryWriter::addIndex
  3189. */
  3190. public function addIndex($type, $name, $column) {
  3191. $table = $type;
  3192. $table = $this->esc($table);
  3193. $name = preg_replace('/\W/', '', $name);
  3194. $column = $this->esc($column);
  3195. $index = $this->adapter->getRow("SELECT 1 as `exists` FROM db_index WHERE index_name = ? ", array($name));
  3196. if ($index && $index['exists']) return; // positive number will return, 0 will continue.
  3197. try{ $this->adapter->exec("CREATE INDEX $name ON $table ($column) "); } catch(Exception $e){}
  3198. }
  3199. /**
  3200. * @see RedBean_QueryWriter::addFK
  3201. */
  3202. public function addFK($type, $targetType, $field, $targetField, $isDependent = false) {
  3203. return $this->buildFK($type, $targetType, $field, $targetField, $isDependent);
  3204. }
  3205. /**
  3206. * This method adds a foreign key from type and field to
  3207. * target type and target field.
  3208. * The foreign key is created without an action. On delete/update
  3209. * no action will be triggered. The FK is only used to allow database
  3210. * tools to generate pretty diagrams and to make it easy to add actions
  3211. * later on.
  3212. * This methods accepts a type and infers the corresponding table name.
  3213. *
  3214. *
  3215. * @param string $type type that will have a foreign key field
  3216. * @param string $targetType points to this type
  3217. * @param string $field field that contains the foreign key value
  3218. * @param string $targetField field where the fk points to
  3219. *
  3220. * @return void
  3221. */
  3222. protected function buildFK($type, $targetType, $field, $targetField, $isDep = false) {
  3223. $table = $this->esc($type);
  3224. $tableNoQ = $this->esc($type, true);
  3225. $targetTable = $this->esc($targetType);
  3226. $targetTableNoQ = $this->esc($targetType, true);
  3227. $column = $this->esc($field);
  3228. $columnNoQ = $this->esc($field, true);
  3229. $targetColumn = $this->esc($targetField);
  3230. $targetColumnNoQ = $this->esc($targetField, true);
  3231. $keys = $this->getKeys($targetTableNoQ, $tableNoQ);
  3232. $needsToAddFK = true;
  3233. $needsToDropFK = false;
  3234. foreach($keys as $key) {
  3235. if ($key['FKTABLE_NAME'] == $tableNoQ && $key['FKCOLUMN_NAME'] == $columnNoQ) {
  3236. //already has an FK
  3237. $needsToDropFK = true;
  3238. if ((($isDep && $key['DELETE_RULE'] == 0) || (!$isDep && $key['DELETE_RULE'] == 3))) {
  3239. return false;
  3240. }
  3241. break;
  3242. }
  3243. }
  3244. if ($needsToDropFK) {
  3245. $sql = "ALTER TABLE $table DROP FOREIGN KEY {$key['FK_NAME']} ";
  3246. $this->adapter->exec($sql);
  3247. }
  3248. $casc = ($isDep ? 'CASCADE' : 'SET NULL');
  3249. $sql = "ALTER TABLE $table ADD CONSTRAINT FOREIGN KEY($column) REFERENCES $targetTable($targetColumn) ON DELETE $casc ";
  3250. $this->adapter->exec($sql);
  3251. }
  3252. /**
  3253. * @see RedBean_QueryWriter::wipeAll
  3254. */
  3255. public function wipeAll() {
  3256. foreach($this->getTables() as $t) {
  3257. foreach($this->getKeys($t) as $k) {
  3258. $this->adapter->exec("ALTER TABLE \"{$k['FKTABLE_NAME']}\" DROP FOREIGN KEY \"{$k['FK_NAME']}\"");
  3259. }
  3260. $this->adapter->exec("DROP TABLE \"$t\"");
  3261. }
  3262. }
  3263. /**
  3264. * Obtains the keys of a table using the PDO schema function.
  3265. *
  3266. * @param type $table
  3267. * @return type
  3268. */
  3269. protected function getKeys($table, $table2 = null) {
  3270. $pdo = $this->adapter->getDatabase()->getPDO();
  3271. $keys = $pdo->cubrid_schema(PDO::CUBRID_SCH_EXPORTED_KEYS, $table);
  3272. if ($table2) $keys = array_merge($keys, $pdo->cubrid_schema(PDO::CUBRID_SCH_IMPORTED_KEYS, $table2));
  3273. return $keys;
  3274. }
  3275. /**
  3276. * @see RedBean_QueryWriter::esc
  3277. */
  3278. public function esc($dbStructure, $noQuotes = false) {
  3279. return parent::esc(strtolower($dbStructure), $noQuotes);
  3280. }
  3281. }
  3282. class RedBean_Exception extends LogicException {}
  3283. class RedBean_Exception_SQL extends RuntimeException {
  3284. /**
  3285. * @var string
  3286. */
  3287. private $sqlState;
  3288. /**
  3289. * Returns an ANSI-92 compliant SQL state.
  3290. *
  3291. * @return string $state ANSI state code
  3292. */
  3293. public function getSQLState() {
  3294. return $this->sqlState;
  3295. }
  3296. /**
  3297. * @todo parse state to verify valid ANSI92!
  3298. * Stores ANSI-92 compliant SQL state.
  3299. *
  3300. * @param string $sqlState code
  3301. *
  3302. * @return void
  3303. */
  3304. public function setSQLState($sqlState) {
  3305. $this->sqlState = $sqlState;
  3306. }
  3307. /**
  3308. * To String prints both code and SQL state.
  3309. *
  3310. * @return string $message prints this exception instance as a string
  3311. */
  3312. public function __toString() {
  3313. return '['.$this->getSQLState().'] - '.$this->getMessage();
  3314. }
  3315. }
  3316. class RedBean_Exception_Security extends RedBean_Exception {}
  3317. class RedBean_OODB extends RedBean_Observable {
  3318. /**
  3319. * @var array
  3320. */
  3321. protected $chillList = array();
  3322. /**
  3323. * @var array
  3324. */
  3325. protected $dep = array();
  3326. /**
  3327. * @var array
  3328. */
  3329. protected $stash = NULL;
  3330. /**
  3331. * @var RedBean_Adapter_DBAdapter
  3332. */
  3333. protected $writer;
  3334. /**
  3335. * @var boolean
  3336. */
  3337. protected $isFrozen = false;
  3338. /**
  3339. * @var null|\RedBean_BeanHelperFacade
  3340. */
  3341. protected $beanhelper = null;
  3342. /**
  3343. * @var RedBean_AssociationManager
  3344. */
  3345. protected $assocManager = null;
  3346. /**
  3347. * Constructor, requires a query writer.
  3348. *
  3349. * @param RedBean_QueryWriter $writer
  3350. */
  3351. public function __construct(RedBean_QueryWriter $writer) {
  3352. if ($writer instanceof RedBean_QueryWriter) $this->writer = $writer;
  3353. $this->beanhelper = new RedBean_BeanHelper_Facade();
  3354. }
  3355. /**
  3356. * Toggles fluid or frozen mode. In fluid mode the database
  3357. * structure is adjusted to accomodate your objects. In frozen mode
  3358. * this is not the case.
  3359. *
  3360. * You can also pass an array containing a selection of frozen types.
  3361. * Let's call this chilly mode, it's just like fluid mode except that
  3362. * certain types (i.e. tables) aren't touched.
  3363. *
  3364. * @param boolean|array $trueFalse
  3365. */
  3366. public function freeze($tf) {
  3367. if (is_array($tf)) {
  3368. $this->chillList = $tf;
  3369. $this->isFrozen = false;
  3370. } else $this->isFrozen = (boolean) $tf;
  3371. }
  3372. /**
  3373. * Returns the current mode of operation of RedBean.
  3374. * In fluid mode the database
  3375. * structure is adjusted to accomodate your objects.
  3376. * In frozen mode
  3377. * this is not the case.
  3378. *
  3379. * @return boolean $yesNo TRUE if frozen, FALSE otherwise
  3380. */
  3381. public function isFrozen() {
  3382. return (bool) $this->isFrozen;
  3383. }
  3384. /**
  3385. * Dispenses a new bean (a RedBean_OODBBean Bean Object)
  3386. * of the specified type. Always
  3387. * use this function to get an empty bean object. Never
  3388. * instantiate a RedBean_OODBBean yourself because it needs
  3389. * to be configured before you can use it with RedBean. This
  3390. * function applies the appropriate initialization /
  3391. * configuration for you.
  3392. *
  3393. * @param string $type type of bean you want to dispense
  3394. * @param string $number number of beans you would like to get
  3395. *
  3396. * @return RedBean_OODBBean $bean the new bean instance
  3397. */
  3398. public function dispense($type, $number = 1) {
  3399. $beans = array();
  3400. for($i = 0; $i < $number; $i++){
  3401. $bean = new RedBean_OODBBean;
  3402. $bean->setBeanHelper($this->beanhelper);
  3403. $bean->setMeta('type', $type );
  3404. $bean->setMeta('sys.id', 'id');
  3405. $bean->id = 0;
  3406. if (!$this->isFrozen) $this->check($bean);
  3407. $bean->setMeta('tainted', true);
  3408. $bean->setMeta('sys.orig', array('id' => 0));
  3409. $this->signal('dispense', $bean );
  3410. $beans[] = $bean;
  3411. }
  3412. return (count($beans) === 1) ? array_pop($beans) : $beans;
  3413. }
  3414. /**
  3415. * Sets bean helper to be given to beans.
  3416. * Bean helpers assist beans in getting a reference to a toolbox.
  3417. *
  3418. * @param RedBean_IBeanHelper $beanhelper helper
  3419. *
  3420. * @return void
  3421. */
  3422. public function setBeanHelper(RedBean_BeanHelper $beanhelper) {
  3423. $this->beanhelper = $beanhelper;
  3424. }
  3425. /**
  3426. * Checks whether a RedBean_OODBBean bean is valid.
  3427. * If the type is not valid or the ID is not valid it will
  3428. * throw an exception: RedBean_Exception_Security.
  3429. * @throws RedBean_Exception_Security $exception
  3430. *
  3431. * @param RedBean_OODBBean $bean the bean that needs to be checked
  3432. *
  3433. * @return void
  3434. */
  3435. public function check(RedBean_OODBBean $bean) {
  3436. //Is all meta information present?
  3437. if (!isset($bean->id) ) {
  3438. throw new RedBean_Exception_Security('Bean has incomplete Meta Information id ');
  3439. }
  3440. if (!is_numeric($bean->id)) {
  3441. throw new RedBean_Exception_Security('ID must be numeric.');
  3442. }
  3443. if (!($bean->getMeta('type'))) {
  3444. throw new RedBean_Exception_Security('Bean has incomplete Meta Information II');
  3445. }
  3446. //Pattern of allowed characters
  3447. $pattern = '/[^a-z0-9_]/i';
  3448. //Does the type contain invalid characters?
  3449. if (preg_match($pattern, $bean->getMeta('type'))) {
  3450. throw new RedBean_Exception_Security('Bean Type is invalid');
  3451. }
  3452. //Are the properties and values valid?
  3453. foreach($bean as $prop => $value) {
  3454. if (
  3455. is_array($value) ||
  3456. (is_object($value)) ||
  3457. strlen($prop) < 1 ||
  3458. preg_match($pattern, $prop)
  3459. ) {
  3460. throw new RedBean_Exception_Security("Invalid Bean: property $prop ");
  3461. }
  3462. }
  3463. }
  3464. /**
  3465. * Searches the database for a bean that matches conditions $conditions and sql $addSQL
  3466. * and returns an array containing all the beans that have been found.
  3467. *
  3468. * Conditions need to take form:
  3469. *
  3470. * array(
  3471. * 'PROPERTY' => array( POSSIBLE VALUES... 'John', 'Steve' )
  3472. * 'PROPERTY' => array( POSSIBLE VALUES... )
  3473. * );
  3474. *
  3475. * All conditions are glued together using the AND-operator, while all value lists
  3476. * are glued using IN-operators thus acting as OR-conditions.
  3477. *
  3478. * Note that you can use property names; the columns will be extracted using the
  3479. * appropriate bean formatter.
  3480. *
  3481. * @throws RedBean_Exception_SQL
  3482. *
  3483. * @param string $type type of beans you are looking for
  3484. * @param array $conditions list of conditions
  3485. * @param string $addSQL SQL to be used in query
  3486. * @param boolean $all whether you prefer to use a WHERE clause or not (TRUE = not)
  3487. *
  3488. * @return array $beans resulting beans
  3489. */
  3490. public function find($type, $conditions = array(), $addSQL = null, $all = false) {
  3491. try {
  3492. $beans = $this->convertToBeans($type, $this->writer->selectRecord($type, $conditions, $addSQL, false, false, $all));
  3493. return $beans;
  3494. } catch(RedBean_Exception_SQL $e) {
  3495. if (!$this->writer->sqlStateIn($e->getSQLState(),
  3496. array(
  3497. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE,
  3498. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN)
  3499. )) throw $e;
  3500. }
  3501. return array();
  3502. }
  3503. /**
  3504. * Checks whether the specified table already exists in the database.
  3505. * Not part of the Object Database interface!
  3506. *
  3507. * @param string $table table name (not type!)
  3508. *
  3509. * @return boolean $exists whether the given table exists within this database.
  3510. */
  3511. public function tableExists($table) {
  3512. $tables = $this->writer->getTables();
  3513. return in_array(($table), $tables);
  3514. }
  3515. /**
  3516. * Processes all column based build commands.
  3517. * A build command is an additional instruction for the Query Writer. It is processed only when
  3518. * a column gets created. The build command is often used to instruct the writer to write some
  3519. * extra SQL to create indexes or constraints. Build commands are stored in meta data of the bean.
  3520. * They are only for internal use, try to refrain from using them in your code directly.
  3521. *
  3522. * @param string $table name of the table to process build commands for
  3523. * @param string $property name of the property to process build commands for
  3524. * @param RedBean_OODBBean $bean bean that contains the build commands
  3525. *
  3526. * @return void
  3527. */
  3528. protected function processBuildCommands($table, $property, RedBean_OODBBean $bean) {
  3529. if ($inx = ($bean->getMeta('buildcommand.indexes'))) {
  3530. if (isset($inx[$property])) $this->writer->addIndex($table, $inx[$property], $property);
  3531. }
  3532. }
  3533. /**
  3534. * Process groups. Internal function. Processes different kind of groups for
  3535. * storage function. Given a list of original beans and a list of current beans,
  3536. * this function calculates which beans remain in the list (residue), which
  3537. * have been deleted (are in the trashcan) and which beans have been added
  3538. * (additions).
  3539. *
  3540. * @param array $originals originals
  3541. * @param array $current the current beans
  3542. * @param array $additions beans that have been added
  3543. * @param array $trashcan beans that have been deleted
  3544. * @param array $residue beans that have been left untouched
  3545. *
  3546. * @return array $result new relational state
  3547. */
  3548. private function processGroups($originals, $current, $additions, $trashcan, $residue) {
  3549. return array(
  3550. array_merge($additions, array_diff($current, $originals)),
  3551. array_merge($trashcan, array_diff($originals, $current)),
  3552. array_merge($residue, array_intersect($current, $originals))
  3553. );
  3554. }
  3555. /**
  3556. * Figures out the desired type given the cast string ID.
  3557. *
  3558. * @param string $cast cast identifier
  3559. *
  3560. * @return integer $typeno
  3561. */
  3562. private function getTypeFromCast($cast) {
  3563. if ($cast == 'string') {
  3564. $typeno = $this->writer->scanType('STRING');
  3565. } elseif ($cast == 'id') {
  3566. $typeno = $this->writer->getTypeForID();
  3567. } elseif(isset($this->writer->sqltype_typeno[$cast])) {
  3568. $typeno = $this->writer->sqltype_typeno[$cast];
  3569. } else {
  3570. throw new RedBean_Exception('Invalid Cast');
  3571. }
  3572. return $typeno;
  3573. }
  3574. /**
  3575. * Processes an embedded bean. First the bean gets unboxed if possible.
  3576. * Then, the bean is stored if needed and finally the ID of the bean
  3577. * will be returned.
  3578. *
  3579. * @param RedBean_OODBBean|Model $v the bean or model
  3580. *
  3581. * @return integer $id
  3582. */
  3583. private function prepareEmbeddedBean($v) {
  3584. if (!$v->id || $v->getMeta('tainted')) {
  3585. $this->store($v);
  3586. }
  3587. return $v->id;
  3588. }
  3589. /**
  3590. * Stores a bean in the database. This function takes a
  3591. * RedBean_OODBBean Bean Object $bean and stores it
  3592. * in the database. If the database schema is not compatible
  3593. * with this bean and RedBean runs in fluid mode the schema
  3594. * will be altered to store the bean correctly.
  3595. * If the database schema is not compatible with this bean and
  3596. * RedBean runs in frozen mode it will throw an exception.
  3597. * This function returns the primary key ID of the inserted
  3598. * bean.
  3599. *
  3600. * @throws RedBean_Exception_Security $exception
  3601. *
  3602. * @param RedBean_OODBBean | RedBean_SimpleModel $bean bean to store
  3603. *
  3604. * @return integer $newid resulting ID of the new bean
  3605. */
  3606. public function store($bean) {
  3607. if ($bean instanceof RedBean_SimpleModel) $bean = $bean->unbox();
  3608. if (!($bean instanceof RedBean_OODBBean)) throw new RedBean_Exception_Security('OODB Store requires a bean, got: '.gettype($bean));
  3609. $processLists = false;
  3610. foreach($bean as $k => $v) if (is_array($v) || is_object($v)) { $processLists = true; break; }
  3611. if (!$processLists && !$bean->getMeta('tainted')) return $bean->getID();
  3612. $this->signal('update', $bean );
  3613. foreach($bean as $k => $v) if (is_array($v) || is_object($v)) { $processLists = true; break; }
  3614. if ($processLists) {
  3615. //Define groups
  3616. $sharedAdditions = $sharedTrashcan = $sharedresidue = $sharedItems = array();
  3617. $ownAdditions = $ownTrashcan = $ownresidue = array();
  3618. $tmpCollectionStore = array();
  3619. $embeddedBeans = array();
  3620. foreach($bean as $p => $v) {
  3621. if ($v instanceof RedBean_SimpleModel) $v = $v->unbox();
  3622. if ($v instanceof RedBean_OODBBean) {
  3623. $linkField = $p.'_id';
  3624. $bean->$linkField = $this->prepareEmbeddedBean($v);
  3625. $bean->setMeta('cast.'.$linkField, 'id');
  3626. $embeddedBeans[$linkField] = $v;
  3627. $tmpCollectionStore[$p] = $bean->$p;
  3628. $bean->removeProperty($p);
  3629. }
  3630. if (is_array($v)) {
  3631. $originals = $bean->getMeta('sys.shadow.'.$p);
  3632. if (!$originals) $originals = array();
  3633. if (strpos($p, 'own') === 0) {
  3634. list($ownAdditions, $ownTrashcan, $ownresidue) = $this->processGroups($originals, $v, $ownAdditions, $ownTrashcan, $ownresidue);
  3635. $bean->removeProperty($p);
  3636. } elseif (strpos($p, 'shared') === 0) {
  3637. list($sharedAdditions, $sharedTrashcan, $sharedresidue) = $this->processGroups($originals, $v, $sharedAdditions, $sharedTrashcan, $sharedresidue);
  3638. $bean->removeProperty($p);
  3639. } else {}
  3640. }
  3641. }
  3642. }
  3643. $this->storeBean($bean);
  3644. if ($processLists) {
  3645. $this->processEmbeddedBeans($bean, $embeddedBeans);
  3646. $myFieldLink = $bean->getMeta('type').'_id';
  3647. $this->processTrashcan($bean, $ownTrashcan);
  3648. $this->processAdditions($bean, $ownAdditions);
  3649. $this->processResidue($ownresidue);
  3650. foreach($sharedTrashcan as $trash) $this->assocManager->unassociate($trash, $bean);
  3651. $this->processSharedAdditions($bean, $sharedAdditions);
  3652. foreach($sharedresidue as $residue) $this->store($residue);
  3653. }
  3654. $this->signal('after_update', $bean);
  3655. return (int) $bean->id;
  3656. }
  3657. /**
  3658. * Stores a cleaned bean; i.e. only scalar values. This is the core of the store()
  3659. * method. When all lists and embedded beans (parent objects) have been processed and
  3660. * removed from the original bean the bean is passed to this method to be stored
  3661. * in the database.
  3662. *
  3663. * @param RedBean_OODBBean $bean the clean bean
  3664. */
  3665. private function storeBean(RedBean_OODBBean $bean) {
  3666. if (!$this->isFrozen) $this->check($bean);
  3667. //what table does it want
  3668. $table = $bean->getMeta('type');
  3669. if ($bean->getMeta('tainted')) {
  3670. //Does table exist? If not, create
  3671. if (!$this->isFrozen && !$this->tableExists($this->writer->esc($table, true))) {
  3672. $this->writer->createTable($table);
  3673. $bean->setMeta('buildreport.flags.created', true);
  3674. }
  3675. if (!$this->isFrozen) {
  3676. $columns = $this->writer->getColumns($table) ;
  3677. }
  3678. //does the table fit?
  3679. $insertvalues = array();
  3680. $insertcolumns = array();
  3681. $updatevalues = array();
  3682. foreach($bean as $p => $v) {
  3683. $origV = $v;
  3684. if ($p !== 'id') {
  3685. if (!$this->isFrozen) {
  3686. //Not in the chill list?
  3687. if (!in_array($bean->getMeta('type'), $this->chillList)) {
  3688. //Does the user want to specify the type?
  3689. if ($bean->getMeta("cast.$p", -1) !== -1) {
  3690. $cast = $bean->getMeta("cast.$p");
  3691. $typeno = $this->getTypeFromCast($cast);
  3692. } else {
  3693. $cast = false;
  3694. //What kind of property are we dealing with?
  3695. $typeno = $this->writer->scanType($v, true);
  3696. }
  3697. //Is this property represented in the table?
  3698. if (isset($columns[$this->writer->esc($p, true)])) {
  3699. //rescan
  3700. $v = $origV;
  3701. if (!$cast) $typeno = $this->writer->scanType($v, false);
  3702. //yes it is, does it still fit?
  3703. $sqlt = $this->writer->code($columns[$this->writer->esc($p, true)]);
  3704. if ($typeno > $sqlt) {
  3705. //no, we have to widen the database column type
  3706. $this->writer->widenColumn($table, $p, $typeno);
  3707. $bean->setMeta('buildreport.flags.widen', true);
  3708. }
  3709. } else {
  3710. //no it is not
  3711. $this->writer->addColumn($table, $p, $typeno);
  3712. $bean->setMeta('buildreport.flags.addcolumn', true);
  3713. //@todo: move build commands here... more practical
  3714. $this->processBuildCommands($table, $p, $bean);
  3715. }
  3716. }
  3717. }
  3718. //Okay, now we are sure that the property value will fit
  3719. $insertvalues[] = $v;
  3720. $insertcolumns[] = $p;
  3721. $updatevalues[] = array('property' => $p, 'value' => $v);
  3722. }
  3723. }
  3724. if (!$this->isFrozen && ($uniques = $bean->getMeta('buildcommand.unique'))) {
  3725. foreach($uniques as $unique) $this->writer->addUniqueIndex($table, $unique);
  3726. }
  3727. $rs = $this->writer->updateRecord($table, $updatevalues, $bean->id);
  3728. $bean->id = $rs;
  3729. $bean->setMeta('tainted', false);
  3730. }
  3731. }
  3732. /**
  3733. * Processes a list of beans from a bean. A bean may contain lists. This
  3734. * method handles shared addition lists; i.e. the $bean->sharedObject properties.
  3735. *
  3736. * @param RedBean_OODBBean $bean the bean
  3737. * @param array $sharedAdditions list with shared additions
  3738. */
  3739. private function processSharedAdditions($bean, $sharedAdditions) {
  3740. foreach($sharedAdditions as $addition) {
  3741. if ($addition instanceof RedBean_OODBBean) {
  3742. $this->assocManager->associate($addition, $bean);
  3743. } else {
  3744. throw new RedBean_Exception_Security('Array may only contain RedBean_OODBBeans');
  3745. }
  3746. }
  3747. }
  3748. /**
  3749. * Processes a list of beans from a bean. A bean may contain lists. This
  3750. * method handles own lists; i.e. the $bean->ownObject properties.
  3751. * A residue is a bean in an own-list that stays where it is. This method
  3752. * checks if there have been any modification to this bean, in that case
  3753. * the bean is stored once again, otherwise the bean will be left untouched.
  3754. *
  3755. * @param RedBean_OODBBean $bean the bean
  3756. * @param array $ownresidue list
  3757. */
  3758. private function processResidue($ownresidue) {
  3759. foreach($ownresidue as $residue) {
  3760. if ($residue->getMeta('tainted')) {
  3761. $this->store($residue);
  3762. }
  3763. }
  3764. }
  3765. /**
  3766. * Processes a list of beans from a bean. A bean may contain lists. This
  3767. * method handles own lists; i.e. the $bean->ownObject properties.
  3768. * A trash can bean is a bean in an own-list that has been removed
  3769. * (when checked with the shadow). This method
  3770. * checks if the bean is also in the dependency list. If it is the bean will be removed.
  3771. * If not, the connection between the bean and the owner bean will be broken by
  3772. * setting the ID to NULL.
  3773. *
  3774. * @param RedBean_OODBBean $bean the bean
  3775. * @param array $ownTrashcan list
  3776. */
  3777. private function processTrashcan($bean, $ownTrashcan) {
  3778. $myFieldLink = $bean->getMeta('type').'_id';
  3779. if (is_array($ownTrashcan) && count($ownTrashcan)>0) {
  3780. $first = reset($ownTrashcan);
  3781. if ($first instanceof RedBean_OODBBean) {
  3782. $alias = $bean->getMeta('sys.alias.'.$first->getMeta('type'));
  3783. if ($alias) $myFieldLink = $alias.'_id';
  3784. }
  3785. }
  3786. foreach($ownTrashcan as $trash) {
  3787. if (isset($this->dep[$trash->getMeta('type')]) && in_array($bean->getMeta('type'), $this->dep[$trash->getMeta('type')])) {
  3788. $this->trash($trash);
  3789. } else {
  3790. $trash->$myFieldLink = null;
  3791. $this->store($trash);
  3792. }
  3793. }
  3794. }
  3795. /**
  3796. * Processes embedded beans.
  3797. * Each embedded bean will be indexed and foreign keys will
  3798. * be created if the bean is in the dependency list.
  3799. *
  3800. * @param RedBean_OODBBean $bean bean
  3801. * @param array $embeddedBeans embedded beans
  3802. */
  3803. private function processEmbeddedBeans($bean, $embeddedBeans) {
  3804. foreach($embeddedBeans as $linkField => $embeddedBean) {
  3805. if (!$this->isFrozen) {
  3806. $this->writer->addIndex($bean->getMeta('type'),
  3807. 'index_foreignkey_'.$bean->getMeta('type').'_'.$embeddedBean->getMeta('type'),
  3808. $linkField);
  3809. $isDep = $this->isDependentOn($bean->getMeta('type'), $embeddedBean->getMeta('type'));
  3810. $this->writer->addFK($bean->getMeta('type'), $embeddedBean->getMeta('type'), $linkField, 'id', $isDep);
  3811. }
  3812. }
  3813. }
  3814. /**
  3815. * Part of the store() functionality.
  3816. * Handles all new additions after the bean has been saved.
  3817. * Stores addition bean in own-list, extracts the id and
  3818. * adds a foreign key. Also adds a constraint in case the type is
  3819. * in the dependent list.
  3820. *
  3821. * @param RedBean_OODBBean $bean bean
  3822. * @param array $ownAdditions list of addition beans in own-list
  3823. */
  3824. private function processAdditions($bean, $ownAdditions) {
  3825. $myFieldLink = $bean->getMeta('type').'_id';
  3826. if ($bean && count($ownAdditions)>0) {
  3827. $first = reset($ownAdditions);
  3828. if ($first instanceof RedBean_OODBBean) {
  3829. $alias = $bean->getMeta('sys.alias.'.$first->getMeta('type'));
  3830. if ($alias) $myFieldLink = $alias.'_id';
  3831. }
  3832. }
  3833. foreach($ownAdditions as $addition) {
  3834. if ($addition instanceof RedBean_OODBBean) {
  3835. $addition->$myFieldLink = $bean->id;
  3836. $addition->setMeta('cast.'.$myFieldLink, 'id');
  3837. $this->store($addition);
  3838. if (!$this->isFrozen) {
  3839. $this->writer->addIndex($addition->getMeta('type'),
  3840. 'index_foreignkey_'.$addition->getMeta('type').'_'.$bean->getMeta('type'),
  3841. $myFieldLink);
  3842. $isDep = $this->isDependentOn($addition->getMeta('type'), $bean->getMeta('type'));
  3843. $this->writer->addFK($addition->getMeta('type'), $bean->getMeta('type'), $myFieldLink, 'id', $isDep);
  3844. }
  3845. } else {
  3846. throw new RedBean_Exception_Security('Array may only contain RedBean_OODBBeans');
  3847. }
  3848. }
  3849. }
  3850. /**
  3851. * Checks whether reference type has been marked as dependent on target type.
  3852. * This is the result of setting reference type as a key in R::dependencies() and
  3853. * putting target type in its array.
  3854. *
  3855. * @param string $refType reference type
  3856. * @param string $otherType other type / target type
  3857. *
  3858. * @return boolean
  3859. */
  3860. protected function isDependentOn($refType, $otherType) {
  3861. return (boolean) (isset($this->dep[$refType]) && in_array($otherType, $this->dep[$refType]));
  3862. }
  3863. /**
  3864. * Loads a bean from the object database.
  3865. * It searches for a RedBean_OODBBean Bean Object in the
  3866. * database. It does not matter how this bean has been stored.
  3867. * RedBean uses the primary key ID $id and the string $type
  3868. * to find the bean. The $type specifies what kind of bean you
  3869. * are looking for; this is the same type as used with the
  3870. * dispense() function. If RedBean finds the bean it will return
  3871. * the RedBean_OODB Bean object; if it cannot find the bean
  3872. * RedBean will return a new bean of type $type and with
  3873. * primary key ID 0. In the latter case it acts basically the
  3874. * same as dispense().
  3875. *
  3876. * Important note:
  3877. * If the bean cannot be found in the database a new bean of
  3878. * the specified type will be generated and returned.
  3879. *
  3880. * @param string $type type of bean you want to load
  3881. * @param integer $id ID of the bean you want to load
  3882. *
  3883. * @return RedBean_OODBBean $bean loaded bean
  3884. */
  3885. public function load($type, $id) {
  3886. $bean = $this->dispense($type);
  3887. if ($this->stash && isset($this->stash[$id])) {
  3888. $row = $this->stash[$id];
  3889. } else {
  3890. try {
  3891. $rows = $this->writer->selectRecord($type, array('id' => array($id)));
  3892. } catch(RedBean_Exception_SQL $e ) {
  3893. if (
  3894. $this->writer->sqlStateIn($e->getSQLState(),
  3895. array(
  3896. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  3897. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
  3898. )
  3899. ) {
  3900. $rows = 0;
  3901. if ($this->isFrozen) throw $e; //only throw if frozen;
  3902. }
  3903. }
  3904. if (empty($rows)) return $bean;
  3905. $row = array_pop($rows);
  3906. }
  3907. $bean->setMeta('sys.orig', $row);
  3908. foreach($row as $p => $v) {
  3909. $bean->$p = $v;
  3910. }
  3911. $this->signal('open', $bean);
  3912. $bean->setMeta('tainted', false);
  3913. return $bean;
  3914. }
  3915. /**
  3916. * Removes a bean from the database.
  3917. * This function will remove the specified RedBean_OODBBean
  3918. * Bean Object from the database.
  3919. *
  3920. * @throws RedBean_Exception_Security $exception
  3921. *
  3922. * @param RedBean_OODBBean|RedBean_SimpleModel $bean bean you want to remove from database
  3923. */
  3924. public function trash($bean) {
  3925. if ($bean instanceof RedBean_SimpleModel) $bean = $bean->unbox();
  3926. if (!($bean instanceof RedBean_OODBBean)) throw new RedBean_Exception_Security('OODB Store requires a bean, got: '.gettype($bean));
  3927. $this->signal('delete', $bean);
  3928. foreach($bean as $p => $v) {
  3929. if ($v instanceof RedBean_OODBBean) {
  3930. $bean->removeProperty($p);
  3931. }
  3932. if (is_array($v)) {
  3933. if (strpos($p, 'own') === 0) {
  3934. $bean->removeProperty($p);
  3935. } elseif (strpos($p, 'shared') === 0) {
  3936. $bean->removeProperty($p);
  3937. }
  3938. }
  3939. }
  3940. if (!$this->isFrozen) $this->check($bean);
  3941. try {
  3942. $this->writer->selectRecord($bean->getMeta('type'),
  3943. array('id' => array($bean->id)), null, true );
  3944. }catch(RedBean_Exception_SQL $e) {
  3945. if (!$this->writer->sqlStateIn($e->getSQLState(),
  3946. array(
  3947. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  3948. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
  3949. )) throw $e;
  3950. }
  3951. $bean->id = 0;
  3952. $this->signal('after_delete', $bean);
  3953. }
  3954. /**
  3955. * Returns an array of beans. Pass a type and a series of ids and
  3956. * this method will bring you the correspondig beans.
  3957. *
  3958. * important note: Because this method loads beans using the load()
  3959. * function (but faster) it will return empty beans with ID 0 for
  3960. * every bean that could not be located. The resulting beans will have the
  3961. * passed IDs as their keys.
  3962. *
  3963. * @param string $type type of beans
  3964. * @param array $ids ids to load
  3965. *
  3966. * @return array $beans resulting beans (may include empty ones)
  3967. */
  3968. public function batch($type, $ids) {
  3969. if (!$ids) return array();
  3970. $collection = array();
  3971. try {
  3972. $rows = $this->writer->selectRecord($type, array('id' => $ids));
  3973. } catch(RedBean_Exception_SQL $e) {
  3974. if (!$this->writer->sqlStateIn($e->getSQLState(),
  3975. array(
  3976. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  3977. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
  3978. )) throw $e;
  3979. $rows = false;
  3980. }
  3981. $this->stash = array();
  3982. if (!$rows) return array();
  3983. foreach($rows as $row) {
  3984. $this->stash[$row['id']] = $row;
  3985. }
  3986. foreach($ids as $id) {
  3987. $collection[$id] = $this->load($type, $id);
  3988. }
  3989. $this->stash = NULL;
  3990. return $collection;
  3991. }
  3992. /**
  3993. * This is a convenience method; it converts database rows
  3994. * (arrays) into beans. Given a type and a set of rows this method
  3995. * will return an array of beans of the specified type loaded with
  3996. * the data fields provided by the result set from the database.
  3997. *
  3998. * @param string $type type of beans you would like to have
  3999. * @param array $rows rows from the database result
  4000. *
  4001. * @return array $collectionOfBeans collection of beans
  4002. */
  4003. public function convertToBeans($type, $rows) {
  4004. $collection = array();
  4005. $this->stash = array();
  4006. foreach($rows as $row) {
  4007. $id = $row['id'];
  4008. $this->stash[$id] = $row;
  4009. $collection[$id] = $this->load($type, $id);
  4010. }
  4011. $this->stash = NULL;
  4012. return $collection;
  4013. }
  4014. /**
  4015. * Returns the number of beans we have in DB of a given type.
  4016. *
  4017. * @param string $type type of bean we are looking for
  4018. * @param string $addSQL additional SQL snippet
  4019. * @param array $params parameters to bind to SQL
  4020. *
  4021. * @return integer $num number of beans found
  4022. */
  4023. public function count($type, $addSQL = '', $params = array()) {
  4024. try {
  4025. return (int) $this->writer->count($type, $addSQL, $params);
  4026. } catch(RedBean_Exception_SQL $e) {
  4027. if (!$this->writer->sqlStateIn($e->getSQLState(),array(RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE))) throw $e;
  4028. }
  4029. return 0;
  4030. }
  4031. /**
  4032. * Trash all beans of a given type.
  4033. *
  4034. * @param string $type type
  4035. *
  4036. * @return boolean $yesNo whether we actually did some work or not..
  4037. */
  4038. public function wipe($type) {
  4039. try {
  4040. $this->writer->wipe($type);
  4041. return true;
  4042. } catch(RedBean_Exception_SQL $e) {
  4043. if (!$this->writer->sqlStateIn($e->getSQLState(),
  4044. array(RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
  4045. )) throw $e;
  4046. return false;
  4047. }
  4048. }
  4049. /**
  4050. * Returns an Association Manager for use with OODB.
  4051. * A simple getter function to obtain a reference to the association manager used for
  4052. * storage and more.
  4053. *
  4054. * @throws Exception
  4055. * @return RedBean_AssociationManager $assoc Association Manager
  4056. */
  4057. public function getAssociationManager() {
  4058. if (!isset($this->assocManager)) throw new Exception('No association manager available.');
  4059. return $this->assocManager;
  4060. }
  4061. /**
  4062. * Sets the association manager instance to be used by this OODB.
  4063. * A simple setter function to set the association manager to be used for storage and
  4064. * more.
  4065. *
  4066. * @param RedBean_AssociationManager $assoc sets the association manager to be used
  4067. *
  4068. * @return void
  4069. */
  4070. public function setAssociationManager(RedBean_AssociationManager $assoc) {
  4071. $this->assocManager = $assoc;
  4072. }
  4073. /**
  4074. * Sets a dependency list. Dependencies can be used to make
  4075. * certain beans depend on others. This causes dependent beans to get removed
  4076. * once the bean they depend on has been removed as well.
  4077. * A dependency takes the form:
  4078. *
  4079. * $me => depends on array( $bean1, $bean2 )
  4080. *
  4081. * For instance a to inform RedBeanPHP about the fact that a page
  4082. * depends on a book:
  4083. *
  4084. * 'page' => array('book')
  4085. *
  4086. * A bean can depend on multiple other beans.
  4087. *
  4088. * A dependency does two things:
  4089. *
  4090. * 1. Adds a ON CASCADE DELETE
  4091. * 2. trashes the depending bean if the entry in the ownList is removed
  4092. *
  4093. * @param array $dep
  4094. */
  4095. public function setDepList($dep) {
  4096. $this->dep = $dep;
  4097. }
  4098. /**
  4099. * Preloads certain properties for beans.
  4100. * Understands aliases.
  4101. *
  4102. * Usage: $redbean->preload($books, array('coauthor'=>'author'));
  4103. *
  4104. * Usage for nested beans:
  4105. *
  4106. * $redbean->preload($texts, array('page', 'page.book', 'page.book.author'));
  4107. *
  4108. * preloads pages, books and authors.
  4109. * You may also use a shortcut here:
  4110. *
  4111. * $redbean->preload($texts, array('page', '*.book', '*.author'));
  4112. *
  4113. * Can also load preload lists:
  4114. *
  4115. * $redbean->preload($books, array('ownPage'=>'page', '*.ownText'=>'text', 'sharedTag'=>'tag'));
  4116. *
  4117. * @param array $beans beans
  4118. * @param array $types types to load
  4119. */
  4120. public function preload($beans, $types, $closure = null) {
  4121. if (is_string($types)) $types = explode(',', $types);
  4122. $oldFields = array(); $i = 0; $retrievals = array(); $oldField = '';
  4123. foreach($types as $key => $typeInfo) {
  4124. list($type,$sqlObj) = (is_array($typeInfo) ? $typeInfo : array($typeInfo, null));
  4125. $map = $ids = $retrievals[$i] = array();
  4126. $field = (is_numeric($key)) ? $type : $key;//use an alias?
  4127. if (strpos($field, '*') !== false) {
  4128. $oldFields[]= $oldField;
  4129. $field = str_replace('*', implode('.', $oldFields), $field);
  4130. }
  4131. if (strpos($field, '&') !== false) $field = str_replace('&', implode('.', $oldFields), $field);
  4132. $filteredBeans = $beans;
  4133. $counterID = 0;
  4134. foreach($filteredBeans as $bean) {
  4135. $bean->setMeta('sys.input-bean-id', array($counterID => $counterID));
  4136. $counterID++;
  4137. }
  4138. while($p = strpos($field, '.')) { //filtering: find the right beans in the path
  4139. $nesting = substr($field, 0, $p);
  4140. $filtered = array();
  4141. foreach($filteredBeans as $bean) {
  4142. $inputBeanID = $bean->getMeta('sys.input-bean-id');
  4143. if (is_array($bean->$nesting)) {
  4144. $nestedBeans = $bean->$nesting;
  4145. foreach($nestedBeans as $nestedBean) {
  4146. $currentInputBeanIDs = $nestedBean->getMeta('sys.input-bean-id');
  4147. if (!is_array($currentInputBeanIDs)) $currentInputBeanIDs = array();
  4148. $addInputIDs = $bean->getMeta('sys.input-bean-id');
  4149. foreach($addInputIDs as $addInputID) $currentInputBeanIDs[$addInputID] = $addInputID;
  4150. $nestedBean->setMeta('sys.input-bean-id', $currentInputBeanIDs);
  4151. }
  4152. $filtered = array_merge($filtered, $nestedBeans);
  4153. } elseif (!is_null($bean->$nesting)) {
  4154. $nestedBean = $bean->$nesting;
  4155. $currentInputBeanIDs = $nestedBean->getMeta('sys.input-bean-id');
  4156. if (!is_array($currentInputBeanIDs)) $currentInputBeanIDs = array();
  4157. $addInputIDs = $bean->getMeta('sys.input-bean-id');
  4158. foreach($addInputIDs as $addInputID) $currentInputBeanIDs[$addInputID] = $addInputID;
  4159. $nestedBean->setMeta('sys.input-bean-id', $currentInputBeanIDs);
  4160. $filtered[] = $bean->$nesting;
  4161. }
  4162. }
  4163. $filteredBeans = $filtered;
  4164. $field = substr($field, $p+1);
  4165. }
  4166. $oldField = $field;
  4167. if (strpos($type, '.')) $type = $field;
  4168. if (strpos($field, 'shared') !== 0) {
  4169. foreach($filteredBeans as $bean) { //gather ids to load the desired bean collections
  4170. if (strpos($field, 'own') === 0) { //based on bean->id for ownlist
  4171. $id = $bean->id; $ids[$id] = $id;
  4172. } elseif($id = $bean->{$field.'_id'}){ //based on bean_id for parent
  4173. $ids[$id] = $id;
  4174. if (!isset($map[$id])) $map[$id] = array();
  4175. $map[$id][] = $bean;
  4176. }
  4177. }
  4178. }
  4179. if (strpos($field, 'shared') === 0) {
  4180. $bean = reset($filteredBeans);
  4181. $link = $bean->getMeta('type').'_id';
  4182. $keys = $this->assocManager->related($filteredBeans, $type, true);
  4183. $linkTable = $this->assocManager->getTable(array($type, $bean->getMeta('type')));
  4184. $linkBeans = $this->batch($linkTable, $keys);
  4185. $linked = $targetIDs = array();
  4186. $targetIDField = $type.'_id';
  4187. foreach($linkBeans as $linkBean) {
  4188. $linkID = $linkBean->$link;
  4189. if (!isset($linked[$linkID])) $linked[$linkID] = array();
  4190. $linked[$linkID][] = $linkBean;
  4191. $targetIDs[$linkBean->$targetIDField] = $linkBean->$targetIDField;
  4192. }
  4193. $sharedBeans = $this->find($type, array('id' => $targetIDs), $sqlObj, (!is_null($sqlObj)));
  4194. foreach($filteredBeans as $filteredBean) {
  4195. $list = array();
  4196. if (isset($linked[$filteredBean->id])) {
  4197. foreach($linked[$filteredBean->id] as $linkBean) {
  4198. foreach($sharedBeans as $sharedBean) {
  4199. if ($sharedBean->id == $linkBean->$targetIDField) $list[$sharedBean->id] = $sharedBean;
  4200. }
  4201. }
  4202. }
  4203. $filteredBean->setProperty($field, $list);
  4204. $inputBeanIDs = $filteredBean->getMeta('sys.input-bean-id');
  4205. foreach($inputBeanIDs as $inputBeanID) {
  4206. if (!isset($retrievals[$i][$inputBeanID])) $retrievals[$i][$inputBeanID] = array();
  4207. foreach($list as $listKey => $listBean) $retrievals[$i][$inputBeanID][$listKey] = $listBean;
  4208. }
  4209. }
  4210. } elseif (strpos($field, 'own') === 0) {//preload for own-list using find
  4211. $link = $bean->getMeta('type').'_id';
  4212. $children = $this->find($type, array($link => $ids), $sqlObj, (!is_null($sqlObj)));
  4213. foreach($filteredBeans as $filteredBean) {
  4214. $list = array();
  4215. foreach($children as $child) if ($child->$link == $filteredBean->id) $list[$child->id] = $child;
  4216. $filteredBean->setProperty($field, $list);
  4217. $inputBeanIDs = $filteredBean->getMeta('sys.input-bean-id');
  4218. foreach($inputBeanIDs as $inputBeanID) {
  4219. if (!isset($retrievals[$i][$inputBeanID])) $retrievals[$i][$inputBeanID] = array();
  4220. foreach($list as $listKey => $listBean) $retrievals[$i][$inputBeanID][$listKey] = $listBean;
  4221. }
  4222. }
  4223. } else { //preload for parent objects using batch()
  4224. foreach($this->batch($type, $ids) as $parent) {
  4225. foreach($map[$parent->id] as $childBean) {
  4226. $childBean->setProperty($field, $parent);
  4227. $inputBeanIDs = $childBean->getMeta('sys.input-bean-id');
  4228. foreach($inputBeanIDs as $inputBeanID) $retrievals[$i][$inputBeanID] = $parent;
  4229. }
  4230. }
  4231. }
  4232. $i++;
  4233. }
  4234. if ($closure) {
  4235. $key = 0;
  4236. foreach($beans as $bean) {
  4237. $params = array();
  4238. foreach($retrievals as $r) $params[] = (isset($r[$key])) ? $r[$key] : null;
  4239. array_unshift($params, $bean);
  4240. call_user_func_array($closure, $params);
  4241. $key ++;
  4242. }
  4243. }
  4244. }
  4245. }
  4246. class RedBean_ToolBox {
  4247. /**
  4248. * @var RedBean_OODB
  4249. */
  4250. protected $oodb;
  4251. /**
  4252. * @var RedBean_QueryWriter
  4253. */
  4254. protected $writer;
  4255. /**
  4256. * @var RedBean_Adapter_DBAdapter
  4257. */
  4258. protected $adapter;
  4259. /**
  4260. * Constructor.
  4261. *
  4262. * @param RedBean_OODB $oodb Object Database
  4263. * @param RedBean_Adapter_DBAdapter $adapter Adapter
  4264. * @param RedBean_QueryWriter $writer Writer
  4265. *
  4266. * return RedBean_ToolBox $toolbox Toolbox
  4267. */
  4268. public function __construct(RedBean_OODB $oodb, RedBean_Adapter $adapter, RedBean_QueryWriter $writer) {
  4269. $this->oodb = $oodb;
  4270. $this->adapter = $adapter;
  4271. $this->writer = $writer;
  4272. return $this;
  4273. }
  4274. /**
  4275. * Returns the query writer in this toolbox.
  4276. *
  4277. * @return RedBean_QueryWriter $writer writer
  4278. */
  4279. public function getWriter() {
  4280. return $this->writer;
  4281. }
  4282. /**
  4283. * Returns the OODB instance in this toolbox.
  4284. *
  4285. * @return RedBean_OODB $oodb Object Database
  4286. */
  4287. public function getRedBean() {
  4288. return $this->oodb;
  4289. }
  4290. /**
  4291. * Returns the database adapter in this toolbox.
  4292. *
  4293. * @return RedBean_Adapter_DBAdapter $adapter Adapter
  4294. */
  4295. public function getDatabaseAdapter() {
  4296. return $this->adapter;
  4297. }
  4298. }
  4299. class RedBean_AssociationManager extends RedBean_Observable {
  4300. /**
  4301. * @var RedBean_OODB
  4302. */
  4303. protected $oodb;
  4304. /**
  4305. * @var RedBean_Adapter_DBAdapter
  4306. */
  4307. protected $adapter;
  4308. /**
  4309. * @var RedBean_QueryWriter
  4310. */
  4311. protected $writer;
  4312. /**
  4313. * Constructor
  4314. *
  4315. * @param RedBean_ToolBox $tools toolbox
  4316. */
  4317. public function __construct(RedBean_ToolBox $tools) {
  4318. $this->oodb = $tools->getRedBean();
  4319. $this->adapter = $tools->getDatabaseAdapter();
  4320. $this->writer = $tools->getWriter();
  4321. $this->toolbox = $tools;
  4322. }
  4323. /**
  4324. * Creates a table name based on a types array.
  4325. * Manages the get the correct name for the linking table for the
  4326. * types provided.
  4327. *
  4328. * @todo find a nice way to decouple this class from QueryWriter?
  4329. *
  4330. * @param array $types 2 types as strings
  4331. *
  4332. * @return string $table table
  4333. */
  4334. public function getTable($types) {
  4335. return RedBean_QueryWriter_AQueryWriter::getAssocTableFormat($types);
  4336. }
  4337. /**
  4338. * Associates two beans with eachother using a many-to-many relation.
  4339. *
  4340. * @param RedBean_OODBBean $bean1 bean1
  4341. * @param RedBean_OODBBean $bean2 bean2
  4342. */
  4343. public function associate($beans1, $beans2) {
  4344. $results = array();
  4345. if (!is_array($beans1)) $beans1 = array($beans1);
  4346. if (!is_array($beans2)) $beans2 = array($beans2);
  4347. foreach($beans1 as $bean1) {
  4348. foreach($beans2 as $bean2) {
  4349. $table = $this->getTable(array($bean1->getMeta('type') , $bean2->getMeta('type')));
  4350. $bean = $this->oodb->dispense($table);
  4351. $results[] = $this->associateBeans($bean1, $bean2, $bean);
  4352. }
  4353. }
  4354. return (count($results)>1) ? $results : reset($results);
  4355. }
  4356. /**
  4357. * Associates a pair of beans. This method associates two beans, no matter
  4358. * what types.Accepts a base bean that contains data for the linking record.
  4359. *
  4360. * @param RedBean_OODBBean $bean1 first bean
  4361. * @param RedBean_OODBBean $bean2 second bean
  4362. * @param RedBean_OODBBean $bean base bean
  4363. *
  4364. * @return mixed $id either the link ID or null
  4365. */
  4366. protected function associateBeans(RedBean_OODBBean $bean1, RedBean_OODBBean $bean2, RedBean_OODBBean $bean) {
  4367. $property1 = $bean1->getMeta('type') . '_id';
  4368. $property2 = $bean2->getMeta('type') . '_id';
  4369. if ($property1 == $property2) $property2 = $bean2->getMeta('type').'2_id';
  4370. //add a build command for Unique Indexes
  4371. $bean->setMeta('buildcommand.unique' , array(array($property1, $property2)));
  4372. //add a build command for Single Column Index (to improve performance in case unqiue cant be used)
  4373. $indexName1 = 'index_for_'.$bean->getMeta('type').'_'.$property1;
  4374. $indexName2 = 'index_for_'.$bean->getMeta('type').'_'.$property2;
  4375. $bean->setMeta('buildcommand.indexes', array($property1 => $indexName1, $property2 => $indexName2));
  4376. $this->oodb->store($bean1);
  4377. $this->oodb->store($bean2);
  4378. $bean->setMeta("cast.$property1", "id");
  4379. $bean->setMeta("cast.$property2", "id");
  4380. $bean->$property1 = $bean1->id;
  4381. $bean->$property2 = $bean2->id;
  4382. try {
  4383. $id = $this->oodb->store($bean);
  4384. //On creation, add constraints....
  4385. if (!$this->oodb->isFrozen() &&
  4386. $bean->getMeta('buildreport.flags.created')){
  4387. $bean->setMeta('buildreport.flags.created', 0);
  4388. if (!$this->oodb->isFrozen())
  4389. $this->writer->addConstraint($bean1, $bean2);
  4390. }
  4391. $results[] = $id;
  4392. } catch(RedBean_Exception_SQL $e) {
  4393. if (!$this->writer->sqlStateIn($e->getSQLState(),
  4394. array(RedBean_QueryWriter::C_SQLSTATE_INTEGRITY_CONSTRAINT_VIOLATION))) throw $e;
  4395. }
  4396. }
  4397. /**
  4398. * Returns all ids of beans of type $type that are related to $bean. If the
  4399. * $getLinks parameter is set to boolean TRUE this method will return the ids
  4400. * of the association beans instead. You can also add additional SQL. This SQL
  4401. * will be appended to the original query string used by this method. Note that this
  4402. * method will not return beans, just keys. For a more convenient method see the R-facade
  4403. * method related(), that is in fact a wrapper for this method that offers a more
  4404. * convenient solution. If you want to make use of this method, consider the
  4405. * OODB batch() method to convert the ids to beans.
  4406. *
  4407. * Since 3.2, you can now also pass an array of beans instead just one
  4408. * bean as the first parameter.
  4409. *
  4410. * @throws RedBean_Exception_SQL
  4411. *
  4412. * @param RedBean_OODBBean|array $bean reference bean
  4413. * @param string $type target type
  4414. * @param bool $getLinks whether you are interested in the assoc records
  4415. * @param bool $sql room for additional SQL
  4416. *
  4417. * @return array $ids
  4418. */
  4419. public function related($bean, $type, $getLinks = false, $sql = false) {
  4420. if (!is_array($bean) && !($bean instanceof RedBean_OODBBean)) throw new RedBean_Exception_Security('Expected array or RedBean_OODBBean but got:'.gettype($bean));
  4421. $ids = array();
  4422. if (is_array($bean)) {
  4423. $beans = $bean;
  4424. foreach($beans as $b) {
  4425. if (!($b instanceof RedBean_OODBBean)) throw new RedBean_Exception_Security('Expected RedBean_OODBBean in array but got:'.gettype($b));
  4426. $ids[] = $b->id;
  4427. }
  4428. $bean = reset($beans);
  4429. } else $ids[] = $bean->id;
  4430. $table = $this->getTable(array($bean->getMeta('type') , $type));
  4431. if ($type == $bean->getMeta('type')) {
  4432. $type .= '2';
  4433. $cross = 1;
  4434. } else $cross = 0;
  4435. if (!$getLinks) $targetproperty = $type.'_id'; else $targetproperty = 'id';
  4436. $property = $bean->getMeta('type').'_id';
  4437. try {
  4438. $sqlFetchKeys = $this->writer->selectRecord($table, array($property => $ids), $sql, false);
  4439. $sqlResult = array();
  4440. foreach($sqlFetchKeys as $row) {
  4441. if (isset($row[$targetproperty])) {
  4442. $sqlResult[] = $row[$targetproperty];
  4443. }
  4444. }
  4445. if ($cross) {
  4446. $sqlFetchKeys2 = $this->writer->selectRecord($table, array($targetproperty => $ids), $sql, false);
  4447. foreach($sqlFetchKeys2 as $row) {
  4448. if (isset($row[$property])) {
  4449. $sqlResult[] = $row[$property];
  4450. }
  4451. }
  4452. }
  4453. return $sqlResult; //or returns rows in case of $sql != empty
  4454. } catch(RedBean_Exception_SQL $e) {
  4455. if (!$this->writer->sqlStateIn($e->getSQLState(),
  4456. array(
  4457. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  4458. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
  4459. )) throw $e;
  4460. return array();
  4461. }
  4462. }
  4463. /**
  4464. * Breaks the association between two beans. This method unassociates two beans. If the
  4465. * method succeeds the beans will no longer form an association. In the database
  4466. * this means that the association record will be removed. This method uses the
  4467. * OODB trash() method to remove the association links, thus giving FUSE models the
  4468. * opportunity to hook-in additional business logic. If the $fast parameter is
  4469. * set to boolean TRUE this method will remove the beans without their consent,
  4470. * bypassing FUSE. This can be used to improve performance.
  4471. *
  4472. * @param RedBean_OODBBean $bean1 first bean
  4473. * @param RedBean_OODBBean $bean2 second bean
  4474. * @param boolean $fast If TRUE, removes the entries by query without FUSE
  4475. */
  4476. public function unassociate($beans1, $beans2, $fast = null) {
  4477. if (!is_array($beans1)) $beans1 = array($beans1);
  4478. if (!is_array($beans2)) $beans2 = array($beans2);
  4479. foreach($beans1 as $bean1) {
  4480. foreach($beans2 as $bean2) {
  4481. $this->oodb->store($bean1);
  4482. $this->oodb->store($bean2);
  4483. $table = $this->getTable(array($bean1->getMeta('type') , $bean2->getMeta('type')));
  4484. $type = $bean1->getMeta('type');
  4485. if ($type == $bean2->getMeta('type')) {
  4486. $type .= '2';
  4487. $cross = 1;
  4488. } else $cross = 0;
  4489. $property1 = $type.'_id';
  4490. $property2 = $bean2->getMeta('type').'_id';
  4491. $value1 = (int) $bean1->id;
  4492. $value2 = (int) $bean2->id;
  4493. try {
  4494. $rows = $this->writer->selectRecord($table, array(
  4495. $property1 => array($value1), $property2 => array($value2)), null, $fast
  4496. );
  4497. if ($cross) {
  4498. $rows2 = $this->writer->selectRecord($table, array(
  4499. $property2 => array($value1), $property1 => array($value2)), null, $fast
  4500. );
  4501. if ($fast) continue;
  4502. $rows = array_merge($rows, $rows2);
  4503. }
  4504. if ($fast) continue;
  4505. $beans = $this->oodb->convertToBeans($table, $rows);
  4506. foreach($beans as $link) $this->oodb->trash($link);
  4507. } catch(RedBean_Exception_SQL $e) {
  4508. if (!$this->writer->sqlStateIn($e->getSQLState(),
  4509. array(
  4510. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  4511. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
  4512. )) throw $e;
  4513. }
  4514. }
  4515. }
  4516. }
  4517. /**
  4518. * Removes all relations for a bean. This method breaks every connection between
  4519. * a certain bean $bean and every other bean of type $type. Warning: this method
  4520. * is really fast because it uses a direct SQL query however it does not inform the
  4521. * models about this. If you want to notify FUSE models about deletion use a foreach-loop
  4522. * with unassociate() instead. (that might be slower though)
  4523. *
  4524. * @param RedBean_OODBBean $bean reference bean
  4525. * @param string $type type of beans that need to be unassociated
  4526. *
  4527. * @return void
  4528. */
  4529. public function clearRelations(RedBean_OODBBean $bean, $type) {
  4530. $this->oodb->store($bean);
  4531. $table = $this->getTable(array($bean->getMeta('type'), $type));
  4532. if ($type == $bean->getMeta('type')) {
  4533. $property2 = $type.'2_id';
  4534. $cross = 1;
  4535. }
  4536. else $cross = 0;
  4537. $property = $bean->getMeta('type').'_id';
  4538. try {
  4539. $this->writer->selectRecord($table, array($property => array($bean->id)), null, true);
  4540. if ($cross) {
  4541. $this->writer->selectRecord($table, array($property2 => array($bean->id)), null, true);
  4542. }
  4543. } catch(RedBean_Exception_SQL $e) {
  4544. if (!$this->writer->sqlStateIn($e->getSQLState(),
  4545. array(
  4546. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  4547. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
  4548. )) throw $e;
  4549. }
  4550. }
  4551. /**
  4552. * Given two beans this function returns TRUE if they are associated using a
  4553. * many-to-many association, FALSE otherwise.
  4554. *
  4555. * @throws RedBean_Exception_SQL
  4556. *
  4557. * @param RedBean_OODBBean $bean1 bean
  4558. * @param RedBean_OODBBean $bean2 bean
  4559. *
  4560. * @return bool $related whether they are associated N-M
  4561. */
  4562. public function areRelated(RedBean_OODBBean $bean1, RedBean_OODBBean $bean2) {
  4563. if (!$bean1->getID() || !$bean2->getID()) return false;
  4564. $table = $this->getTable(array($bean1->getMeta('type'), $bean2->getMeta('type')));
  4565. $type = $bean1->getMeta('type');
  4566. if ($type == $bean2->getMeta('type')) {
  4567. $type .= '2';
  4568. $cross = 1;
  4569. } else $cross = 0;
  4570. $property1 = $type.'_id';
  4571. $property2 = $bean2->getMeta('type').'_id';
  4572. $value1 = (int) $bean1->id;
  4573. $value2 = (int) $bean2->id;
  4574. try {
  4575. $rows = $this->writer->selectRecord($table, array(
  4576. $property1 => array($value1), $property2 => array($value2)), null
  4577. );
  4578. if ($cross) {
  4579. $rows2 = $this->writer->selectRecord($table, array(
  4580. $property2 => array($value1), $property1 => array($value2)), null
  4581. );
  4582. $rows = array_merge($rows, $rows2);
  4583. }
  4584. }catch(RedBean_Exception_SQL $e) {
  4585. if (!$this->writer->sqlStateIn($e->getSQLState(),
  4586. array(
  4587. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  4588. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
  4589. )) throw $e;
  4590. return false;
  4591. }
  4592. return (count($rows)>0);
  4593. }
  4594. /**
  4595. * @deprecated
  4596. * @param array $beans beans
  4597. * @param string $property property
  4598. */
  4599. public function swap($beans, $property) {
  4600. $bean1 = array_shift($beans);
  4601. $bean2 = array_shift($beans);
  4602. $tmp = $bean1->$property;
  4603. $bean1->$property = $bean2->$property;
  4604. $bean2->$property = $tmp;
  4605. $this->oodb->store($bean1);
  4606. $this->oodb->store($bean2);
  4607. }
  4608. /**
  4609. * Returns all the beans associated with $bean.
  4610. * This method will return an array containing all the beans that have
  4611. * been associated once with the associate() function and are still
  4612. * associated with the bean specified. The type parameter indicates the
  4613. * type of beans you are looking for. You can also pass some extra SQL and
  4614. * values for that SQL to filter your results after fetching the
  4615. * related beans.
  4616. *
  4617. * Dont try to make use of subqueries, a subquery using IN() seems to
  4618. * be slower than two queries!
  4619. *
  4620. * Since 3.2, you can now also pass an array of beans instead just one
  4621. * bean as the first parameter.
  4622. *
  4623. * @param RedBean_OODBBean|array $bean the bean you have
  4624. * @param string $type the type of beans you want
  4625. * @param string $sql SQL snippet for extra filtering
  4626. * @param array $val values to be inserted in SQL slots
  4627. *
  4628. * @return array $beans beans yielded by your query.
  4629. */
  4630. public function relatedSimple($bean, $type, $sql = null, $values = array()) {
  4631. $keys = $this->related($bean, $type);
  4632. if (count($keys) == 0 || !is_array($keys)) return array();
  4633. if (!$sql) return $this->oodb->batch($type, $keys);
  4634. $rows = $this->writer->selectRecord($type, array('id' => $keys), array($sql, $values), false);
  4635. return $this->oodb->convertToBeans($type, $rows);
  4636. }
  4637. /**
  4638. * Returns only single associated bean.
  4639. *
  4640. * @param RedBean_OODBBean $bean bean provided
  4641. * @param string $type type of bean you are searching for
  4642. * @param string $sql SQL for extra filtering
  4643. * @param array $values values to be inserted in SQL slots
  4644. *
  4645. *
  4646. * @return RedBean_OODBBean $bean
  4647. */
  4648. public function relatedOne(RedBean_OODBBean $bean, $type, $sql = null, $values = array()) {
  4649. $beans = $this->relatedSimple($bean, $type, $sql, $values);
  4650. if (!count($beans) || !is_array($beans)) return null;
  4651. return reset($beans);
  4652. }
  4653. /**
  4654. * The opposite of related(). Returns all the beans that are not
  4655. * associated with the bean provided.
  4656. *
  4657. * @param RedBean_OODBBean $bean bean provided
  4658. * @param string $type type of bean you are searching for
  4659. * @param string $sql SQL for extra filtering
  4660. * @param array $values values to be inserted in SQL slots
  4661. *
  4662. * @return array $beans beans
  4663. */
  4664. public function unrelated(RedBean_OODBBean $bean, $type, $sql = null, $values = array()) {
  4665. $keys = $this->related($bean, $type);
  4666. $rows = $this->writer->selectRecord($type, array('id' => $keys), array($sql, $values), false, true);
  4667. return $this->oodb->convertToBeans($type, $rows);
  4668. }
  4669. }
  4670. class RedBean_AssociationManager_ExtAssociationManager extends RedBean_AssociationManager {
  4671. /**
  4672. * @deprecated
  4673. */
  4674. public function extAssociate(RedBean_OODBBean $bean1, RedBean_OODBBean $bean2, RedBean_OODBBean $baseBean) {
  4675. $table = $this->getTable(array($bean1->getMeta('type') , $bean2->getMeta('type')));
  4676. $baseBean->setMeta('type', $table);
  4677. return $this->associateBeans($bean1, $bean2, $baseBean);
  4678. }
  4679. /**
  4680. * @deprecated
  4681. */
  4682. public function extAssociateSimple($beans1, $beans2, $extra = null) {
  4683. if (!is_array($extra)) {
  4684. $info = json_decode($extra, true);
  4685. if (!$info) $info = array('extra' => $extra);
  4686. } else {
  4687. $info = $extra;
  4688. }
  4689. $bean = $this->oodb->dispense('xtypeless');
  4690. $bean->import($info);
  4691. return $this->extAssociate($beans1, $beans2, $bean);
  4692. }
  4693. }
  4694. class RedBean_Setup {
  4695. /**
  4696. * This method checks the DSN string.
  4697. *
  4698. * @throws RedBean_Exception_NotImplemented
  4699. *
  4700. * @param string $dsn
  4701. *
  4702. * @return boolean $true
  4703. */
  4704. private static function checkDSN($dsn) {
  4705. if (!preg_match('/^(mysql|sqlite|pgsql|cubrid|oracle):/', strtolower(trim($dsn)))) trigger_error('Unsupported DSN');
  4706. return true;
  4707. }
  4708. /**
  4709. * Initializes the database and prepares a toolbox.
  4710. *
  4711. * @param string|PDO $dsn Database Connection String (or PDO instance)
  4712. * @param string $username Username for database
  4713. * @param string $password Password for database
  4714. * @param boolean $frozen Start in frozen mode?
  4715. *
  4716. * @return RedBean_ToolBox $toolbox
  4717. */
  4718. public static function kickstart($dsn, $username = null, $password = null, $frozen = false ) {
  4719. if ($dsn instanceof PDO) {
  4720. $db = new RedBean_Driver_PDO($dsn); $dsn = $db->getDatabaseType();
  4721. } else {
  4722. self::checkDSN($dsn);
  4723. if (strpos($dsn, 'oracle') === 0)
  4724. $db = new RedBean_Driver_OCI($dsn, $username, $password);
  4725. else
  4726. $db = new RedBean_Driver_PDO($dsn, $username, $password);
  4727. }
  4728. $adapter = new RedBean_Adapter_DBAdapter($db);
  4729. if (strpos($dsn, 'pgsql') === 0) $writer = new RedBean_QueryWriter_PostgreSQL($adapter);
  4730. else if (strpos($dsn, 'sqlite') === 0) $writer = new RedBean_QueryWriter_SQLiteT($adapter);
  4731. else if (strpos($dsn, 'cubrid') === 0) $writer = new RedBean_QueryWriter_CUBRID($adapter);
  4732. else if (strpos($dsn, 'oracle') === 0) $writer = new RedBean_QueryWriter_Oracle($adapter);
  4733. else $writer = new RedBean_QueryWriter_MySQL($adapter);
  4734. $redbean = new RedBean_OODB($writer);
  4735. if ($frozen) $redbean->freeze(true);
  4736. $toolbox = new RedBean_ToolBox($redbean, $adapter, $writer);
  4737. return $toolbox;
  4738. }
  4739. }
  4740. interface RedBean_IModelFormatter {
  4741. /**
  4742. * ModelHelper will call this method of the class
  4743. * you provide to discover the model
  4744. *
  4745. * @param string $model
  4746. *
  4747. * @return string $formattedModel
  4748. */
  4749. public function formatModel($model);
  4750. }
  4751. interface RedBean_Logger {
  4752. /**
  4753. * @param string $message the message to log. (optional)
  4754. */
  4755. public function log();
  4756. }
  4757. class RedBean_Logger_Default implements RedBean_Logger {
  4758. /**
  4759. * Default logger method logging to STDOUT.
  4760. * This is the default/reference implementation of a logger.
  4761. * This method will write the message value to STDOUT (screen).
  4762. *
  4763. * @param $message (optional)
  4764. */
  4765. public function log() {
  4766. if (func_num_args() > 0) {
  4767. foreach (func_get_args() as $argument) {
  4768. if (is_array($argument)) echo print_r($argument, true); else echo $argument;
  4769. echo "<br>\n";
  4770. }
  4771. }
  4772. }
  4773. }
  4774. interface RedBean_BeanHelper {
  4775. /**
  4776. * @abstract
  4777. * @return RedBean_Toolbox $toolbox toolbox
  4778. */
  4779. public function getToolbox();
  4780. /**
  4781. * Given a certain bean this method will
  4782. * return the corresponding model.
  4783. *
  4784. * @param RedBean_OODBBean $bean
  4785. */
  4786. public function getModelForBean(RedBean_OODBBean $bean);
  4787. }
  4788. class RedBean_BeanHelper_Facade implements RedBean_BeanHelper {
  4789. /**
  4790. * @see RedBean_BeanHelper::getToolbox
  4791. */
  4792. public function getToolbox() {
  4793. return RedBean_Facade::$toolbox;
  4794. }
  4795. /**
  4796. * @see RedBean_BeanHelper::getModelForBean
  4797. */
  4798. public function getModelForBean(RedBean_OODBBean $bean) {
  4799. $modelName = RedBean_ModelHelper::getModelName($bean->getMeta('type'), $bean);
  4800. if (!class_exists($modelName)) return null;
  4801. $obj = RedBean_ModelHelper::factory($modelName);
  4802. $obj->loadBean($bean);
  4803. return $obj;
  4804. }
  4805. }
  4806. class RedBean_SimpleModel {
  4807. /**
  4808. * @var RedBean_OODBBean
  4809. */
  4810. protected $bean;
  4811. /**
  4812. * Used by FUSE: the ModelHelper class to connect a bean to a model.
  4813. * This method loads a bean in the model.
  4814. *
  4815. * @param RedBean_OODBBean $bean bean
  4816. */
  4817. public function loadBean(RedBean_OODBBean $bean) {
  4818. $this->bean = $bean;
  4819. }
  4820. /**
  4821. * Magic Getter to make the bean properties available from
  4822. * the $this-scope.
  4823. *
  4824. * @param string $prop property
  4825. *
  4826. * @return mixed $propertyValue value
  4827. */
  4828. public function __get($prop) {
  4829. return $this->bean->$prop;
  4830. }
  4831. /**
  4832. * Magic Setter
  4833. *
  4834. * @param string $prop property
  4835. * @param mixed $value value
  4836. */
  4837. public function __set($prop, $value) {
  4838. $this->bean->$prop = $value;
  4839. }
  4840. /**
  4841. * Isset implementation
  4842. *
  4843. * @param string $key key
  4844. *
  4845. * @return
  4846. */
  4847. public function __isset($key) {
  4848. return (isset($this->bean->$key));
  4849. }
  4850. /**
  4851. * Box the bean using the current model.
  4852. *
  4853. * @return RedBean_SimpleModel $box a bean in a box
  4854. */
  4855. public function box() {
  4856. return $this;
  4857. }
  4858. /**
  4859. * Unbox the bean from the model.
  4860. *
  4861. * @return RedBean_OODBBean $bean bean
  4862. */
  4863. public function unbox(){
  4864. return $this->bean;
  4865. }
  4866. }
  4867. class RedBean_ModelHelper implements RedBean_Observer {
  4868. /**
  4869. * @var RedBean_IModelFormatter
  4870. */
  4871. private static $modelFormatter;
  4872. /**
  4873. * @var type
  4874. */
  4875. private static $dependencyInjector;
  4876. /**
  4877. * @var array
  4878. */
  4879. private static $modelCache = array();
  4880. /**
  4881. * @see RedBean_Observer::onEvent
  4882. */
  4883. public function onEvent($eventName, $bean) {
  4884. $bean->$eventName();
  4885. }
  4886. /**
  4887. * Given a model ID (model identifier) this method returns the
  4888. * full model name.
  4889. *
  4890. * @param string $model
  4891. * @param RedBean_OODBBean $bean
  4892. *
  4893. * @return string $fullname
  4894. */
  4895. public static function getModelName($model, $bean = null) {
  4896. if (isset(self::$modelCache[$model])) return self::$modelCache[$model];
  4897. if (self::$modelFormatter){
  4898. $modelID = self::$modelFormatter->formatModel($model, $bean);
  4899. } else {
  4900. $modelID = 'Model_'.ucfirst($model);
  4901. }
  4902. self::$modelCache[$model] = $modelID;
  4903. return self::$modelCache[$model];
  4904. }
  4905. /**
  4906. * Sets the model formatter to be used to discover a model
  4907. * for Fuse.
  4908. *
  4909. * @param string $modelFormatter
  4910. */
  4911. public static function setModelFormatter($modelFormatter) {
  4912. self::$modelFormatter = $modelFormatter;
  4913. }
  4914. /**
  4915. * Obtains a new instance of $modelClassName, using a dependency injection
  4916. * container if possible.
  4917. *
  4918. * @param string $modelClassName name of the model
  4919. */
  4920. public static function factory($modelClassName) {
  4921. if (self::$dependencyInjector) {
  4922. return self::$dependencyInjector->getInstance($modelClassName);
  4923. }
  4924. return new $modelClassName();
  4925. }
  4926. /**
  4927. * Sets the dependency injector to be used.
  4928. *
  4929. * @param RedBean_DependencyInjector $di injecto to be used
  4930. */
  4931. public static function setDependencyInjector(RedBean_DependencyInjector $di) {
  4932. self::$dependencyInjector = $di;
  4933. }
  4934. /**
  4935. * Stops the dependency injector from resolving dependencies. Removes the
  4936. * reference to the dependency injector.
  4937. */
  4938. public static function clearDependencyInjector() {
  4939. self::$dependencyInjector = null;
  4940. }
  4941. /**
  4942. * Attaches the FUSE event listeners. Now the Model Helper will listen for
  4943. * CRUD events. If a CRUD event occurs it will send a signal to the model
  4944. * that belongs to the CRUD bean and this model will take over control from
  4945. * there.
  4946. *
  4947. * @param Observable $observable
  4948. */
  4949. public function attachEventListeners(RedBean_Observable $observable) {
  4950. foreach(array('update', 'open', 'delete', 'after_delete', 'after_update', 'dispense') as $e) $observable->addEventListener($e, $this);
  4951. }
  4952. }
  4953. class RedBean_SQLHelper {
  4954. /**
  4955. * @var RedBean_Adapter
  4956. */
  4957. protected $adapter;
  4958. /**
  4959. * @var boolean
  4960. */
  4961. protected $capture = false;
  4962. /**
  4963. * @var string
  4964. */
  4965. protected $sql = '';
  4966. /**
  4967. * @var array
  4968. */
  4969. protected $params = array();
  4970. /**
  4971. * Constructor
  4972. *
  4973. * @param RedBean_DBAdapter $adapter database adapter for querying
  4974. */
  4975. public function __construct(RedBean_Adapter $adapter) {
  4976. $this->adapter = $adapter;
  4977. }
  4978. /**
  4979. * Magic method to construct SQL query
  4980. *
  4981. * @param string $funcName name of the next SQL statement/keyword
  4982. * @param array $args list of statements to be seperated by commas
  4983. *
  4984. * @return mixed $result either self or result depending on mode
  4985. */
  4986. public function __call($funcName, $args = array()) {
  4987. $funcName = str_replace('_', ' ', $funcName);
  4988. if ($this->capture) {
  4989. $this->sql .= ' '.$funcName . ' '.implode(',', $args);
  4990. return $this;
  4991. } else {
  4992. return $this->adapter->getCell('SELECT '.$funcName.'('.implode(',', $args).')');
  4993. }
  4994. }
  4995. /**
  4996. * Begins SQL query
  4997. *
  4998. * @return RedBean_SQLHelper $this chainable
  4999. */
  5000. public function begin() {
  5001. $this->capture = true;
  5002. return $this;
  5003. }
  5004. /**
  5005. * Adds a value to the parameter list
  5006. *
  5007. * @param mixed $param parameter to be added
  5008. *
  5009. * @return RedBean_SQLHelper $this chainable
  5010. */
  5011. public function put($param) {
  5012. $this->params[] = $param;
  5013. return $this;
  5014. }
  5015. /**
  5016. * Executes query and returns result
  5017. *
  5018. * @return mixed $result
  5019. */
  5020. public function get($what = '') {
  5021. $what = 'get'.ucfirst($what);
  5022. $rs = $this->adapter->$what($this->sql, $this->params);
  5023. $this->clear();
  5024. return $rs;
  5025. }
  5026. /**
  5027. * Clears the parameter list as well as the SQL query string.
  5028. *
  5029. * @return RedBean_SQLHelper $this chainable
  5030. */
  5031. public function clear() {
  5032. $this->sql = '';
  5033. $this->params = array();
  5034. $this->capture = false; //turn off capture mode (issue #142)
  5035. return $this;
  5036. }
  5037. /**
  5038. * To explicitly add a piece of SQL.
  5039. *
  5040. * @param string $sql sql
  5041. *
  5042. * @return RedBean_SQLHelper
  5043. */
  5044. public function addSQL($sql) {
  5045. if ($this->capture) {
  5046. $this->sql .= ' '.$sql.' ';
  5047. return $this;
  5048. }
  5049. }
  5050. /**
  5051. * Returns query parts.
  5052. *
  5053. * @return array $queryParts query parts.
  5054. */
  5055. public function getQuery() {
  5056. $list = array($this->sql, $this->params);
  5057. $this->clear();
  5058. return $list;
  5059. }
  5060. /**
  5061. * Nests another query builder query in the current query.
  5062. *
  5063. * @param RedBean_SQLHelper $sqlHelper
  5064. */
  5065. public function nest(RedBean_SQLHelper $sqlHelper) {
  5066. list($sql, $params) = $sqlHelper->getQuery();
  5067. $this->sql .= $sql;
  5068. $this->params += $params;
  5069. return $this;
  5070. }
  5071. /**
  5072. * Writes a '(' to the sql query.
  5073. */
  5074. public function open() {
  5075. if ($this->capture) {
  5076. $this->sql .= ' ( ';
  5077. return $this;
  5078. }
  5079. }
  5080. /**
  5081. * Writes a ')' to the sql query.
  5082. */
  5083. public function close() {
  5084. if ($this->capture) {
  5085. $this->sql .= ' ) ';
  5086. return $this;
  5087. }
  5088. }
  5089. /**
  5090. * Generates question mark slots for an array of values.
  5091. *
  5092. * @param array $array Array with values to generate slots for
  5093. *
  5094. * @return string $slots
  5095. */
  5096. public function genSlots($array) {
  5097. if (is_array($array) && count($array)>0) {
  5098. $filler = array_fill(0, count($array), '?');
  5099. return implode(',', $filler);
  5100. } else {
  5101. return '';
  5102. }
  5103. }
  5104. /**
  5105. * Returns a new SQL Helper with the same adapter as the current one.
  5106. *
  5107. * @return RedBean_SQLHelper
  5108. */
  5109. public function getNew() {
  5110. return new self($this->adapter);
  5111. }
  5112. }
  5113. class RedBean_TagManager {
  5114. /**
  5115. * @var RedBean_Toolbox
  5116. */
  5117. protected $toolbox;
  5118. /**
  5119. * @var RedBean_AssociationManager
  5120. */
  5121. protected $associationManager;
  5122. /**
  5123. * @var RedBean_OODBBean
  5124. */
  5125. protected $redbean;
  5126. /**
  5127. * Constructor
  5128. *
  5129. * @param RedBean_Toolbox $toolbox
  5130. */
  5131. public function __construct(RedBean_Toolbox $toolbox) {
  5132. $this->toolbox = $toolbox;
  5133. $this->redbean = $toolbox->getRedBean();
  5134. $this->associationManager = $this->redbean->getAssociationManager();
  5135. }
  5136. /**
  5137. * Finds a tag bean by it's title.
  5138. *
  5139. * @param string $title title
  5140. *
  5141. * @return RedBean_OODBBean $bean | null
  5142. */
  5143. public function findTagByTitle($title) {
  5144. $beans = $this->redbean->find('tag', array('title' => array($title)));
  5145. if ($beans) {
  5146. $bean = reset($beans);
  5147. return $bean;
  5148. }
  5149. return null;
  5150. }
  5151. /**
  5152. * Tests whether a bean has been associated with one ore more
  5153. * of the listed tags. If the third parameter is TRUE this method
  5154. * will return TRUE only if all tags that have been specified are indeed
  5155. * associated with the given bean, otherwise FALSE.
  5156. * If the third parameter is FALSE this
  5157. * method will return TRUE if one of the tags matches, FALSE if none
  5158. * match.
  5159. *
  5160. * @param RedBean_OODBBean $bean bean to check for tags
  5161. * @param array $tags list of tags
  5162. * @param boolean $all whether they must all match or just some
  5163. *
  5164. * @return boolean $didMatch whether the bean has been assoc. with the tags
  5165. */
  5166. public function hasTag($bean, $tags, $all = false) {
  5167. $foundtags = $this->tag($bean);
  5168. if (is_string($foundtags)) $foundtags = explode(',', $tags);
  5169. $same = array_intersect($tags, $foundtags);
  5170. if ($all) return (implode(',', $same) === implode(',', $tags));
  5171. return (bool) (count($same)>0);
  5172. }
  5173. /**
  5174. * Removes all sepcified tags from the bean. The tags specified in
  5175. * the second parameter will no longer be associated with the bean.
  5176. *
  5177. * @param RedBean_OODBBean $bean tagged bean
  5178. * @param array $tagList list of tags (names)
  5179. *
  5180. * @return void
  5181. */
  5182. public function untag($bean, $tagList) {
  5183. if ($tagList !== false && !is_array($tagList)) $tags = explode(",", (string)$tagList); else $tags = $tagList;
  5184. foreach($tags as $tag) if ($t = $this->findTagByTitle($tag)) $this->associationManager->unassociate($bean, $t);
  5185. }
  5186. /**
  5187. * Tags a bean or returns tags associated with a bean.
  5188. * If $tagList is null or omitted this method will return a
  5189. * comma separated list of tags associated with the bean provided.
  5190. * If $tagList is a comma separated list (string) of tags all tags will
  5191. * be associated with the bean.
  5192. * You may also pass an array instead of a string.
  5193. *
  5194. * @param RedBean_OODBBean $bean bean
  5195. * @param mixed $tagList tags
  5196. *
  5197. * @return string $commaSepListTags
  5198. */
  5199. public function tag(RedBean_OODBBean $bean, $tagList = null) {
  5200. if (is_null($tagList)) {
  5201. $tags = array();
  5202. $keys = $this->associationManager->related($bean, 'tag');
  5203. if ($keys) {
  5204. $tags = $this->redbean->batch('tag', $keys);
  5205. }
  5206. $foundTags = array();
  5207. foreach($tags as $tag) {
  5208. $foundTags[] = $tag->title;
  5209. }
  5210. return $foundTags;
  5211. }
  5212. $this->associationManager->clearRelations($bean, 'tag');
  5213. $this->addTags($bean, $tagList);
  5214. }
  5215. /**
  5216. * Adds tags to a bean.
  5217. * If $tagList is a comma separated list of tags all tags will
  5218. * be associated with the bean.
  5219. * You may also pass an array instead of a string.
  5220. *
  5221. * @param RedBean_OODBBean $bean bean
  5222. * @param array $tagList list of tags to add to bean
  5223. *
  5224. * @return void
  5225. */
  5226. public function addTags(RedBean_OODBBean $bean, $tagList) {
  5227. if ($tagList !== false && !is_array($tagList)) $tags = explode(",", (string)$tagList); else $tags = $tagList;
  5228. if ($tagList === false) return;
  5229. foreach($tags as $tag) {
  5230. if (!$t = $this->findTagByTitle($tag)) {
  5231. $t = $this->redbean->dispense('tag');
  5232. $t->title = $tag;
  5233. $this->redbean->store($t);
  5234. }
  5235. $this->associationManager->associate($bean, $t);
  5236. }
  5237. }
  5238. /**
  5239. * Returns all beans that have been tagged with one of the tags given.
  5240. *
  5241. * @param $beanType type of bean you are looking for
  5242. * @param $tagList list of tags to match
  5243. *
  5244. * @return array
  5245. */
  5246. public function tagged($beanType, $tagList) {
  5247. if ($tagList !== false && !is_array($tagList)) $tags = explode(",", (string) $tagList); else $tags = $tagList;
  5248. $collection = array();
  5249. $tags = $this->redbean->find('tag', array('title' => $tags));
  5250. if (is_array($tags) && count($tags)>0) {
  5251. $collectionKeys = $this->associationManager->related($tags, $beanType);
  5252. if ($collectionKeys) {
  5253. $collection = $this->redbean->batch($beanType, $collectionKeys);
  5254. }
  5255. }
  5256. return $collection;
  5257. }
  5258. /**
  5259. * Returns all beans that have been tagged with ALL of the tags given.
  5260. *
  5261. * @param $beanType type of bean you are looking for
  5262. * @param $tagList list of tags to match
  5263. *
  5264. * @return array
  5265. */
  5266. public function taggedAll($beanType, $tagList) {
  5267. if ($tagList !== false && !is_array($tagList)) $tags = explode(",", (string)$tagList); else $tags = $tagList;
  5268. $beans = array();
  5269. foreach($tags as $tag) {
  5270. $beans = $this->tagged($beanType, $tag);
  5271. if (isset($oldBeans)) $beans = array_intersect_assoc($beans, $oldBeans);
  5272. $oldBeans = $beans;
  5273. }
  5274. return $beans;
  5275. }
  5276. }
  5277. class RedBean_LabelMaker {
  5278. /**
  5279. * @var RedBean_Toolbox
  5280. */
  5281. protected $toolbox;
  5282. /**
  5283. * Constructor.
  5284. *
  5285. * @param RedBean_ToolBox $toolbox
  5286. */
  5287. public function __construct(RedBean_ToolBox $toolbox) {
  5288. $this->toolbox = $toolbox;
  5289. }
  5290. /**
  5291. * A label is a bean with only an id, type and name property.
  5292. * This function will dispense beans for all entries in the array. The
  5293. * values of the array will be assigned to the name property of each
  5294. * individual bean.
  5295. *
  5296. * @param string $type type of beans you would like to have
  5297. * @param array $labels list of labels, names for each bean
  5298. *
  5299. * @return array $bean a list of beans with type and name property
  5300. */
  5301. public function dispenseLabels($type, $labels) {
  5302. $labelBeans = array();
  5303. foreach($labels as $label) {
  5304. $labelBean = $this->toolbox->getRedBean()->dispense($type);
  5305. $labelBean->name = $label;
  5306. $labelBeans[] = $labelBean;
  5307. }
  5308. return $labelBeans;
  5309. }
  5310. /**
  5311. * Gathers labels from beans. This function loops through the beans,
  5312. * collects the values of the name properties of each individual bean
  5313. * and stores the names in a new array. The array then gets sorted using the
  5314. * default sort function of PHP (sort).
  5315. *
  5316. * @param array $beans list of beans to loop
  5317. *
  5318. * @return array $array list of names of beans
  5319. */
  5320. public function gatherLabels($beans) {
  5321. $labels = array();
  5322. foreach($beans as $bean) $labels[] = $bean->name;
  5323. sort($labels);
  5324. return $labels;
  5325. }
  5326. }
  5327. class RedBean_Finder {
  5328. /**
  5329. * @var RedBean_ToolBox
  5330. */
  5331. protected $toolbox;
  5332. /**
  5333. * @var RedBean_OODB
  5334. */
  5335. protected $redbean;
  5336. /**
  5337. * Constructor.
  5338. * The Finder requires a toolbox.
  5339. *
  5340. * @param RedBean_ToolBox $toolbox
  5341. */
  5342. public function __construct(RedBean_ToolBox $toolbox) {
  5343. $this->toolbox = $toolbox;
  5344. $this->redbean = $toolbox->getRedBean();
  5345. }
  5346. /**
  5347. * Finds a bean using a type and a where clause (SQL).
  5348. * As with most Query tools in RedBean you can provide values to
  5349. * be inserted in the SQL statement by populating the value
  5350. * array parameter; you can either use the question mark notation
  5351. * or the slot-notation (:keyname).
  5352. *
  5353. * @param string $type type the type of bean you are looking for
  5354. * @param string $sql sql SQL query to find the desired bean, starting right after WHERE clause
  5355. * @param array $values values array of values to be bound to parameters in query
  5356. *
  5357. * @return array $beans beans
  5358. */
  5359. public function find($type, $sql = null, $values = array()) {
  5360. if ($sql instanceof RedBean_SQLHelper) list($sql, $values) = $sql->getQuery();
  5361. if (!is_array($values)) throw new InvalidArgumentException('Expected array, ' . gettype($values) . ' given.');
  5362. return $this->redbean->find($type, array(), array($sql, $values));
  5363. }
  5364. /**
  5365. * @see RedBean_Finder::find
  5366. * The findAll() method differs from the find() method in that it does
  5367. * not assume a WHERE-clause, so this is valid:
  5368. *
  5369. * R::findAll('person', ' ORDER BY name DESC ');
  5370. *
  5371. * Your SQL does not have to start with a valid WHERE-clause condition.
  5372. *
  5373. * @param string $type type the type of bean you are looking for
  5374. * @param string $sql sql SQL query to find the desired bean, starting right after WHERE clause
  5375. * @param array $values values array of values to be bound to parameters in query
  5376. *
  5377. * @return array $beans beans
  5378. */
  5379. public function findAll($type, $sql = null, $values = array()) {
  5380. if ($sql instanceof RedBean_SQLHelper) list($sql, $values) = $sql->getQuery();
  5381. if (!is_array($values)) throw new InvalidArgumentException('Expected array, '.gettype($values).' given.');
  5382. return $this->redbean->find($type, array(), array($sql, $values), true);
  5383. }
  5384. /**
  5385. * @see RedBean_Finder::find
  5386. * The variation also exports the beans (i.e. it returns arrays).
  5387. *
  5388. * @param string $type type the type of bean you are looking for
  5389. * @param string $sql sql SQL query to find the desired bean, starting right after WHERE clause
  5390. * @param array $values values array of values to be bound to parameters in query
  5391. *
  5392. * @return array $arrays arrays
  5393. */
  5394. public function findAndExport($type, $sql = null, $values = array()) {
  5395. $items = $this->find($type, $sql, $values);
  5396. $arr = array();
  5397. foreach($items as $key => $item) $arr[$key] = $item->export();
  5398. return $arr;
  5399. }
  5400. /**
  5401. * @see RedBean_Finder::find
  5402. * This variation returns the first bean only.
  5403. *
  5404. * @param string $type type
  5405. * @param string $sql sql
  5406. * @param array $values values
  5407. *
  5408. * @return RedBean_OODBBean $bean
  5409. */
  5410. public function findOne($type, $sql = null, $values = array()) {
  5411. $items = $this->find($type, $sql, $values);
  5412. $found = reset($items);
  5413. if (!$found) return null;
  5414. return $found;
  5415. }
  5416. /**
  5417. * @see RedBean_Finder::find
  5418. * This variation returns the last bean only.
  5419. *
  5420. * @param string $type type
  5421. * @param string $sql sql
  5422. * @param array $values values
  5423. *
  5424. * @return RedBean_OODBBean $bean
  5425. */
  5426. public function findLast($type, $sql = null, $values = array()) {
  5427. $items = $this->find($type, $sql, $values);
  5428. $found = end($items);
  5429. if (!$found) return null;
  5430. return $found;
  5431. }
  5432. /**
  5433. * @see RedBean_Finder::find
  5434. * Convience method. Tries to find beans of a certain type,
  5435. * if no beans are found, it dispenses a bean of that type.
  5436. *
  5437. * @param string $type type
  5438. * @param string $sql sql
  5439. * @param array $values values
  5440. *
  5441. * @return array $beans Contains RedBean_OODBBean instances
  5442. */
  5443. public function findOrDispense($type, $sql = null, $values = array()) {
  5444. $foundBeans = $this->find($type, $sql, $values);
  5445. if (count($foundBeans) == 0) return array($this->redbean->dispense($type)); else return $foundBeans;
  5446. }
  5447. }
  5448. class RedBean_Facade {
  5449. /**
  5450. * @var array
  5451. */
  5452. public static $toolboxes = array();
  5453. /**
  5454. * @var RedBean_ToolBox
  5455. */
  5456. public static $toolbox;
  5457. /**
  5458. * @var RedBean_OODB
  5459. */
  5460. public static $redbean;
  5461. /**
  5462. * @var RedBean_QueryWriter
  5463. */
  5464. public static $writer;
  5465. /**
  5466. * @var RedBean_DBAdapter
  5467. */
  5468. public static $adapter;
  5469. /**
  5470. * @var RedBean_AssociationManager
  5471. */
  5472. public static $associationManager;
  5473. /**
  5474. * @var RedBean_ExtAssociationManager
  5475. */
  5476. public static $extAssocManager;
  5477. /**
  5478. * @var RedBean_TagManager
  5479. */
  5480. public static $tagManager;
  5481. /**
  5482. * @var RedBean_DuplicationManager
  5483. */
  5484. public static $duplicationManager;
  5485. /**
  5486. * @var RedBean_LabelMaker
  5487. */
  5488. public static $labelMaker;
  5489. /**
  5490. * @var RedBean_Finder
  5491. */
  5492. public static $finder;
  5493. /**
  5494. * @var string
  5495. */
  5496. public static $currentDB = '';
  5497. /**
  5498. * @var RedBean_SQLHelper
  5499. */
  5500. public static $f;
  5501. /**
  5502. * @var boolean
  5503. */
  5504. private static $strictType = true;
  5505. /**
  5506. * Get version
  5507. * @return string
  5508. */
  5509. public static function getVersion() {
  5510. return '3.4.2';
  5511. }
  5512. /**
  5513. * Kickstarts redbean for you. This method should be called before you start using
  5514. * RedBean. The Setup() method can be called without any arguments, in this case it will
  5515. * try to create a SQLite database in /tmp called red.db (this only works on UNIX-like systems).
  5516. *
  5517. * @param string $dsn Database connection string
  5518. * @param string $username Username for database
  5519. * @param string $password Password for database
  5520. *
  5521. * @return void
  5522. */
  5523. public static function setup($dsn = null, $username = null, $password = null) {
  5524. if (function_exists('sys_get_temp_dir')) $tmp = sys_get_temp_dir(); else $tmp = 'tmp';
  5525. if (is_null($dsn)) $dsn = 'sqlite:/'.$tmp.'/red.db';
  5526. self::addDatabase('default', $dsn, $username, $password);
  5527. self::selectDatabase('default');
  5528. return self::$toolbox;
  5529. }
  5530. /**
  5531. * Starts a transaction within a closure (or other valid callback).
  5532. * If an Exception is thrown inside, the operation is automatically rolled back.
  5533. * If no Exception happens, it commits automatically.
  5534. * It also supports (simulated) nested transactions (that is useful when
  5535. * you have many methods that needs transactions but are unaware of
  5536. * each other).
  5537. * ex:
  5538. * $from = 1;
  5539. * $to = 2;
  5540. * $ammount = 300;
  5541. *
  5542. * R::transaction(function() use($from, $to, $ammount)
  5543. * {
  5544. * $accountFrom = R::load('account', $from);
  5545. * $accountTo = R::load('account', $to);
  5546. *
  5547. * $accountFrom->money -= $ammount;
  5548. * $accountTo->money += $ammount;
  5549. *
  5550. * R::store($accountFrom);
  5551. * R::store($accountTo);
  5552. * });
  5553. *
  5554. * @param callable $callback Closure (or other callable) with the transaction logic
  5555. *
  5556. * @return void
  5557. */
  5558. public static function transaction($callback) {
  5559. if (!is_callable($callback)) throw new InvalidArgumentException('R::transaction needs a valid callback.');
  5560. static $depth = 0;
  5561. try {
  5562. if ($depth == 0) self::begin();
  5563. $depth++;
  5564. call_user_func($callback); //maintain 5.2 compatibility
  5565. $depth--;
  5566. if ($depth == 0) self::commit();
  5567. } catch(Exception $e) {
  5568. $depth--;
  5569. if ($depth == 0) self::rollback();
  5570. throw $e;
  5571. }
  5572. }
  5573. /**
  5574. * Adds a database to the facade, afterwards you can select the database using
  5575. * selectDatabase($key).
  5576. *
  5577. * @param string $key ID for the database
  5578. * @param string $dsn DSN for the database
  5579. * @param string $user User for connection
  5580. * @param null|string $pass Password for connection
  5581. * @param bool $frozen Whether this database is frozen or not
  5582. *
  5583. * @return void
  5584. */
  5585. public static function addDatabase($key, $dsn, $user = null, $pass = null, $frozen = false) {
  5586. self::$toolboxes[$key] = RedBean_Setup::kickstart($dsn, $user, $pass, $frozen);
  5587. }
  5588. /**
  5589. * Selects a different database for the Facade to work with.
  5590. *
  5591. * @param string $key Key of the database to select
  5592. * @return int 1
  5593. */
  5594. public static function selectDatabase($key) {
  5595. if (self::$currentDB === $key) return false;
  5596. self::configureFacadeWithToolbox(self::$toolboxes[$key]);
  5597. self::$currentDB = $key;
  5598. return true;
  5599. }
  5600. /**
  5601. * Toggles DEBUG mode.
  5602. * In Debug mode all SQL that happens under the hood will
  5603. * be printed to the screen or logged by provided logger.
  5604. *
  5605. * @param boolean $tf
  5606. * @param RedBean_Logger $logger
  5607. */
  5608. public static function debug($tf = true, $logger = NULL) {
  5609. if (!$logger) $logger = new RedBean_Logger_Default;
  5610. if (!isset(self::$adapter)) throw new RedBean_Exception_Security('Use R::setup() first.');
  5611. self::$adapter->getDatabase()->setDebugMode($tf, $logger);
  5612. }
  5613. /**
  5614. * Stores a RedBean OODB Bean and returns the ID.
  5615. *
  5616. * @param RedBean_OODBBean|RedBean_SimpleModel $bean bean
  5617. *
  5618. * @return integer $id id
  5619. */
  5620. public static function store($bean) {
  5621. return self::$redbean->store($bean);
  5622. }
  5623. /**
  5624. * Toggles fluid or frozen mode. In fluid mode the database
  5625. * structure is adjusted to accomodate your objects. In frozen mode
  5626. * this is not the case.
  5627. *
  5628. * You can also pass an array containing a selection of frozen types.
  5629. * Let's call this chilly mode, it's just like fluid mode except that
  5630. * certain types (i.e. tables) aren't touched.
  5631. *
  5632. * @param boolean|array $trueFalse
  5633. */
  5634. public static function freeze($tf = true) {
  5635. self::$redbean->freeze($tf);
  5636. }
  5637. /**
  5638. * Loads multiple types of beans with the same ID.
  5639. * This might look like a strange method, however it can be useful
  5640. * for loading a one-to-one relation.
  5641. *
  5642. * Usage:
  5643. * list($author, $bio) = R::load('author, bio', $id);
  5644. *
  5645. * @param string|array $types
  5646. * @param mixed $id
  5647. *
  5648. * @return RedBean_OODBBean $bean
  5649. */
  5650. public static function loadMulti($types, $id) {
  5651. if (is_string($types) && strpos($types, ',') !== false) $types = explode(',', $types);
  5652. if (is_array($types)) {
  5653. $list = array();
  5654. foreach($types as $typeItem) {
  5655. $list[] = self::$redbean->load($typeItem, $id);
  5656. }
  5657. return $list;
  5658. }
  5659. return array();
  5660. }
  5661. /**
  5662. * Loads the bean with the given type and id and returns it.
  5663. *
  5664. * Usage:
  5665. * $book = R::load('book', $id); -- loads a book bean
  5666. *
  5667. * Can also load one-to-one related beans:
  5668. *
  5669. * @param string $type type
  5670. * @param integer $id id of the bean you want to load
  5671. *
  5672. * @return RedBean_OODBBean $bean
  5673. */
  5674. public static function load($type, $id) {
  5675. return self::$redbean->load($type, $id);
  5676. }
  5677. /**
  5678. * Deletes the specified bean.
  5679. *
  5680. * @param RedBean_OODBBean|RedBean_SimpleModel $bean bean to be deleted
  5681. *
  5682. * @return mixed
  5683. */
  5684. public static function trash($bean) {
  5685. return self::$redbean->trash($bean);
  5686. }
  5687. /**
  5688. * Dispenses a new RedBean OODB Bean for use with
  5689. * the rest of the methods.
  5690. *
  5691. * @todo extract from facade
  5692. *
  5693. *
  5694. * @param string $type type
  5695. * @param integer $number number of beans to dispense
  5696. *
  5697. * @return array $oneOrMoreBeans
  5698. */
  5699. public static function dispense($type, $num = 1) {
  5700. if (!preg_match('/^[a-z0-9]+$/', $type) && self::$strictType) throw new RedBean_Exception_Security('Invalid type: '.$type);
  5701. return self::$redbean->dispense($type, $num);
  5702. }
  5703. /**
  5704. * Toggles strict bean type names.
  5705. * If set to true (default) this will forbid the use of underscores and
  5706. * uppercase characters in bean type strings (R::dispense).
  5707. *
  5708. * @param boolean $trueFalse
  5709. */
  5710. public static function setStrictTyping($trueFalse) {
  5711. self::$strictType = (boolean) $trueFalse;
  5712. }
  5713. /**
  5714. * Convience method. Tries to find beans of a certain type,
  5715. * if no beans are found, it dispenses a bean of that type.
  5716. *
  5717. * @param string $type type of bean you are looking for
  5718. * @param string $sql SQL code for finding the bean
  5719. * @param array $values parameters to bind to SQL
  5720. *
  5721. * @return array $beans Contains RedBean_OODBBean instances
  5722. */
  5723. public static function findOrDispense($type, $sql = null, $values = array()) {
  5724. return self::$finder->findOrDispense($type, $sql, $values);
  5725. }
  5726. /**
  5727. * Associates two Beans. This method will associate two beans with eachother.
  5728. * You can then get one of the beans by using the related() function and
  5729. * providing the other bean. You can also provide a base bean in the extra
  5730. * parameter. This base bean allows you to add extra information to the association
  5731. * record. Note that this is for advanced use only and the information will not
  5732. * be added to one of the beans, just to the association record.
  5733. * It's also possible to provide an array or JSON string as base bean. If you
  5734. * pass a scalar this function will interpret the base bean as having one
  5735. * property called 'extra' with the value of the scalar.
  5736. *
  5737. * @todo extract from facade
  5738. *
  5739. * @param RedBean_OODBBean $bean1 bean that will be part of the association
  5740. * @param RedBean_OODBBean $bean2 bean that will be part of the association
  5741. * @param mixed $extra bean, scalar, array or JSON providing extra data.
  5742. *
  5743. * @return mixed
  5744. */
  5745. public static function associate($beans1, $beans2, $extra = null) {
  5746. if (!$extra) {
  5747. return self::$associationManager->associate($beans1, $beans2);
  5748. } else {
  5749. return self::$extAssocManager->extAssociateSimple($beans1, $beans2, $extra);
  5750. }
  5751. }
  5752. /**
  5753. * Breaks the association between two beans.
  5754. * This functions breaks the association between a pair of beans. After
  5755. * calling this functions the beans will no longer be associated with
  5756. * eachother. Calling related() with either one of the beans will no longer
  5757. * return the other bean.
  5758. *
  5759. * @param RedBean_OODBBean $bean1 bean
  5760. * @param RedBean_OODBBean $bean2 bean
  5761. *
  5762. * @return mixed
  5763. */
  5764. public static function unassociate($beans1, $beans2, $fast = false) {
  5765. return self::$associationManager->unassociate($beans1, $beans2, $fast);
  5766. }
  5767. /**
  5768. * Returns all the beans associated with $bean.
  5769. * This method will return an array containing all the beans that have
  5770. * been associated once with the associate() function and are still
  5771. * associated with the bean specified. The type parameter indicates the
  5772. * type of beans you are looking for. You can also pass some extra SQL and
  5773. * values for that SQL to filter your results after fetching the
  5774. * related beans.
  5775. *
  5776. * Dont try to make use of subqueries, a subquery using IN() seems to
  5777. * be slower than two queries!
  5778. *
  5779. * Since 3.2, you can now also pass an array of beans instead just one
  5780. * bean as the first parameter.
  5781. *
  5782. * @param RedBean_OODBBean|array $bean the bean you have
  5783. * @param string $type the type of beans you want
  5784. * @param string $sql SQL snippet for extra filtering
  5785. * @param array $val values to be inserted in SQL slots
  5786. *
  5787. * @return array $beans beans yielded by your query.
  5788. */
  5789. public static function related($bean, $type, $sql = null, $values = array()) {
  5790. return self::$associationManager->relatedSimple($bean, $type, $sql, $values);
  5791. }
  5792. /**
  5793. * Returns only single associated bean.
  5794. *
  5795. * @param RedBean_OODBBean $bean bean provided
  5796. * @param string $type type of bean you are searching for
  5797. * @param string $sql SQL for extra filtering
  5798. * @param array $values values to be inserted in SQL slots
  5799. *
  5800. *
  5801. * @return RedBean_OODBBean $bean
  5802. */
  5803. public static function relatedOne(RedBean_OODBBean $bean, $type, $sql = null, $values = array()) {
  5804. return self::$associationManager->relatedOne($bean, $type, $sql, $values);
  5805. }
  5806. /**
  5807. * Checks whether a pair of beans is related N-M. This function does not
  5808. * check whether the beans are related in N:1 way.
  5809. *
  5810. * @param RedBean_OODBBean $bean1 first bean
  5811. * @param RedBean_OODBBean $bean2 second bean
  5812. *
  5813. * @return bool $yesNo whether they are related
  5814. */
  5815. public static function areRelated(RedBean_OODBBean $bean1, RedBean_OODBBean $bean2) {
  5816. return self::$associationManager->areRelated($bean1, $bean2);
  5817. }
  5818. /**
  5819. * The opposite of related(). Returns all the beans that are not
  5820. * associated with the bean provided.
  5821. *
  5822. * @param RedBean_OODBBean $bean bean provided
  5823. * @param string $type type of bean you are searching for
  5824. * @param string $sql SQL for extra filtering
  5825. * @param array $values values to be inserted in SQL slots
  5826. *
  5827. * @return array $beans beans
  5828. */
  5829. public static function unrelated(RedBean_OODBBean $bean, $type, $sql = null, $values = array()) {
  5830. return self::$associationManager->unrelated($bean, $type, $sql, $values);
  5831. }
  5832. /**
  5833. * Clears all associated beans.
  5834. * Breaks all many-to-many associations of a bean and a specified type.
  5835. *
  5836. * @param RedBean_OODBBean $bean bean you wish to clear many-to-many relations for
  5837. * @param string $type type of bean you wish to break associatons with
  5838. *
  5839. * @return void
  5840. */
  5841. public static function clearRelations(RedBean_OODBBean $bean, $type) {
  5842. self::$associationManager->clearRelations($bean, $type);
  5843. }
  5844. /**
  5845. * Finds a bean using a type and a where clause (SQL).
  5846. * As with most Query tools in RedBean you can provide values to
  5847. * be inserted in the SQL statement by populating the value
  5848. * array parameter; you can either use the question mark notation
  5849. * or the slot-notation (:keyname).
  5850. *
  5851. * @param string $type type the type of bean you are looking for
  5852. * @param string $sql sql SQL query to find the desired bean, starting right after WHERE clause
  5853. * @param array $values values array of values to be bound to parameters in query
  5854. *
  5855. * @return array $beans beans
  5856. */
  5857. public static function find($type, $sql = null, $values = array()) {
  5858. return self::$finder->find($type, $sql, $values);
  5859. }
  5860. /**
  5861. * @see RedBean_Facade::find
  5862. * The findAll() method differs from the find() method in that it does
  5863. * not assume a WHERE-clause, so this is valid:
  5864. *
  5865. * R::findAll('person',' ORDER BY name DESC ');
  5866. *
  5867. * Your SQL does not have to start with a valid WHERE-clause condition.
  5868. *
  5869. * @param string $type type the type of bean you are looking for
  5870. * @param string $sql sql SQL query to find the desired bean, starting right after WHERE clause
  5871. * @param array $values values array of values to be bound to parameters in query
  5872. *
  5873. * @return array $beans beans
  5874. */
  5875. public static function findAll($type, $sql = null, $values = array()) {
  5876. return self::$finder->findAll($type, $sql, $values);
  5877. }
  5878. /**
  5879. * @see RedBean_Facade::find
  5880. * The variation also exports the beans (i.e. it returns arrays).
  5881. *
  5882. * @param string $type type the type of bean you are looking for
  5883. * @param string $sql sql SQL query to find the desired bean, starting right after WHERE clause
  5884. * @param array $values values array of values to be bound to parameters in query
  5885. *
  5886. * @return array $arrays arrays
  5887. */
  5888. public static function findAndExport($type, $sql = null, $values = array()) {
  5889. return self::$finder->findAndExport($type, $sql, $values);
  5890. }
  5891. /**
  5892. * @see RedBean_Facade::find
  5893. * This variation returns the first bean only.
  5894. *
  5895. * @param string $type type the type of bean you are looking for
  5896. * @param string $sql sql SQL query to find the desired bean, starting right after WHERE clause
  5897. * @param array $values values array of values to be bound to parameters in query
  5898. *
  5899. * @return RedBean_OODBBean $bean
  5900. */
  5901. public static function findOne($type, $sql = null, $values = array()) {
  5902. return self::$finder->findOne($type, $sql, $values);
  5903. }
  5904. /**
  5905. * @see RedBean_Facade::find
  5906. * This variation returns the last bean only.
  5907. *
  5908. * @param string $type type the type of bean you are looking for
  5909. * @param string $sql sql SQL query to find the desired bean, starting right after WHERE clause
  5910. * @param array $values values array of values to be bound to parameters in query
  5911. *
  5912. * @return RedBean_OODBBean $bean
  5913. */
  5914. public static function findLast($type, $sql = null, $values = array()) {
  5915. return self::$finder->findLast($type, $sql, $values);
  5916. }
  5917. /**
  5918. * Returns an array of beans. Pass a type and a series of ids and
  5919. * this method will bring you the correspondig beans.
  5920. *
  5921. * important note: Because this method loads beans using the load()
  5922. * function (but faster) it will return empty beans with ID 0 for
  5923. * every bean that could not be located. The resulting beans will have the
  5924. * passed IDs as their keys.
  5925. *
  5926. * @param string $type type of beans
  5927. * @param array $ids ids to load
  5928. *
  5929. * @return array $beans resulting beans (may include empty ones)
  5930. */
  5931. public static function batch($type, $ids) {
  5932. return self::$redbean->batch($type, $ids);
  5933. }
  5934. /**
  5935. * Convenience function to execute Queries directly.
  5936. * Executes SQL.
  5937. *
  5938. * @param string $sql sql SQL query to execute
  5939. * @param array $values values a list of values to be bound to query parameters
  5940. *
  5941. * @return integer $affected number of affected rows
  5942. */
  5943. public static function exec($sql, $values = array()) {
  5944. return self::query('exec', $sql, $values);
  5945. }
  5946. /**
  5947. * Convenience function to execute Queries directly.
  5948. * Executes SQL.
  5949. *
  5950. * @param string $sql sql SQL query to execute
  5951. * @param array $values values a list of values to be bound to query parameters
  5952. *
  5953. * @return array $results
  5954. */
  5955. public static function getAll($sql, $values = array()) {
  5956. return self::query('get', $sql, $values);
  5957. }
  5958. /**
  5959. * Convenience function to execute Queries directly.
  5960. * Executes SQL.
  5961. *
  5962. * @param string $sql sql SQL query to execute
  5963. * @param array $values values a list of values to be bound to query parameters
  5964. *
  5965. * @return string $result scalar
  5966. */
  5967. public static function getCell($sql, $values = array()) {
  5968. return self::query('getCell', $sql, $values);
  5969. }
  5970. /**
  5971. * Convenience function to execute Queries directly.
  5972. * Executes SQL.
  5973. *
  5974. * @param string $sql sql SQL query to execute
  5975. * @param array $values values a list of values to be bound to query parameters
  5976. *
  5977. * @return array $results
  5978. */
  5979. public static function getRow($sql, $values = array()) {
  5980. return self::query('getRow', $sql, $values);
  5981. }
  5982. /**
  5983. * Convenience function to execute Queries directly.
  5984. * Executes SQL.
  5985. *
  5986. * @param string $sql sql SQL query to execute
  5987. * @param array $values values a list of values to be bound to query parameters
  5988. *
  5989. * @return array $results
  5990. */
  5991. public static function getCol($sql, $values = array()) {
  5992. return self::query('getCol', $sql, $values);
  5993. }
  5994. /**
  5995. * Internal Query function, executes the desired query. Used by
  5996. * all facade query functions. This keeps things DRY.
  5997. *
  5998. * @throws RedBean_Exception_SQL
  5999. *
  6000. * @param string $method desired query method (i.e. 'cell', 'col', 'exec' etc..)
  6001. * @param string $sql the sql you want to execute
  6002. * @param array $values array of values to be bound to query statement
  6003. *
  6004. * @return array $results results of query
  6005. */
  6006. private static function query($method, $sql, $values) {
  6007. if (!self::$redbean->isFrozen()) {
  6008. try {
  6009. $rs = RedBean_Facade::$adapter->$method($sql, $values);
  6010. }catch(RedBean_Exception_SQL $e) {
  6011. if(self::$writer->sqlStateIn($e->getSQLState(),
  6012. array(
  6013. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_COLUMN,
  6014. RedBean_QueryWriter::C_SQLSTATE_NO_SUCH_TABLE)
  6015. )) {
  6016. return array();
  6017. } else {
  6018. throw $e;
  6019. }
  6020. }
  6021. return $rs;
  6022. } else {
  6023. return RedBean_Facade::$adapter->$method($sql, $values);
  6024. }
  6025. }
  6026. /**
  6027. * Convenience function to execute Queries directly.
  6028. * Executes SQL.
  6029. * Results will be returned as an associative array. The first
  6030. * column in the select clause will be used for the keys in this array and
  6031. * the second column will be used for the values. If only one column is
  6032. * selected in the query, both key and value of the array will have the
  6033. * value of this field for each row.
  6034. *
  6035. * @param string $sql sql SQL query to execute
  6036. * @param array $values values a list of values to be bound to query parameters
  6037. *
  6038. * @return array $results
  6039. */
  6040. public static function getAssoc($sql, $values = array()) {
  6041. return self::query('getAssoc', $sql, $values);
  6042. }
  6043. /**
  6044. * Makes a copy of a bean. This method makes a deep copy
  6045. * of the bean.The copy will have the following features.
  6046. * - All beans in own-lists will be duplicated as well
  6047. * - All references to shared beans will be copied but not the shared beans themselves
  6048. * - All references to parent objects (_id fields) will be copied but not the parents themselves
  6049. * In most cases this is the desired scenario for copying beans.
  6050. * This function uses a trail-array to prevent infinite recursion, if a recursive bean is found
  6051. * (i.e. one that already has been processed) the ID of the bean will be returned.
  6052. * This should not happen though.
  6053. *
  6054. * Note:
  6055. * This function does a reflectional database query so it may be slow.
  6056. *
  6057. * @param RedBean_OODBBean $bean bean to be copied
  6058. * @param array $trail for internal usage, pass array()
  6059. * @param boolean $pid for internal usage
  6060. *
  6061. * @return array $copiedBean the duplicated bean
  6062. */
  6063. public static function dup($bean, $trail = array(), $pid = false, $filters = array()) {
  6064. self::$duplicationManager->setFilters($filters);
  6065. return self::$duplicationManager->dup($bean, $trail, $pid);
  6066. }
  6067. /**
  6068. * Exports a collection of beans. Handy for XML/JSON exports with a
  6069. * Javascript framework like Dojo or ExtJS.
  6070. * What will be exported:
  6071. * - contents of the bean
  6072. * - all own bean lists (recursively)
  6073. * - all shared beans (not THEIR own lists)
  6074. *
  6075. * @param array|RedBean_OODBBean $beans beans to be exported
  6076. * @param boolean $parents whether you want parent beans to be exported
  6077. * @param array $filters whitelist of types
  6078. *
  6079. * @return array $array exported structure
  6080. */
  6081. public static function exportAll($beans, $parents = false, $filters = array()) {
  6082. return self::$duplicationManager->exportAll($beans, $parents, $filters);
  6083. }
  6084. /**
  6085. * @deprecated
  6086. *
  6087. * @param array $beans beans
  6088. * @param string $property property
  6089. */
  6090. public static function swap($beans, $property) {
  6091. return self::$associationManager->swap($beans, $property);
  6092. }
  6093. /**
  6094. * Converts a series of rows to beans.
  6095. *
  6096. * @param string $type type
  6097. * @param array $rows must contain an array of arrays.
  6098. *
  6099. * @return array $beans
  6100. */
  6101. public static function convertToBeans($type, $rows) {
  6102. return self::$redbean->convertToBeans($type, $rows);
  6103. }
  6104. /**
  6105. * Part of RedBeanPHP Tagging API.
  6106. * Tests whether a bean has been associated with one ore more
  6107. * of the listed tags. If the third parameter is TRUE this method
  6108. * will return TRUE only if all tags that have been specified are indeed
  6109. * associated with the given bean, otherwise FALSE.
  6110. * If the third parameter is FALSE this
  6111. * method will return TRUE if one of the tags matches, FALSE if none
  6112. * match.
  6113. *
  6114. * @param RedBean_OODBBean $bean bean to check for tags
  6115. * @param array $tags list of tags
  6116. * @param boolean $all whether they must all match or just some
  6117. *
  6118. * @return boolean $didMatch whether the bean has been assoc. with the tags
  6119. */
  6120. public static function hasTag($bean, $tags, $all = false) {
  6121. return self::$tagManager->hasTag($bean, $tags, $all);
  6122. }
  6123. /**
  6124. * Part of RedBeanPHP Tagging API.
  6125. * Removes all sepcified tags from the bean. The tags specified in
  6126. * the second parameter will no longer be associated with the bean.
  6127. *
  6128. * @param RedBean_OODBBean $bean tagged bean
  6129. * @param array $tagList list of tags (names)
  6130. *
  6131. * @return void
  6132. */
  6133. public static function untag($bean, $tagList) {
  6134. return self::$tagManager->untag($bean, $tagList);
  6135. }
  6136. /**
  6137. * Part of RedBeanPHP Tagging API.
  6138. * Tags a bean or returns tags associated with a bean.
  6139. * If $tagList is null or omitted this method will return a
  6140. * comma separated list of tags associated with the bean provided.
  6141. * If $tagList is a comma separated list (string) of tags all tags will
  6142. * be associated with the bean.
  6143. * You may also pass an array instead of a string.
  6144. *
  6145. * @param RedBean_OODBBean $bean bean
  6146. * @param mixed $tagList tags
  6147. *
  6148. * @return string $commaSepListTags
  6149. */
  6150. public static function tag(RedBean_OODBBean $bean, $tagList = null) {
  6151. return self::$tagManager->tag($bean, $tagList);
  6152. }
  6153. /**
  6154. * Part of RedBeanPHP Tagging API.
  6155. * Adds tags to a bean.
  6156. * If $tagList is a comma separated list of tags all tags will
  6157. * be associated with the bean.
  6158. * You may also pass an array instead of a string.
  6159. *
  6160. * @param RedBean_OODBBean $bean bean
  6161. * @param array $tagList list of tags to add to bean
  6162. *
  6163. * @return void
  6164. */
  6165. public static function addTags(RedBean_OODBBean $bean, $tagList) {
  6166. return self::$tagManager->addTags($bean, $tagList);
  6167. }
  6168. /**
  6169. * Part of RedBeanPHP Tagging API.
  6170. * Returns all beans that have been tagged with one of the tags given.
  6171. *
  6172. * @param $beanType type of bean you are looking for
  6173. * @param $tagList list of tags to match
  6174. *
  6175. * @return array
  6176. */
  6177. public static function tagged($beanType, $tagList) {
  6178. return self::$tagManager->tagged($beanType, $tagList);
  6179. }
  6180. /**
  6181. * Part of RedBeanPHP Tagging API.
  6182. * Returns all beans that have been tagged with ALL of the tags given.
  6183. *
  6184. * @param $beanType type of bean you are looking for
  6185. * @param $tagList list of tags to match
  6186. *
  6187. * @return array
  6188. */
  6189. public static function taggedAll($beanType, $tagList) {
  6190. return self::$tagManager->taggedAll($beanType, $tagList);
  6191. }
  6192. /**
  6193. * Wipes all beans of type $beanType.
  6194. *
  6195. * @param string $beanType type of bean you want to destroy entirely.
  6196. */
  6197. public static function wipe($beanType) {
  6198. return RedBean_Facade::$redbean->wipe($beanType);
  6199. }
  6200. /**
  6201. * Counts beans
  6202. *
  6203. * @param string $beanType type of bean
  6204. * @param string $addSQL additional SQL snippet (for filtering, limiting)
  6205. * @param array $params parameters to bind to SQL
  6206. *
  6207. * @return integer $numOfBeans
  6208. */
  6209. public static function count($beanType, $addSQL = '', $params = array()) {
  6210. return RedBean_Facade::$redbean->count($beanType, $addSQL, $params);
  6211. }
  6212. /**
  6213. * Configures the facade, want to have a new Writer? A new Object Database or a new
  6214. * Adapter and you want it on-the-fly? Use this method to hot-swap your facade with a new
  6215. * toolbox.
  6216. *
  6217. * @param RedBean_ToolBox $tb toolbox
  6218. *
  6219. * @return RedBean_ToolBox $tb old, rusty, previously used toolbox
  6220. */
  6221. public static function configureFacadeWithToolbox(RedBean_ToolBox $tb) {
  6222. $oldTools = self::$toolbox;
  6223. self::$toolbox = $tb;
  6224. self::$writer = self::$toolbox->getWriter();
  6225. self::$adapter = self::$toolbox->getDatabaseAdapter();
  6226. self::$redbean = self::$toolbox->getRedBean();
  6227. self::$finder = new RedBean_Finder(self::$toolbox);
  6228. self::$associationManager = new RedBean_AssociationManager(self::$toolbox);
  6229. self::$redbean->setAssociationManager(self::$associationManager);
  6230. self::$labelMaker = new RedBean_LabelMaker(self::$toolbox);
  6231. self::$extAssocManager = new RedBean_AssociationManager_ExtAssociationManager(self::$toolbox);
  6232. $helper = new RedBean_ModelHelper();
  6233. $helper->attachEventListeners(self::$redbean);
  6234. self::$associationManager->addEventListener('delete', $helper);
  6235. self::$duplicationManager = new RedBean_DuplicationManager(self::$toolbox);
  6236. self::$tagManager = new RedBean_TagManager(self::$toolbox);
  6237. self::$f = new RedBean_SQLHelper(self::$adapter);
  6238. return $oldTools;
  6239. }
  6240. /**
  6241. * Facade Convience method for adapter transaction system.
  6242. * Begins a transaction.
  6243. *
  6244. * @return void
  6245. */
  6246. public static function begin() {
  6247. if (!self::$redbean->isFrozen()) return false;
  6248. self::$adapter->startTransaction();
  6249. return true;
  6250. }
  6251. /**
  6252. * Facade Convience method for adapter transaction system.
  6253. * Commits a transaction.
  6254. *
  6255. * @return void
  6256. */
  6257. public static function commit() {
  6258. if (!self::$redbean->isFrozen()) return false;
  6259. self::$adapter->commit();
  6260. return true;
  6261. }
  6262. /**
  6263. * Facade Convience method for adapter transaction system.
  6264. * Rolls back a transaction.
  6265. *
  6266. * @return void
  6267. */
  6268. public static function rollback() {
  6269. if (!self::$redbean->isFrozen()) return false;
  6270. self::$adapter->rollback();
  6271. return true;
  6272. }
  6273. /**
  6274. * Returns a list of columns. Format of this array:
  6275. * array( fieldname => type )
  6276. * Note that this method only works in fluid mode because it might be
  6277. * quite heavy on production servers!
  6278. *
  6279. * @param string $table name of the table (not type) you want to get columns of
  6280. *
  6281. * @return array $columns list of columns and their types
  6282. */
  6283. public static function getColumns($table) {
  6284. return self::$writer->getColumns($table);
  6285. }
  6286. /**
  6287. * Generates question mark slots for an array of values.
  6288. *
  6289. * @param array $array
  6290. * @return string $slots
  6291. */
  6292. public static function genSlots($array) {
  6293. return self::$f->genSlots($array);
  6294. }
  6295. /**
  6296. * Nukes the entire database.
  6297. */
  6298. public static function nuke() {
  6299. if (!self::$redbean->isFrozen()) {
  6300. self::$writer->wipeAll();
  6301. }
  6302. }
  6303. /**
  6304. * Sets a list of dependencies.
  6305. * A dependency list contains an entry for each dependent bean.
  6306. * A dependent bean will be removed if the relation with one of the
  6307. * dependencies gets broken.
  6308. *
  6309. * Example:
  6310. *
  6311. * array(
  6312. * 'page' => array('book', 'magazine')
  6313. * )
  6314. *
  6315. * A page will be removed if:
  6316. *
  6317. * unset($book->ownPage[$pageID]);
  6318. *
  6319. * or:
  6320. *
  6321. * unset($magazine->ownPage[$pageID]);
  6322. *
  6323. * but not if:
  6324. *
  6325. * unset($paper->ownPage[$pageID]);
  6326. *
  6327. *
  6328. * @param array $dep list of dependencies
  6329. */
  6330. public static function dependencies($dep) {
  6331. self::$redbean->setDepList($dep);
  6332. }
  6333. /**
  6334. * Short hand function to store a set of beans at once, IDs will be
  6335. * returned as an array. For information please consult the R::store()
  6336. * function.
  6337. * A loop saver.
  6338. *
  6339. * @param array $beans list of beans to be stored
  6340. *
  6341. * @return array $ids list of resulting IDs
  6342. */
  6343. public static function storeAll($beans) {
  6344. $ids = array();
  6345. foreach($beans as $bean) $ids[] = self::store($bean);
  6346. return $ids;
  6347. }
  6348. /**
  6349. * Short hand function to trash a set of beans at once.
  6350. * For information please consult the R::trash() function.
  6351. * A loop saver.
  6352. *
  6353. * @param array $beans list of beans to be trashed
  6354. */
  6355. public static function trashAll($beans) {
  6356. foreach($beans as $bean) self::trash($bean);
  6357. }
  6358. /**
  6359. * A label is a bean with only an id, type and name property.
  6360. * This function will dispense beans for all entries in the array. The
  6361. * values of the array will be assigned to the name property of each
  6362. * individual bean.
  6363. *
  6364. * @param string $type type of beans you would like to have
  6365. * @param array $labels list of labels, names for each bean
  6366. *
  6367. * @return array $bean a list of beans with type and name property
  6368. */
  6369. public static function dispenseLabels($type, $labels) {
  6370. return self::$labelMaker->dispenseLabels($type, $labels);
  6371. }
  6372. /**
  6373. * Gathers labels from beans. This function loops through the beans,
  6374. * collects the values of the name properties of each individual bean
  6375. * and stores the names in a new array. The array then gets sorted using the
  6376. * default sort function of PHP (sort).
  6377. *
  6378. * @param array $beans list of beans to loop
  6379. *
  6380. * @return array $array list of names of beans
  6381. */
  6382. public static function gatherLabels($beans) {
  6383. return self::$labelMaker->gatherLabels($beans);
  6384. }
  6385. /**
  6386. * Closes the database connection.
  6387. */
  6388. public static function close() {
  6389. if (isset(self::$adapter)) self::$adapter->close();
  6390. }
  6391. /**
  6392. * Simple convenience function, returns ISO date formatted representation
  6393. * of $time.
  6394. *
  6395. * @param mixed $time UNIX timestamp
  6396. *
  6397. * @return type
  6398. */
  6399. public static function isoDate($time = null) {
  6400. if (!$time) $time = time();
  6401. return @date('Y-m-d', $time);
  6402. }
  6403. /**
  6404. * Simple convenience function, returns ISO date time
  6405. * formatted representation
  6406. * of $time.
  6407. *
  6408. * @param mixed $time UNIX timestamp
  6409. *
  6410. * @return type
  6411. */
  6412. public static function isoDateTime($time = null) {
  6413. if (!$time) $time = time();
  6414. return @date('Y-m-d H:i:s', $time);
  6415. }
  6416. /**
  6417. * Optional accessor for neat code.
  6418. * Sets the database adapter you want to use.
  6419. *
  6420. * @param RedBean_Adapter $adapter
  6421. */
  6422. public static function setDatabaseAdapter(RedBean_Adapter $adapter) {
  6423. self::$adapter = $adapter;
  6424. }
  6425. /**
  6426. * Optional accessor for neat code.
  6427. * Sets the database adapter you want to use.
  6428. *
  6429. * @param RedBean_QueryWriter $writer
  6430. */
  6431. public static function setWriter(RedBean_QueryWriter $writer) {
  6432. self::$writer = $writer;
  6433. }
  6434. /**
  6435. * Optional accessor for neat code.
  6436. * Sets the database adapter you want to use.
  6437. *
  6438. * @param RedBean_OODB $redbean
  6439. */
  6440. public static function setRedBean(RedBean_OODB $redbean) {
  6441. self::$redbean = $redbean;
  6442. }
  6443. /**
  6444. * Optional accessor for neat code.
  6445. * Sets the database adapter you want to use.
  6446. *
  6447. * @return RedBean_DatabaseAdapter $adapter
  6448. */
  6449. public static function getDatabaseAdapter() {
  6450. return self::$adapter;
  6451. }
  6452. /**
  6453. * Optional accessor for neat code.
  6454. * Sets the database adapter you want to use.
  6455. *
  6456. * @return RedBean_QueryWriter $writer
  6457. */
  6458. public static function getWriter() {
  6459. return self::$writer;
  6460. }
  6461. /**
  6462. * Optional accessor for neat code.
  6463. * Sets the database adapter you want to use.
  6464. *
  6465. * @return RedBean_RedBean $redbean
  6466. */
  6467. public static function getRedBean() {
  6468. return self::$redbean;
  6469. }
  6470. /**
  6471. * Preloads certain properties for beans.
  6472. * Understands aliases.
  6473. *
  6474. * Usage: R::preload($books, array('coauthor'=>'author'));
  6475. *
  6476. * @param array $beans beans
  6477. * @param array $types types to load
  6478. */
  6479. public static function preload($beans, $types, $closure = null) {
  6480. return self::$redbean->preload($beans, $types, $closure);
  6481. }
  6482. //Alias for Preload.
  6483. public static function each($beans, $types, $closure = null) {
  6484. return self::preload($beans, $types, $closure);
  6485. }
  6486. /**
  6487. * Facade method for RedBean_QueryWriter_AQueryWriter::renameAssocation()
  6488. *
  6489. * @param string|array $from
  6490. * @param string $to
  6491. */
  6492. public static function renameAssociation($from, $to = null) {
  6493. RedBean_QueryWriter_AQueryWriter::renameAssociation($from, $to);
  6494. }
  6495. }
  6496. //Compatibility with PHP 5.2 and earlier
  6497. if (!function_exists('lcfirst')) {
  6498. function lcfirst($str){ return (string)(strtolower(substr($str, 0, 1)).substr($str, 1)); }
  6499. }
  6500. interface RedBean_Plugin { };
  6501. class RedBean_Plugin_BeanCan implements RedBean_Plugin {
  6502. /**
  6503. * @var RedBean_ModelHelper
  6504. */
  6505. private $modelHelper;
  6506. /**
  6507. * Constructor.
  6508. */
  6509. public function __construct() {
  6510. $this->modelHelper = new RedBean_ModelHelper;
  6511. }
  6512. /**
  6513. * Writes a response object for the client (JSON encoded). Internal method.
  6514. *
  6515. * @param mixed $result result
  6516. * @param integer $id request ID
  6517. * @param integer $errorCode error code from server
  6518. * @param string $errorMessage error message from server
  6519. *
  6520. * @return string $json JSON encoded response.
  6521. */
  6522. private function resp($result = null, $id = null, $errorCode = '-32603', $errorMessage = 'Internal Error') {
  6523. $response = array('jsonrpc' => '2.0');
  6524. if (!is_null($id)) { $response['id'] = $id; }
  6525. if ($result) {
  6526. $response['result'] = $result;
  6527. } else {
  6528. $response['error'] = array('code' => $errorCode, 'message' => $errorMessage);
  6529. }
  6530. return (json_encode($response));
  6531. }
  6532. /**
  6533. * Processes a JSON object request.
  6534. *
  6535. * @param array $jsonObject JSON request object
  6536. *
  6537. * @return mixed $result result
  6538. */
  6539. public function handleJSONRequest($jsonString) {
  6540. //Decode JSON string
  6541. $jsonArray = json_decode($jsonString, true);
  6542. if (!$jsonArray) return $this->resp(null, null, -32700, 'Cannot Parse JSON');
  6543. if (!isset($jsonArray['jsonrpc'])) return $this->resp(null, null, -32600, 'No RPC version');
  6544. if (($jsonArray['jsonrpc'] != '2.0')) return $this->resp(null, null, -32600, 'Incompatible RPC Version');
  6545. //DO we have an ID to identify this request?
  6546. if (!isset($jsonArray['id'])) return $this->resp(null, null, -32600, 'No ID');
  6547. //Fetch the request Identification String.
  6548. $id = $jsonArray['id'];
  6549. //Do we have a method?
  6550. if (!isset($jsonArray['method'])) return $this->resp(null, $id, -32600, 'No method');
  6551. //Do we have params?
  6552. if (!isset($jsonArray['params'])) {
  6553. $data = array();
  6554. } else {
  6555. $data = $jsonArray['params'];
  6556. }
  6557. //Check method signature
  6558. $method = explode(':', trim($jsonArray['method']));
  6559. if (count($method) != 2) {
  6560. return $this->resp(null, $id, -32600, 'Invalid method signature. Use: BEAN:ACTION');
  6561. }
  6562. //Collect Bean and Action
  6563. $beanType = $method[0];
  6564. $action = $method[1];
  6565. //May not contain anything other than ALPHA NUMERIC chars and _
  6566. if (preg_match('/\W/', $beanType)) return $this->resp(null, $id, -32600, 'Invalid Bean Type String');
  6567. if (preg_match('/\W/', $action)) return $this->resp(null, $id, -32600, 'Invalid Action String');
  6568. try {
  6569. switch($action) {
  6570. case 'store':
  6571. if (!isset($data[0])) return $this->resp(null, $id, -32602, 'First param needs to be Bean Object');
  6572. $data = $data[0];
  6573. if (!isset($data['id'])) $bean = RedBean_Facade::dispense($beanType); else $bean = RedBean_Facade::load($beanType, $data['id']);
  6574. $bean->import($data);
  6575. $rid = RedBean_Facade::store($bean);
  6576. return $this->resp($rid, $id);
  6577. case 'load':
  6578. if (!isset($data[0])) return $this->resp(null, $id, -32602, 'First param needs to be Bean ID');
  6579. $bean = RedBean_Facade::load($beanType, $data[0]);
  6580. return $this->resp($bean->export(), $id);
  6581. case 'trash':
  6582. if (!isset($data[0])) return $this->resp(null, $id, -32602, 'First param needs to be Bean ID');
  6583. $bean = RedBean_Facade::load($beanType, $data[0]);
  6584. RedBean_Facade::trash($bean);
  6585. return $this->resp('OK', $id);
  6586. case 'export':
  6587. if (!isset($data[0])) return $this->resp(null, $id, -32602, 'First param needs to be Bean ID');
  6588. $bean = RedBean_Facade::load($beanType, $data[0]);
  6589. $array = RedBean_Facade::exportAll(array($bean), true);
  6590. return $this->resp($array, $id);
  6591. default:
  6592. $modelName = $this->modelHelper->getModelName($beanType);
  6593. if (!class_exists($modelName)) return $this->resp(null, $id, -32601, 'No such bean in the can!');
  6594. $beanModel = new $modelName;
  6595. if (!method_exists($beanModel, $action)) return $this->resp(null, $id, -32601, "Method not found in Bean: $beanType ");
  6596. return $this->resp(call_user_func_array(array($beanModel, $action), $data), $id);
  6597. }
  6598. } catch(Exception $exception) {
  6599. return $this->resp(null, $id, -32099, $exception->getCode().'-'.$exception->getMessage());
  6600. }
  6601. }
  6602. /**
  6603. * Support for RESTFul GET-requests.
  6604. * Only supports very BASIC REST requests, for more functionality please use
  6605. * the JSON-RPC 2 interface.
  6606. *
  6607. * @param string $pathToResource RESTFul path to resource
  6608. *
  6609. * @return string $json a JSON encoded response ready for sending to client
  6610. */
  6611. public function handleRESTGetRequest($pathToResource) {
  6612. if (!is_string($pathToResource)) return $this->resp(null, 0, -32099, 'IR');
  6613. $resourceInfo = explode('/', $pathToResource);
  6614. $type = $resourceInfo[0];
  6615. try {
  6616. if (count($resourceInfo) < 2) {
  6617. return $this->resp(RedBean_Facade::findAndExport($type));
  6618. } else {
  6619. $id = (int) $resourceInfo[1];
  6620. return $this->resp(RedBean_Facade::load($type, $id)->export(), $id);
  6621. }
  6622. } catch(Exception $e) {
  6623. return $this->resp(null, 0, -32099);
  6624. }
  6625. }
  6626. }
  6627. class RedBean_Plugin_QueryLogger implements RedBean_Observer, RedBean_Plugin {
  6628. /**
  6629. * @var array
  6630. */
  6631. protected $logs = array();
  6632. /**
  6633. * Creates a new instance of the Query Logger and attaches
  6634. * this logger to the adapter.
  6635. *
  6636. * @static
  6637. * @param RedBean_Observable $adapter the adapter you want to attach to
  6638. *
  6639. * @return RedBean_Plugin_QueryLogger $querylogger instance of the Query Logger
  6640. */
  6641. public static function getInstanceAndAttach(RedBean_Observable $adapter) {
  6642. $queryLog = new RedBean_Plugin_QueryLogger;
  6643. $adapter->addEventListener('sql_exec', $queryLog);
  6644. return $queryLog;
  6645. }
  6646. /**
  6647. * Singleton pattern
  6648. * Constructor - private
  6649. */
  6650. private function __construct(){}
  6651. /**
  6652. * Implementation of the onEvent() method for Observer interface.
  6653. * If a query gets executed this method gets invoked because the
  6654. * adapter will send a signal to the attached logger.
  6655. *
  6656. * @param string $eventName ID of the event (name)
  6657. * @param RedBean_DBAdapter $adapter adapter that sends the signal
  6658. *
  6659. * @return void
  6660. */
  6661. public function onEvent($eventName, $adapter) {
  6662. if ($eventName == 'sql_exec') {
  6663. $this->logs[] = $adapter->getSQL();
  6664. }
  6665. }
  6666. /**
  6667. * Searches the logs for the given word and returns the entries found in
  6668. * the log container.
  6669. *
  6670. * @param string $word word to look for
  6671. *
  6672. * @return array $entries entries that contain the keyword
  6673. */
  6674. public function grep($word) {
  6675. $found = array();
  6676. foreach($this->logs as $log) {
  6677. if (strpos($log, $word) !== false) {
  6678. $found[] = $log;
  6679. }
  6680. }
  6681. return $found;
  6682. }
  6683. /**
  6684. * Returns all the logs.
  6685. *
  6686. * @return array $logs logs
  6687. */
  6688. public function getLogs() { return $this->logs; }
  6689. /**
  6690. * Clears the logs.
  6691. *
  6692. * @return void
  6693. */
  6694. public function clear() { $this->logs = array();}
  6695. }
  6696. class RedBean_Plugin_Cooker implements RedBean_Plugin {
  6697. /**
  6698. * @var boolean
  6699. */
  6700. private static $loadBeans = false;
  6701. /**
  6702. * @var boolean
  6703. */
  6704. private static $useNULLForEmptyString = false;
  6705. /**
  6706. * If you enable bean loading graph will load beans if there is an ID in the array.
  6707. * This is very powerful but can also cause security issues if a user knows how to
  6708. * manipulate beans and there is no model based ID validation.
  6709. *
  6710. * @param boolean $yesNo
  6711. */
  6712. public static function enableBeanLoading($yesNo) {
  6713. self::$loadBeans = ($yesNo);
  6714. }
  6715. /**
  6716. * Sets the toolbox to be used by graph()
  6717. *
  6718. * @param RedBean_Toolbox $toolbox toolbox
  6719. * @return void
  6720. */
  6721. public function setToolbox(RedBean_Toolbox $toolbox) {
  6722. $this->toolbox = $toolbox;
  6723. $this->redbean = $this->toolbox->getRedbean();
  6724. }
  6725. /**
  6726. * Turns an array (post/request array) into a collection of beans.
  6727. * Handy for turning forms into bean structures that can be stored with a
  6728. * single call.
  6729. *
  6730. * Typical usage:
  6731. *
  6732. * $struct = R::graph($_POST);
  6733. * R::store($struct);
  6734. *
  6735. * Example of a valid array:
  6736. *
  6737. * $form = array(
  6738. * 'type' => 'order',
  6739. * 'ownProduct' => array(
  6740. * array('id' => 171, 'type' => 'product'),
  6741. * ),
  6742. * 'ownCustomer' => array(
  6743. * array('type' => 'customer', 'name' => 'Bill')
  6744. * ),
  6745. * 'sharedCoupon' => array(
  6746. * array('type' => 'coupon', 'name' => '123'),
  6747. * array('type' => 'coupon', 'id' => 3)
  6748. * )
  6749. * );
  6750. *
  6751. * Each entry in the array will become a property of the bean.
  6752. * The array needs to have a type-field indicating the type of bean it is
  6753. * going to be. The array can have nested arrays. A nested array has to be
  6754. * named conform the bean-relation conventions, i.e. ownPage/sharedPage
  6755. * each entry in the nested array represents another bean.
  6756. *
  6757. * @param array $array array to be turned into a bean collection
  6758. * @param boolean $filterEmpty whether you want to exclude empty beans
  6759. *
  6760. * @return array $beans beans
  6761. */
  6762. public function graph($array, $filterEmpty = false) {
  6763. $beans = array();
  6764. if (is_array($array) && isset($array['type'])) {
  6765. $type = $array['type'];
  6766. unset($array['type']);
  6767. //Do we need to load the bean?
  6768. if (isset($array['id'])) {
  6769. if (self::$loadBeans) {
  6770. $id = (int) $array['id'];
  6771. $bean = $this->redbean->load($type, $id);
  6772. } else {
  6773. throw new RedBean_Exception_Security('Attempt to load a bean in Cooker. Use enableBeanLoading to override but please read security notices first.');
  6774. }
  6775. } else {
  6776. $bean = $this->redbean->dispense($type);
  6777. }
  6778. foreach($array as $property => $value) {
  6779. if (is_array($value)) {
  6780. $bean->$property = $this->graph($value, $filterEmpty);
  6781. } else {
  6782. if($value == '' && self::$useNULLForEmptyString){
  6783. $bean->$property = null;
  6784. } else $bean->$property = $value;
  6785. }
  6786. }
  6787. return $bean;
  6788. } elseif (is_array($array)) {
  6789. foreach($array as $key => $value) {
  6790. $listBean = $this->graph($value, $filterEmpty);
  6791. if (!($listBean instanceof RedBean_OODBBean)) {
  6792. throw new RedBean_Exception_Security('Expected bean but got :'.gettype($listBean));
  6793. }
  6794. if ($listBean->isEmpty()) {
  6795. if (!$filterEmpty) {
  6796. $beans[$key] = $listBean;
  6797. }
  6798. } else {
  6799. $beans[$key] = $listBean;
  6800. }
  6801. }
  6802. return $beans;
  6803. } else {
  6804. throw new RedBean_Exception_Security('Expected array but got :'.gettype($array));
  6805. }
  6806. }
  6807. /**
  6808. * Toggles the use-NULL flag.
  6809. *
  6810. * @param boolean $yesNo
  6811. */
  6812. public function setUseNullFlag($yesNo) {
  6813. self::$useNULLForEmptyString = (boolean) $yesNo;
  6814. }
  6815. }
  6816. class RedBean_Plugin_Cache extends RedBean_OODB implements RedBean_Plugin {
  6817. /**
  6818. * @var array
  6819. */
  6820. protected $cache = array();
  6821. /**
  6822. * @var integer
  6823. */
  6824. protected $hits = 0;
  6825. /**
  6826. * @var integer
  6827. */
  6828. protected $misses = 0;
  6829. /**
  6830. * Constructor.
  6831. * Cache decorates RedBeanPHP OODB class, so needs a writer.
  6832. *
  6833. * @param RedBean_QueryWriter $writer
  6834. */
  6835. public function __construct(RedBean_QueryWriter $writer) {
  6836. parent::__construct($writer);
  6837. }
  6838. /**
  6839. * Loads a bean by type and id. If the bean cannot be found an
  6840. * empty bean will be returned instead. This is a cached version
  6841. * of the loader, if the bean has been cached it will be served
  6842. * from cache, otherwise the bean will be retrieved from the database
  6843. * as usual an a new cache entry will be added..
  6844. *
  6845. * @param string $type type of bean you are looking for
  6846. * @param integer $id identifier of the bean
  6847. *
  6848. * @return RedBean_OODBBean $bean the bean object found
  6849. */
  6850. public function load($type, $id) {
  6851. if (isset($this->cache[$type][$id])) {
  6852. $this->hits ++;
  6853. $bean = $this->cache[$type][$id];
  6854. } else {
  6855. $this->misses ++;
  6856. $bean = parent::load($type, $id);
  6857. if ($bean->id) {
  6858. if (!isset($this->cache[$type])) $this->cache[$type] = array();
  6859. $this->cache[$type][$id] = $bean;
  6860. }
  6861. }
  6862. return $bean;
  6863. }
  6864. /**
  6865. * Stores a RedBean OODBBean and caches it.
  6866. *
  6867. * @param RedBean_OODBBean $bean the bean you want to store
  6868. *
  6869. * @return integer $id
  6870. */
  6871. public function store($bean) {
  6872. $id = parent::store($bean);
  6873. $type = $bean->getMeta('type');
  6874. if (!isset($this->cache[$type])) $this->cache[$type] = array();
  6875. $this->cache[$type][$id] = $bean;
  6876. return $id;
  6877. }
  6878. /**
  6879. * Trashes a RedBean OODBBean and removes it from cache.
  6880. *
  6881. * @param RedBean_OODBBean $bean bean
  6882. * @return mixed
  6883. */
  6884. public function trash($bean) {
  6885. $type = $bean->getMeta('type');
  6886. $id = $bean->id;
  6887. if (isset($this->cache[$type][$id])) unset($this->cache[$type][$id]);
  6888. return parent::trash($bean);
  6889. }
  6890. /**
  6891. * Flushes the cache for a given type.
  6892. *
  6893. * @param string $type
  6894. *
  6895. * @return RedBean_Plugin_Cache
  6896. */
  6897. public function flush($type) {
  6898. if (isset($this->cache[$type])) $this->cache[$type] = array();
  6899. return $this;
  6900. }
  6901. /**
  6902. * Flushes the cache completely.
  6903. *
  6904. * @return RedBean_Plugin_Cache
  6905. */
  6906. public function flushAll() {
  6907. $this->cache = array();
  6908. return $this;
  6909. }
  6910. /**
  6911. * Returns the number of hits. If a call to load() or
  6912. * batch() can use the cache this counts as a hit.
  6913. * Otherwise it's a miss.
  6914. *
  6915. * @return integer
  6916. */
  6917. public function getHits() {
  6918. return $this->hits;
  6919. }
  6920. /**
  6921. * Returns the number of hits. If a call to load() or
  6922. * batch() can use the cache this counts as a hit.
  6923. * Otherwise it's a miss.
  6924. *
  6925. * @return integer
  6926. */
  6927. public function getMisses() {
  6928. return $this->misses;
  6929. }
  6930. /**
  6931. * Resets hits counter to 0.
  6932. */
  6933. public function resetHits() {
  6934. $this->hits = 0;
  6935. }
  6936. /**
  6937. * Resets misses counter to 0.
  6938. */
  6939. public function resetMisses() {
  6940. $this->misses = 0;
  6941. }
  6942. }
  6943. class RedBean_DependencyInjector {
  6944. /**
  6945. * @var array
  6946. */
  6947. protected $dependencies = array();
  6948. /**
  6949. * Adds a dependency to the list.
  6950. * You can add dependencies using this method. Pass both the key of the
  6951. * dependency and the dependency itself. The key of the dependency is a
  6952. * name that should match the setter. For instance if you have a dependency
  6953. * class called My_Mailer and a setter on the model called setMailSystem
  6954. * you should pass an instance of My_Mailer with key MailSystem.
  6955. * The injector will now look for a setter called setMailSystem.
  6956. *
  6957. * @param string $dependencyID name of the dependency (should match setter)
  6958. * @param mixed $dependency the service to be injected
  6959. */
  6960. public function addDependency($dependencyID, $dependency) {
  6961. $this->dependencies[$dependencyID] = $dependency;
  6962. }
  6963. /**
  6964. * Returns an instance of the class $modelClassName completely
  6965. * configured as far as possible with all the available
  6966. * service objects in the dependency list.
  6967. *
  6968. * @param string $modelClassName the name of the class of the model
  6969. *
  6970. * @return mixed $object the model/object
  6971. */
  6972. public function getInstance($modelClassName) {
  6973. $object = new $modelClassName;
  6974. if ($this->dependencies && is_array($this->dependencies)) {
  6975. foreach($this->dependencies as $key => $dep) {
  6976. $depSetter = 'set'.$key;
  6977. if (method_exists($object, $depSetter)) {
  6978. $object->$depSetter($dep);
  6979. }
  6980. }
  6981. }
  6982. return $object;
  6983. }
  6984. }
  6985. class RedBean_DuplicationManager {
  6986. /**
  6987. * @var RedBean_Toolbox
  6988. */
  6989. protected $toolbox;
  6990. /**
  6991. * @var RedBean_AssociationManager
  6992. */
  6993. protected $associationManager;
  6994. /**
  6995. * @var RedBean_OODB
  6996. */
  6997. protected $redbean;
  6998. /**
  6999. * @var array
  7000. */
  7001. protected $tables = array();
  7002. /**
  7003. * @var array
  7004. */
  7005. protected $columns = array();
  7006. /**
  7007. * @var array
  7008. */
  7009. protected $filters = array();
  7010. /**
  7011. * @var array
  7012. */
  7013. protected $cacheTables = false;
  7014. /**
  7015. * Constructor,
  7016. * creates a new instance of DupManager.
  7017. * @param RedBean_Toolbox $toolbox
  7018. */
  7019. public function __construct(RedBean_Toolbox $toolbox) {
  7020. $this->toolbox = $toolbox;
  7021. $this->redbean = $toolbox->getRedBean();
  7022. $this->associationManager = $this->redbean->getAssociationManager();
  7023. }
  7024. /**
  7025. * For better performance you can pass the tables in an array to this method.
  7026. * If the tables are available the duplication manager will not query them so
  7027. * this might be beneficial for performance.
  7028. *
  7029. * @param array $tables
  7030. */
  7031. public function setTables($tables) {
  7032. foreach($tables as $key => $value) {
  7033. if (is_numeric($key)) {
  7034. $this->tables[] = $value;
  7035. } else {
  7036. $this->tables[] = $key;
  7037. $this->columns[$key] = $value;
  7038. }
  7039. }
  7040. $this->cacheTables = true;
  7041. }
  7042. /**
  7043. * Returns a schema array for cache.
  7044. *
  7045. * @return array
  7046. */
  7047. public function getSchema() {
  7048. return $this->columns;
  7049. }
  7050. /**
  7051. * Indicates whether you want the duplication manager to cache the database schema.
  7052. * If this flag is set to TRUE the duplication manager will query the database schema
  7053. * only once. Otherwise the duplicationmanager will, by default, query the schema
  7054. * every time a duplication action is performed (dup()).
  7055. *
  7056. * @param boolean $yesNo
  7057. */
  7058. public function setCacheTables($yesNo) {
  7059. $this->cacheTables = $yesNo;
  7060. }
  7061. /**
  7062. * A filter array is an array with table names.
  7063. * By setting a table filter you can make the duplication manager only take into account
  7064. * certain bean types. Other bean types will be ignored when exporting or making a
  7065. * deep copy. If no filters are set all types will be taking into account, this is
  7066. * the default behavior.
  7067. *
  7068. * @param array $filters
  7069. */
  7070. public function setFilters($filters) {
  7071. $this->filters = $filters;
  7072. }
  7073. /**
  7074. * Determines whether the bean has an own list based on
  7075. * schema inspection from realtime schema or cache.
  7076. *
  7077. * @param string $type bean type
  7078. * @param string $target type of list you want to detect
  7079. *
  7080. * @return boolean
  7081. */
  7082. protected function hasOwnList($type, $target) {
  7083. return (isset($this->columns[$target][$type.'_id']));
  7084. }
  7085. /**
  7086. * Determines whether the bea has a shared list based on
  7087. * schema inspection from realtime schema or cache.
  7088. *
  7089. * @param string $type bean type
  7090. * @param string $target type of list you are looking for
  7091. *
  7092. * @return boolean
  7093. */
  7094. protected function hasSharedList($type, $target) {
  7095. return (in_array(RedBean_QueryWriter_AQueryWriter::getAssocTableFormat(array($type, $target)), $this->tables));
  7096. }
  7097. /**
  7098. * Makes a copy of a bean. This method makes a deep copy
  7099. * of the bean.The copy will have the following features.
  7100. * - All beans in own-lists will be duplicated as well
  7101. * - All references to shared beans will be copied but not the shared beans themselves
  7102. * - All references to parent objects (_id fields) will be copied but not the parents themselves
  7103. * In most cases this is the desired scenario for copying beans.
  7104. * This function uses a trail-array to prevent infinite recursion, if a recursive bean is found
  7105. * (i.e. one that already has been processed) the ID of the bean will be returned.
  7106. * This should not happen though.
  7107. *
  7108. * Note:
  7109. * This function does a reflectional database query so it may be slow.
  7110. *
  7111. * Note:
  7112. * this function actually passes the arguments to a protected function called
  7113. * duplicate() that does all the work. This method takes care of creating a clone
  7114. * of the bean to avoid the bean getting tainted (triggering saving when storing it).
  7115. *
  7116. * @param RedBean_OODBBean $bean bean to be copied
  7117. * @param array $trail for internal usage, pass array()
  7118. * @param boolean $pid for internal usage
  7119. *
  7120. * @return array $copiedBean the duplicated bean
  7121. */
  7122. public function dup($bean, $trail = array(), $pid = false) {
  7123. if (!count($this->tables)) $this->tables = $this->toolbox->getWriter()->getTables();
  7124. if (!count($this->columns)) foreach($this->tables as $table) $this->columns[$table] = $this->toolbox->getWriter()->getColumns($table);
  7125. $beanCopy = clone($bean);
  7126. $rs = $this->duplicate($beanCopy, $trail, $pid);
  7127. if (!$this->cacheTables) {
  7128. $this->tables = array();
  7129. $this->columns = array();
  7130. }
  7131. return $rs;
  7132. }
  7133. /**
  7134. * @see RedBean_DuplicationManager::dup
  7135. *
  7136. * @param RedBean_OODBBean $bean bean to be copied
  7137. * @param array $trail trail to prevent infinite loops
  7138. * @param boolean $pid preserve IDs
  7139. *
  7140. * @return array $copiedBean the duplicated bean
  7141. */
  7142. protected function duplicate($bean, $trail = array(), $pid = false) {
  7143. $type = $bean->getMeta('type');
  7144. $key = $type.$bean->getID();
  7145. if (isset($trail[$key])) return $bean;
  7146. $trail[$key] = $bean;
  7147. $copy = $this->redbean->dispense($type);
  7148. $copy->importFrom($bean);
  7149. $copy->id = 0;
  7150. $tables = $this->tables;
  7151. foreach($tables as $table) {
  7152. if (is_array($this->filters) && count($this->filters) && !in_array($table, $this->filters)) continue;
  7153. if ($table == $type) continue;
  7154. $owned = 'own'.ucfirst($table);
  7155. $shared = 'shared'.ucfirst($table);
  7156. if ($this->hasSharedList($type, $table)) {
  7157. if ($beans = $bean->$shared) {
  7158. $copy->$shared = array();
  7159. foreach($beans as $subBean) {
  7160. array_push($copy->$shared, $subBean);
  7161. }
  7162. }
  7163. } elseif ($this->hasOwnList($type, $table)) {
  7164. if ($beans = $bean->$owned) {
  7165. $copy->$owned = array();
  7166. foreach($beans as $subBean) {
  7167. array_push($copy->$owned, $this->duplicate($subBean, $trail, $pid));
  7168. }
  7169. }
  7170. $copy->setMeta('sys.shadow.'.$owned, null);
  7171. }
  7172. $copy->setMeta('sys.shadow.'.$shared, null);
  7173. }
  7174. if ($pid) $copy->id = $bean->id;
  7175. return $copy;
  7176. }
  7177. /**
  7178. * Exports a collection of beans. Handy for XML/JSON exports with a
  7179. * Javascript framework like Dojo or ExtJS.
  7180. * What will be exported:
  7181. * - contents of the bean
  7182. * - all own bean lists (recursively)
  7183. * - all shared beans (not THEIR own lists)
  7184. *
  7185. * @param array|RedBean_OODBBean $beans beans to be exported
  7186. * @param boolean $parents also export parents
  7187. * @param array $filters only these types (whitelist)
  7188. *
  7189. * @return array $array exported structure
  7190. */
  7191. public function exportAll($beans, $parents = false, $filters = array()) {
  7192. $array = array();
  7193. if (!is_array($beans)) $beans = array($beans);
  7194. foreach($beans as $bean) {
  7195. $this->setFilters($filters);
  7196. $f = $this->dup($bean, array(), true);
  7197. $array[] = $f->export(false, $parents, false, $filters);
  7198. }
  7199. return $array;
  7200. }
  7201. }
  7202. class R extends RedBean_Facade{
  7203. public static function graph($array, $filterEmpty=false) { $c = new RedBean_Plugin_Cooker(); $c->setToolbox(self::$toolbox);return $c->graph($array, $filterEmpty);}
  7204. }