DataObject.php 165 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782
  1. <?php
  2. /**
  3. * Object Based Database Query Builder and data store
  4. *
  5. * For PHP versions 4,5 and 6
  6. *
  7. * LICENSE: This source file is subject to version 3.01 of the PHP license
  8. * that is available through the world-wide-web at the following URI:
  9. * http://www.php.net/license/3_01.txt. If you did not receive a copy of
  10. * the PHP License and are unable to obtain it through the web, please
  11. * send a note to license@php.net so we can mail you a copy immediately.
  12. *
  13. * @category Database
  14. * @package DB_DataObject
  15. * @author Alan Knowles <alan@akbkhome.com>
  16. * @copyright 1997-2006 The PHP Group
  17. * @license http://www.php.net/license/3_01.txt PHP License 3.01
  18. * @version CVS: $Id: DataObject.php 336751 2015-05-12 04:39:50Z alan_k $
  19. * @link http://pear.php.net/package/DB_DataObject
  20. */
  21. /* ===========================================================================
  22. *
  23. * !!!!!!!!!!!!! W A R N I N G !!!!!!!!!!!
  24. *
  25. * THIS MAY SEGFAULT PHP IF YOU ARE USING THE ZEND OPTIMIZER (to fix it,
  26. * just add "define('DB_DATAOBJECT_NO_OVERLOAD',true);" before you include
  27. * this file. reducing the optimization level may also solve the segfault.
  28. * ===========================================================================
  29. */
  30. /**
  31. * Needed classes
  32. * - we use getStaticProperty from PEAR pretty extensively (cant remove it ATM)
  33. */
  34. require_once 'PEAR.php';
  35. /**
  36. * We are duping fetchmode constants to be compatible with
  37. * both DB and MDB2
  38. */
  39. define('DB_DATAOBJECT_FETCHMODE_ORDERED', 1);
  40. define('DB_DATAOBJECT_FETCHMODE_ASSOC', 2);
  41. /**
  42. * these are constants for the get_table array
  43. * user to determine what type of escaping is required around the object vars.
  44. */
  45. define('DB_DATAOBJECT_INT', 1); // does not require ''
  46. define('DB_DATAOBJECT_STR', 2); // requires ''
  47. define('DB_DATAOBJECT_DATE', 4); // is date #TODO
  48. define('DB_DATAOBJECT_TIME', 8); // is time #TODO
  49. define('DB_DATAOBJECT_BOOL', 16); // is boolean #TODO
  50. define('DB_DATAOBJECT_TXT', 32); // is long text #TODO
  51. define('DB_DATAOBJECT_BLOB', 64); // is blob type
  52. define('DB_DATAOBJECT_NOTNULL', 128); // not null col.
  53. define('DB_DATAOBJECT_MYSQLTIMESTAMP', 256); // mysql timestamps (ignored by update/insert)
  54. /*
  55. * Define this before you include DataObjects.php to disable overload - if it segfaults due to Zend optimizer..
  56. */
  57. //define('DB_DATAOBJECT_NO_OVERLOAD',true)
  58. /**
  59. * Theses are the standard error codes, most methods will fail silently - and return false
  60. * to access the error message either use $table->_lastError
  61. * or $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
  62. * the code is $last_error->code, and the message is $last_error->message (a standard PEAR error)
  63. */
  64. define('DB_DATAOBJECT_ERROR_INVALIDARGS', -1); // wrong args to function
  65. define('DB_DATAOBJECT_ERROR_NODATA', -2); // no data available
  66. define('DB_DATAOBJECT_ERROR_INVALIDCONFIG', -3); // something wrong with the config
  67. define('DB_DATAOBJECT_ERROR_NOCLASS', -4); // no class exists
  68. define('DB_DATAOBJECT_ERROR_INVALID_CALL', -7); // overlad getter/setter failure
  69. /**
  70. * Used in methods like delete() and count() to specify that the method should
  71. * build the condition only out of the whereAdd's and not the object parameters.
  72. */
  73. define('DB_DATAOBJECT_WHEREADD_ONLY', true);
  74. /**
  75. *
  76. * storage for connection and result objects,
  77. * it is done this way so that print_r()'ing the is smaller, and
  78. * it reduces the memory size of the object.
  79. * -- future versions may use $this->_connection = & PEAR object..
  80. * although will need speed tests to see how this affects it.
  81. * - includes sub arrays
  82. * - connections = md5 sum mapp to pear db object
  83. * - results = [id] => map to pear db object
  84. * - resultseq = sequence id for results & results field
  85. * - resultfields = [id] => list of fields return from query (for use with toArray())
  86. * - ini = mapping of database to ini file results
  87. * - links = mapping of database to links file
  88. * - lasterror = pear error objects for last error event.
  89. * - config = aliased view of PEAR::getStaticPropery('DB_DataObject','options') * done for performance.
  90. * - array of loaded classes by autoload method - to stop it doing file access request over and over again!
  91. */
  92. $GLOBALS['_DB_DATAOBJECT']['RESULTS'] = array();
  93. $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ'] = 1;
  94. $GLOBALS['_DB_DATAOBJECT']['RESULTFIELDS'] = array();
  95. $GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'] = array();
  96. $GLOBALS['_DB_DATAOBJECT']['INI'] = array();
  97. $GLOBALS['_DB_DATAOBJECT']['LINKS'] = array();
  98. $GLOBALS['_DB_DATAOBJECT']['SEQUENCE'] = array();
  99. $GLOBALS['_DB_DATAOBJECT']['LASTERROR'] = null;
  100. $GLOBALS['_DB_DATAOBJECT']['CONFIG'] = array();
  101. $GLOBALS['_DB_DATAOBJECT']['CACHE'] = array();
  102. $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = false;
  103. $GLOBALS['_DB_DATAOBJECT']['QUERYENDTIME'] = 0;
  104. // this will be horrifically slow!!!!
  105. // these two are BC/FC handlers for call in PHP4/5
  106. if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
  107. class DB_DataObject_Overload
  108. {
  109. public function __call($method, $args)
  110. {
  111. $return = null;
  112. $this->_call($method, $args, $return);
  113. return $return;
  114. }
  115. public function __sleep()
  116. {
  117. return array_keys(get_object_vars($this));
  118. }
  119. }
  120. } else {
  121. class DB_DataObject_Overload
  122. {
  123. }
  124. }
  125. /*
  126. *
  127. * @package DB_DataObject
  128. * @author Alan Knowles <alan@akbkhome.com>
  129. * @since PHP 4.0
  130. */
  131. class DB_DataObject extends DB_DataObject_Overload
  132. {
  133. /**
  134. * The Version - use this to check feature changes
  135. *
  136. * @access private
  137. * @var string
  138. */
  139. public $_DB_DataObject_version = "1.11.3";
  140. /**
  141. * The Database table (used by table extends)
  142. *
  143. * @access private
  144. * @var string
  145. */
  146. public $__table = ''; // database table
  147. /**
  148. * The Number of rows returned from a query
  149. *
  150. * @access public
  151. * @var int
  152. */
  153. public $N = 0; // Number of rows returned from a query
  154. /* ============================================================= */
  155. /* Major Public Methods */
  156. /* (designed to be optionally then called with parent::method()) */
  157. /* ============================================================= */
  158. /**
  159. * The Database connection dsn (as described in the PEAR DB)
  160. * only used really if you are writing a very simple application/test..
  161. * try not to use this - it is better stored in configuration files..
  162. *
  163. * @access private
  164. * @var string
  165. */
  166. public $_database_dsn = '';
  167. /**
  168. * The Database connection id (md5 sum of databasedsn)
  169. *
  170. * @access private
  171. * @var string
  172. */
  173. public $_database_dsn_md5 = '';
  174. /**
  175. * The Database name
  176. * created in __connection
  177. *
  178. * @access private
  179. * @var string
  180. */
  181. public $_database = '';
  182. /**
  183. * The QUERY rules
  184. * This replaces alot of the private variables
  185. * used to build a query, it is unset after find() is run.
  186. *
  187. *
  188. *
  189. * @access private
  190. * @var array
  191. */
  192. public $_query = array(
  193. 'condition' => '', // the WHERE condition
  194. 'group_by' => '', // the GROUP BY condition
  195. 'order_by' => '', // the ORDER BY condition
  196. 'having' => '', // the HAVING condition
  197. 'useindex' => '', // the USE INDEX condition
  198. 'limit_start' => '', // the LIMIT condition
  199. 'limit_count' => '', // the LIMIT condition
  200. 'data_select' => '*', // the columns to be SELECTed
  201. 'unions' => array(), // the added unions,
  202. 'derive_table' => '', // derived table name (BETA)
  203. 'derive_select' => '', // derived table select (BETA)
  204. );
  205. /**
  206. * Database result id (references global $_DB_DataObject[results]
  207. *
  208. * @access private
  209. * @var integer
  210. */
  211. public $_DB_resultid;
  212. /**
  213. * ResultFields - on the last call to fetch(), resultfields is sent here,
  214. * so we can clean up the memory.
  215. *
  216. * @access public
  217. * @var array
  218. */
  219. public $_resultFields = false;
  220. /**
  221. * Have the links been loaded?
  222. * if they have it contains a array of those variables.
  223. *
  224. * @access private
  225. * @var boolean | array
  226. */
  227. public $_link_loaded = false;
  228. /**
  229. * The JOIN condition
  230. *
  231. * @access private
  232. * @var string
  233. */
  234. public $_join = '';
  235. /**
  236. * Last Error that has occured
  237. * - use $this->_lastError or
  238. * $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
  239. *
  240. * @access public
  241. * @var object PEAR_Error (or false)
  242. */
  243. public $_lastError = false;
  244. /**
  245. * sets and returns debug level
  246. * eg. DB_DataObject::debugLevel(4);
  247. *
  248. * @param int $v level
  249. * @access public
  250. * @return int|none
  251. */
  252. public static function debugLevel($v = null)
  253. {
  254. global $_DB_DATAOBJECT;
  255. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  256. (new DB_DataObject)->_loadConfig();
  257. }
  258. if ($v !== null) {
  259. $r = isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
  260. $_DB_DATAOBJECT['CONFIG']['debug'] = $v;
  261. return $r;
  262. }
  263. return isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
  264. }
  265. /**
  266. * Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to PEAR::getStaticProperty('DB_DataObject','options');
  267. *
  268. * After Profiling DB_DataObject, I discoved that the debug calls where taking
  269. * considerable time (well 0.1 ms), so this should stop those calls happening. as
  270. * all calls to debug are wrapped with direct variable queries rather than actually calling the funciton
  271. * THIS STILL NEEDS FURTHER INVESTIGATION
  272. *
  273. * @access public
  274. * @return void an error object
  275. */
  276. public function _loadConfig()
  277. {
  278. global $_DB_DATAOBJECT;
  279. $_DB_DATAOBJECT['CONFIG'] = &(new PEAR)->getStaticProperty('DB_DataObject', 'options');
  280. return null;
  281. }
  282. /**
  283. * (deprecated - use ::get / and your own caching method)
  284. * @param $class
  285. * @param $k
  286. * @param null $v
  287. * @return bool
  288. */
  289. public static function staticGet($class, $k, $v = null)
  290. {
  291. $lclass = strtolower($class);
  292. global $_DB_DATAOBJECT;
  293. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  294. (new DB_DataObject)->_loadConfig();
  295. }
  296. $key = "$k:$v";
  297. if ($v === null) {
  298. $key = $k;
  299. }
  300. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  301. (new DB_DataObject)->debug("$class $key", "STATIC GET - TRY CACHE");
  302. }
  303. if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
  304. return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
  305. }
  306. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  307. (new DB_DataObject)->debug("$class $key", "STATIC GET - NOT IN CACHE");
  308. }
  309. $obj = DB_DataObject::factory(substr($class, strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
  310. if ((new PEAR)->isError($obj)) {
  311. $dor = new DB_DataObject();
  312. $dor->raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
  313. $r = false;
  314. return $r;
  315. }
  316. if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
  317. $_DB_DATAOBJECT['CACHE'][$lclass] = array();
  318. }
  319. if (!$obj->get($k, $v)) {
  320. $dor = new DB_DataObject();
  321. $dor->raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
  322. $r = false;
  323. return $r;
  324. }
  325. $_DB_DATAOBJECT['CACHE'][$lclass][$key] = $obj;
  326. return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
  327. }
  328. /**
  329. * Debugger. - use this in your extended classes to output debugging information.
  330. *
  331. * Uses DB_DataObject::DebugLevel(x) to turn it on
  332. *
  333. * @param string $message - message to output
  334. * @param int $logtype - bold at start
  335. * @param int $level - output level
  336. * @return void
  337. * @access public
  338. */
  339. public function debug($message, $logtype = 0, $level = 1)
  340. {
  341. global $_DB_DATAOBJECT;
  342. if (empty($_DB_DATAOBJECT['CONFIG']['debug']) ||
  343. (is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) && $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
  344. return null;
  345. }
  346. // this is a bit flaky due to php's wonderfull class passing around crap..
  347. // but it's about as good as it gets..
  348. $class = (isset($this) && is_a($this, 'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
  349. if (!is_string($message)) {
  350. $message = print_r($message, true);
  351. }
  352. if (!is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) && is_callable($_DB_DATAOBJECT['CONFIG']['debug'])) {
  353. return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
  354. }
  355. if (!ini_get('html_errors')) {
  356. echo "$class : $logtype : $message\n";
  357. flush();
  358. return null;
  359. }
  360. if (!is_string($message)) {
  361. $message = print_r($message, true);
  362. }
  363. $colorize = ($logtype == 'ERROR') ? '<font color="red">' : '<font>';
  364. echo "<code>{$colorize}<B>$class: $logtype:</B> " . nl2br(htmlspecialchars($message)) . "</font></code><BR>\n";
  365. }
  366. /**
  367. * classic factory method for loading a table class
  368. * usage: $do = DB_DataObject::factory('person')
  369. * WARNING - this may emit a include error if the file does not exist..
  370. * use @ to silence it (if you are sure it is acceptable)
  371. * eg. $do = @DB_DataObject::factory('person')
  372. *
  373. * table name can bedatabasename/table
  374. * - and allow modular dataobjects to be written..
  375. * (this also helps proxy creation)
  376. *
  377. * Experimental Support for Multi-Database factory eg. mydatabase.mytable
  378. *
  379. *
  380. * @param string $table tablename (use blank to create a new instance of the same class.)
  381. * @access private
  382. * @return DataObject|PEAR|PEAR_Error|true
  383. */
  384. public static function factory($table = '')
  385. {
  386. global $_DB_DATAOBJECT;
  387. // multi-database support.. - experimental.
  388. $database = '';
  389. if (strpos($table, '/') !== false) {
  390. list($database, $table) = explode('.', $table, 2);
  391. }
  392. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  393. (new DB_DataObject)->_loadConfig();
  394. }
  395. // no configuration available for database
  396. if (!empty($database) && empty($_DB_DATAOBJECT['CONFIG']['database_' . $database])) {
  397. $do = new DB_DataObject();
  398. $do->raiseError(
  399. "unable to find database_{$database} in Configuration, It is required for factory with database",
  400. 0,
  401. PEAR_ERROR_DIE
  402. );
  403. }
  404. /*
  405. if ($table === '') {
  406. if (is_a($this,'DB_DataObject') && strlen($this->tableName())) {
  407. $table = $this->tableName();
  408. } else {
  409. return DB_DataObject::raiseError(
  410. "factory did not recieve a table name",
  411. DB_DATAOBJECT_ERROR_INVALIDARGS);
  412. }
  413. }
  414. */
  415. // does this need multi db support??
  416. $cp = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
  417. explode(PATH_SEPARATOR, $_DB_DATAOBJECT['CONFIG']['class_prefix']) : '';
  418. //print_r($cp);
  419. // multiprefix support.
  420. $tbl = preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table));
  421. if (is_array($cp)) {
  422. $class = array();
  423. foreach ($cp as $cpr) {
  424. $ce = substr(phpversion(), 0, 1) > 4 ? class_exists($cpr . $tbl, false) : class_exists($cpr . $tbl);
  425. if ($ce) {
  426. $class = $cpr . $tbl;
  427. break;
  428. }
  429. $class[] = $cpr . $tbl;
  430. }
  431. } else {
  432. $class = $tbl;
  433. $ce = substr(phpversion(), 0, 1) > 4 ? class_exists($class, false) : class_exists($class);
  434. }
  435. $rclass = $ce ? $class : (new DB_DataObject)->_autoloadClass($class, $table);
  436. // proxy = full|light
  437. if (!$rclass && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) {
  438. (new DB_DataObject)->debug("FAILED TO Autoload $database.$table - using proxy.", "FACTORY", 1);
  439. $proxyMethod = 'getProxy' . $_DB_DATAOBJECT['CONFIG']['proxy'];
  440. // if you have loaded (some other way) - dont try and load it again..
  441. class_exists('DB_DataObject_Generator') ? '' :
  442. //require_once 'DB/DataObject/Generator.php';
  443. require_once 'Generator.php';
  444. $d = new DB_DataObject;
  445. $d->__table = $table;
  446. $ret = $d->_connect();
  447. if (is_object($ret) && is_a($ret, 'PEAR_Error')) {
  448. return $ret;
  449. }
  450. $x = new DB_DataObject_Generator;
  451. return $x->$proxyMethod($d->_database, $table);
  452. }
  453. if (!$rclass || !class_exists($rclass)) {
  454. $dor = new DB_DataObject();
  455. return $dor->raiseError(
  456. "factory could not find class " .
  457. (is_array($class) ? implode(PATH_SEPARATOR, $class) : $class) .
  458. "from $table",
  459. DB_DATAOBJECT_ERROR_INVALIDCONFIG
  460. );
  461. }
  462. $ret = new $rclass();
  463. if (!empty($database)) {
  464. (new DB_DataObject)->debug("Setting database to $database", "FACTORY", 1);
  465. $ret->database($database);
  466. }
  467. return $ret;
  468. }
  469. /**
  470. * Default error handling is to create a pear error, but never return it.
  471. * if you need to handle errors you should look at setting the PEAR_Error callback
  472. * this is due to the fact it would wreck havoc on the internal methods!
  473. *
  474. * @param int $message message
  475. * @param int $type type
  476. * @param int $behaviour behaviour (die or continue!);
  477. * @access public
  478. * @return error|int|object
  479. */
  480. public function raiseError($message, $type = null, $behaviour = null)
  481. {
  482. global $_DB_DATAOBJECT;
  483. if ($behaviour == PEAR_ERROR_DIE && !empty($_DB_DATAOBJECT['CONFIG']['dont_die'])) {
  484. $behaviour = null;
  485. }
  486. $error = &(new PEAR)->getStaticProperty('DB_DataObject', 'lastError');
  487. // no checks for production here?....... - we log errors before we throw them.
  488. DB_DataObject::debug($message, 'ERROR', 1);
  489. if ((new PEAR)->isError($message)) {
  490. $error = $message;
  491. } else {
  492. //require_once 'DB/DataObject/Error.php';
  493. require_once 'Error.php';
  494. $dor = new PEAR();
  495. $error = $dor->raiseError(
  496. $message,
  497. $type,
  498. $behaviour,
  499. $opts = null,
  500. $userinfo = null,
  501. 'DB_DataObject_Error'
  502. );
  503. }
  504. // this will never work totally with PHP's object model.
  505. // as this is passed on static calls (like staticGet in our case)
  506. $_DB_DATAOBJECT['LASTERROR'] = $error;
  507. if (isset($this) && is_object($this) && is_subclass_of($this, 'db_dataobject')) {
  508. $this->_lastError = $error;
  509. }
  510. return $error;
  511. }
  512. /**
  513. * autoload Class
  514. *
  515. * @param string|array $class Class
  516. * @param bool $table Table trying to load.
  517. * @return string classname on Success
  518. * @access private
  519. */
  520. public function _autoloadClass($class, $table = false)
  521. {
  522. global $_DB_DATAOBJECT;
  523. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  524. DB_DataObject::_loadConfig();
  525. }
  526. $class_prefix = empty($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
  527. '' : $_DB_DATAOBJECT['CONFIG']['class_prefix'];
  528. $table = $table ? $table : substr($class, strlen($class_prefix));
  529. // only include the file if it exists - and barf badly if it has parse errors :)
  530. if (!empty($_DB_DATAOBJECT['CONFIG']['proxy']) || empty($_DB_DATAOBJECT['CONFIG']['class_location'])) {
  531. return false;
  532. }
  533. // support for:
  534. // class_location = mydir/ => maps to mydir/Tablename.php
  535. // class_location = mydir/myfile_%s.php => maps to mydir/myfile_Tablename
  536. // with directory sepr
  537. // class_location = mydir/:mydir2/: => tries all of thes locations.
  538. $cl = $_DB_DATAOBJECT['CONFIG']['class_location'];
  539. switch (true) {
  540. case (strpos($cl, '%s') !== false):
  541. $file = sprintf($cl, preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table)));
  542. break;
  543. case (strpos($cl, PATH_SEPARATOR) !== false):
  544. $file = array();
  545. foreach (explode(PATH_SEPARATOR, $cl) as $p) {
  546. $file[] = $p . '/' . preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table)) . ".php";
  547. }
  548. break;
  549. default:
  550. $file = $cl . '/' . preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table)) . ".php";
  551. break;
  552. }
  553. $cls = is_array($class) ? $class : array($class);
  554. if (is_array($file) || !file_exists($file)) {
  555. $found = false;
  556. $file = is_array($file) ? $file : array($file);
  557. $search = implode(PATH_SEPARATOR, $file);
  558. foreach ($file as $f) {
  559. foreach (explode(PATH_SEPARATOR, '' . PATH_SEPARATOR . ini_get('include_path')) as $p) {
  560. $ff = empty($p) ? $f : "$p/$f";
  561. if (file_exists($ff)) {
  562. $file = $ff;
  563. $found = true;
  564. break;
  565. }
  566. }
  567. if ($found) {
  568. break;
  569. }
  570. }
  571. if (!$found) {
  572. $dor = new DB_DataObject();
  573. $dor->raiseError(
  574. "autoload:Could not find class " . implode(',', $cls) .
  575. " using class_location value :" . $search .
  576. " using include_path value :" . ini_get('include_path'),
  577. DB_DATAOBJECT_ERROR_INVALIDCONFIG
  578. );
  579. return false;
  580. }
  581. }
  582. include_once $file;
  583. $ce = false;
  584. foreach ($cls as $c) {
  585. $ce = substr(phpversion(), 0, 1) > 4 ? class_exists($c, false) : class_exists($c);
  586. if ($ce) {
  587. $class = $c;
  588. break;
  589. }
  590. }
  591. if (!$ce) {
  592. $dor = new DB_DataObject();
  593. $dor->raiseError(
  594. "autoload:Could not autoload " . implode(',', $cls),
  595. DB_DATAOBJECT_ERROR_INVALIDCONFIG
  596. );
  597. return false;
  598. }
  599. return $class;
  600. }
  601. /**
  602. * connects to the database
  603. *
  604. *
  605. * TODO: tidy this up - This has grown to support a number of connection options like
  606. * a) dynamic changing of ini file to change which database to connect to
  607. * b) multi data via the table_{$table} = dsn ini option
  608. * c) session based storage.
  609. *
  610. * @access private
  611. * @return error|PEAR|true
  612. */
  613. public function _connect()
  614. {
  615. global $_DB_DATAOBJECT;
  616. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  617. $this->_loadConfig();
  618. }
  619. // Set database driver for reference
  620. $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
  621. 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
  622. // is it already connected ?
  623. if ($this->_database_dsn_md5 && !empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
  624. // connection is an error...
  625. if ((new PEAR)->isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
  626. return $this->raiseError(
  627. $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
  628. $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code,
  629. PEAR_ERROR_DIE
  630. );
  631. }
  632. if (empty($this->_database)) {
  633. $this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
  634. $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
  635. $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
  636. ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
  637. : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
  638. if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
  639. && is_file($this->_database)) {
  640. $this->_database = basename($this->_database);
  641. }
  642. if ($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'ibase') {
  643. $this->_database = substr(basename($this->_database), 0, -4);
  644. }
  645. }
  646. // theoretically we have a md5, it's listed in connections and it's not an error.
  647. // so everything is ok!
  648. return true;
  649. }
  650. // it's not currently connected!
  651. // try and work out what to use for the dsn !
  652. $options = $_DB_DATAOBJECT['CONFIG'];
  653. // if the databse dsn dis defined in the object..
  654. $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
  655. if (!$dsn) {
  656. if (!$this->_database && !strlen($this->tableName())) {
  657. $this->_database = isset($options["table_{$this->tableName()}"]) ? $options["table_{$this->tableName()}"] : null;
  658. }
  659. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  660. $this->debug("Checking for database specific ini ('{$this->_database}') : database_{$this->_database} in options", "CONNECT");
  661. }
  662. if ($this->_database && !empty($options["database_{$this->_database}"])) {
  663. $dsn = $options["database_{$this->_database}"];
  664. } elseif (!empty($options['database'])) {
  665. $dsn = $options['database'];
  666. }
  667. }
  668. // if still no database...
  669. if (!$dsn) {
  670. return $this->raiseError(
  671. "No database name / dsn found anywhere",
  672. DB_DATAOBJECT_ERROR_INVALIDCONFIG,
  673. PEAR_ERROR_DIE
  674. );
  675. }
  676. if (is_string($dsn)) {
  677. $this->_database_dsn_md5 = md5($dsn);
  678. } else {
  679. /// support array based dsn's
  680. $this->_database_dsn_md5 = md5(serialize($dsn));
  681. }
  682. if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
  683. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  684. $this->debug("USING CACHED CONNECTION", "CONNECT", 3);
  685. }
  686. if (!$this->_database) {
  687. $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
  688. $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
  689. ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
  690. : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
  691. if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
  692. && is_file($this->_database)) {
  693. $this->_database = basename($this->_database);
  694. }
  695. }
  696. return true;
  697. }
  698. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  699. $this->debug("NEW CONNECTION TP DATABASE :" . $this->_database, "CONNECT", 3);
  700. /* actualy make a connection */
  701. $this->debug(print_r($dsn, true) . " {$this->_database_dsn_md5}", "CONNECT", 3);
  702. }
  703. // Note this is verbose deliberatly!
  704. if ($db_driver == 'DB') {
  705. /* PEAR DB connect */
  706. // this allows the setings of compatibility on DB
  707. $db_options = (new PEAR)->getStaticProperty('DB', 'options');
  708. require_once 'DB.php';
  709. if ($db_options) {
  710. $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn, $db_options);
  711. } else {
  712. $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn);
  713. }
  714. } else {
  715. /* assumption is MDB2 */
  716. require_once 'MDB2.php';
  717. // this allows the setings of compatibility on MDB2
  718. $db_options = (new PEAR)->getStaticProperty('MDB2', 'options');
  719. $db_options = is_array($db_options) ? $db_options : array();
  720. $db_options['portability'] = isset($db_options['portability'])
  721. ? $db_options['portability'] : MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE;
  722. $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = MDB2::connect($dsn, $db_options);
  723. }
  724. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  725. $this->debug(print_r($_DB_DATAOBJECT['CONNECTIONS'], true), "CONNECT", 5);
  726. }
  727. if ((new PEAR)->isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
  728. $this->debug($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->toString(), "CONNECT FAILED", 5);
  729. return $this->raiseError(
  730. "Connect failed, turn on debugging to 5 see why",
  731. $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code,
  732. PEAR_ERROR_DIE
  733. );
  734. }
  735. if (empty($this->_database)) {
  736. $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
  737. $this->_database = ($db_driver != 'DB' && $hasGetDatabase)
  738. ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase()
  739. : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
  740. if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite')
  741. && is_file($this->_database)) {
  742. $this->_database = basename($this->_database);
  743. }
  744. }
  745. // Oracle need to optimize for portibility - not sure exactly what this does though :)
  746. return true;
  747. }
  748. /**
  749. * Return or assign the name of the current table
  750. *
  751. *
  752. * @param string optinal table name to set
  753. * @access public
  754. * @return string The name of the current table
  755. */
  756. public function tableName()
  757. {
  758. global $_DB_DATAOBJECT;
  759. $args = func_get_args();
  760. if (count($args)) {
  761. $this->__table = $args[0];
  762. }
  763. if (empty($this->__table)) {
  764. return '';
  765. }
  766. if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
  767. return strtolower($this->__table);
  768. }
  769. return $this->__table;
  770. }
  771. /**
  772. * Get a result using key, value.
  773. *
  774. * for example
  775. * $object->get("ID",1234);
  776. * Returns Number of rows located (usually 1) for success,
  777. * and puts all the table columns into this classes variables
  778. *
  779. * see the fetch example on how to extend this.
  780. *
  781. * if no value is entered, it is assumed that $key is a value
  782. * and get will then use the first key in keys()
  783. * to obtain the key.
  784. *
  785. * @param string $k column
  786. * @param string $v value
  787. * @access public
  788. * @return int No. of rows
  789. */
  790. public function get($k = null, $v = null)
  791. {
  792. global $_DB_DATAOBJECT;
  793. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  794. DB_DataObject::_loadConfig();
  795. }
  796. $keys = array();
  797. if ($v === null) {
  798. $v = $k;
  799. $keys = $this->keys();
  800. if (!$keys) {
  801. $this->raiseError("No Keys available for {$this->tableName()}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
  802. return false;
  803. }
  804. $k = $keys[0];
  805. }
  806. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  807. $this->debug("$k $v " . print_r($keys, true), "GET");
  808. }
  809. if ($v === null) {
  810. $this->raiseError("No Value specified for get", DB_DATAOBJECT_ERROR_INVALIDARGS);
  811. return false;
  812. }
  813. $this->$k = $v;
  814. return $this->find(1);
  815. }
  816. /**
  817. * get/set an array of table primary keys
  818. *
  819. * set usage: $do->keys('id','code');
  820. *
  821. * This is defined in the table definition if it gets it wrong,
  822. * or you do not want to use ini tables, you can override this.
  823. * @param string optional set the key
  824. * @param * optional set more keys
  825. * @access public
  826. * @return array
  827. */
  828. public function keys()
  829. {
  830. // for temporary storage of database fields..
  831. // note this is not declared as we dont want to bloat the print_r output
  832. $args = func_get_args();
  833. if (count($args)) {
  834. $this->_database_keys = $args;
  835. }
  836. if (isset($this->_database_keys)) {
  837. return $this->_database_keys;
  838. }
  839. global $_DB_DATAOBJECT;
  840. if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
  841. $this->_connect();
  842. }
  843. if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName() . "__keys"])) {
  844. return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName() . "__keys"]);
  845. }
  846. $this->databaseStructure();
  847. if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName() . "__keys"])) {
  848. return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName() . "__keys"]);
  849. }
  850. return array();
  851. }
  852. /**
  853. * Autoload or manually load the table definitions
  854. *
  855. *
  856. * usage :
  857. * DB_DataObject::databaseStructure( 'databasename',
  858. * parse_ini_file('mydb.ini',true),
  859. * parse_ini_file('mydb.link.ini',true));
  860. *
  861. * obviously you dont have to use ini files.. (just return array similar to ini files..)
  862. *
  863. * It should append to the table structure array
  864. *
  865. *
  866. * @param optional string name of database to assign / read
  867. * @param optional array structure of database, and keys
  868. * @param optional array table links
  869. *
  870. * @access public
  871. * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
  872. * or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
  873. */
  874. public function databaseStructure()
  875. {
  876. global $_DB_DATAOBJECT;
  877. // Assignment code
  878. if ($args = func_get_args()) {
  879. if (count($args) == 1) {
  880. // this returns all the tables and their structure..
  881. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  882. $this->debug("Loading Generator as databaseStructure called with args", 1);
  883. }
  884. $x = new DB_DataObject;
  885. $x->_database = $args[0];
  886. $this->_connect();
  887. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  888. $tables = $DB->getListOf('tables');
  889. class_exists('DB_DataObject_Generator') ? '' :
  890. //require_once 'DB/DataObject/Generator.php';
  891. require_once 'Generator.php';
  892. foreach ($tables as $table) {
  893. $y = new DB_DataObject_Generator;
  894. $y->fillTableSchema($x->_database, $table);
  895. }
  896. return $_DB_DATAOBJECT['INI'][$x->_database];
  897. } else {
  898. $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
  899. $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
  900. if (isset($args[1])) {
  901. $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
  902. $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
  903. }
  904. return true;
  905. }
  906. }
  907. if (!$this->_database) {
  908. $this->_connect();
  909. }
  910. // if this table is already loaded this table..
  911. if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
  912. return true;
  913. }
  914. // initialize the ini data.. if empt..
  915. if (empty($_DB_DATAOBJECT['INI'][$this->_database])) {
  916. $_DB_DATAOBJECT['INI'][$this->_database] = array();
  917. }
  918. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  919. DB_DataObject::_loadConfig();
  920. }
  921. // we do not have the data for this table yet...
  922. // if we are configured to use the proxy..
  923. if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
  924. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  925. $this->debug("Loading Generator to fetch Schema", 1);
  926. }
  927. class_exists('DB_DataObject_Generator') ? '' :
  928. //require_once 'DB/DataObject/Generator.php';
  929. require_once 'Generator.php';
  930. $x = new DB_DataObject_Generator;
  931. $x->fillTableSchema($this->_database, $this->tableName());
  932. return true;
  933. }
  934. // if you supply this with arguments, then it will take those
  935. // as the database and links array...
  936. $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
  937. array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
  938. array();
  939. if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
  940. $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
  941. $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
  942. explode(PATH_SEPARATOR, $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
  943. }
  944. $_DB_DATAOBJECT['INI'][$this->_database] = array();
  945. foreach ($schemas as $ini) {
  946. if (file_exists($ini) && is_file($ini)) {
  947. $_DB_DATAOBJECT['INI'][$this->_database] = array_merge(
  948. $_DB_DATAOBJECT['INI'][$this->_database],
  949. parse_ini_file($ini, true)
  950. );
  951. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  952. if (!is_readable($ini)) {
  953. $this->debug("ini file is not readable: $ini", "databaseStructure", 1);
  954. } else {
  955. $this->debug("Loaded ini file: $ini", "databaseStructure", 1);
  956. }
  957. }
  958. } else {
  959. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  960. $this->debug("Missing ini file: $ini", "databaseStructure", 1);
  961. }
  962. }
  963. }
  964. // are table name lowecased..
  965. if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
  966. foreach ($_DB_DATAOBJECT['INI'][$this->_database] as $k => $v) {
  967. // results in duplicate cols.. but not a big issue..
  968. $_DB_DATAOBJECT['INI'][$this->_database][strtolower($k)] = $v;
  969. }
  970. }
  971. // now have we loaded the structure..
  972. if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
  973. return true;
  974. }
  975. // - if not try building it..
  976. if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
  977. class_exists('DB_DataObject_Generator') ? '' :
  978. //require_once 'DB/DataObject/Generator.php';
  979. require_once 'Generator.php';
  980. $x = new DB_DataObject_Generator;
  981. $x->fillTableSchema($this->_database, $this->tableName());
  982. // should this fail!!!???
  983. return true;
  984. }
  985. $this->debug("Cant find database schema: {$this->_database}/{$this->tableName()} \n" .
  986. "in links file data: " . print_r($_DB_DATAOBJECT['INI'], true), "databaseStructure", 5);
  987. // we have to die here!! - it causes chaos if we dont (including looping forever!)
  988. $this->raiseError("Unable to load schema for database and table (turn debugging up to 5 for full error message)", DB_DATAOBJECT_ERROR_INVALIDARGS, PEAR_ERROR_DIE);
  989. return false;
  990. }
  991. /**
  992. * find results, either normal or crosstable
  993. *
  994. * for example
  995. *
  996. * $object = new mytable();
  997. * $object->ID = 1;
  998. * $object->find();
  999. *
  1000. *
  1001. * will set $object->N to number of rows, and expects next command to fetch rows
  1002. * will return $object->N
  1003. *
  1004. * if an error occurs $object->N will be set to false and return value will also be false;
  1005. * if numRows is not supported it will
  1006. *
  1007. *
  1008. * @param boolean $n Fetch first result
  1009. * @access public
  1010. * @return mixed (number of rows returned, or true if numRows fetching is not supported)
  1011. */
  1012. public function find($n = false)
  1013. {
  1014. global $_DB_DATAOBJECT;
  1015. if ($this->_query === false) {
  1016. $this->raiseError(
  1017. "You cannot do two queries on the same object (copy it before finding)",
  1018. DB_DATAOBJECT_ERROR_INVALIDARGS
  1019. );
  1020. return false;
  1021. }
  1022. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  1023. DB_DataObject::_loadConfig();
  1024. }
  1025. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1026. $this->debug($n, "find", 1);
  1027. }
  1028. if (!strlen($this->tableName())) {
  1029. // xdebug can backtrace this!
  1030. trigger_error("NO \$__table SPECIFIED in class definition", E_USER_ERROR);
  1031. }
  1032. $this->N = 0;
  1033. $query_before = $this->_query;
  1034. $this->_build_condition($this->table());
  1035. $this->_connect();
  1036. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  1037. $sql = $this->_build_select();
  1038. foreach ($this->_query['unions'] as $union_ar) {
  1039. $sql .= $union_ar[1] . $union_ar[0]->_build_select() . " \n";
  1040. }
  1041. $sql .= $this->_query['order_by'] . " \n";
  1042. /* We are checking for method modifyLimitQuery as it is PEAR DB specific */
  1043. if ((!isset($_DB_DATAOBJECT['CONFIG']['db_driver'])) ||
  1044. ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
  1045. /* PEAR DB specific */
  1046. if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
  1047. $sql = $DB->modifyLimitQuery($sql, $this->_query['limit_start'], $this->_query['limit_count']);
  1048. }
  1049. } else {
  1050. /* theoretically MDB2! */
  1051. if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
  1052. $DB->setLimit($this->_query['limit_count'], $this->_query['limit_start']);
  1053. }
  1054. }
  1055. $err = $this->_query($sql);
  1056. if (is_a($err, 'PEAR_Error')) {
  1057. return false;
  1058. }
  1059. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1060. $this->debug("CHECK autofetchd $n", "find", 1);
  1061. }
  1062. // find(true)
  1063. $ret = $this->N;
  1064. if (!$ret && !empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
  1065. // clear up memory if nothing found!?
  1066. unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
  1067. }
  1068. if ($n && $this->N > 0) {
  1069. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1070. $this->debug("ABOUT TO AUTOFETCH", "find", 1);
  1071. }
  1072. $fs = $this->fetch();
  1073. // if fetch returns false (eg. failed), then the backend doesnt support numRows (eg. ret=true)
  1074. // - hence find() also returns false..
  1075. $ret = ($ret === true) ? $fs : $ret;
  1076. }
  1077. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1078. $this->debug("DONE", "find", 1);
  1079. }
  1080. $this->_query = $query_before;
  1081. return $ret;
  1082. }
  1083. /* ==================================================== */
  1084. /* Major Private Vars */
  1085. /* ==================================================== */
  1086. /**
  1087. * Builds the WHERE based on the values of of this object
  1088. *
  1089. * @param mixed $keys
  1090. * @param array $filter (used by update to only uses keys in this filter list).
  1091. * @param array $negative_filter (used by delete to prevent deleting using the keys mentioned..)
  1092. * @access private
  1093. * @return string
  1094. */
  1095. public function _build_condition($keys, $filter = array(), $negative_filter = array())
  1096. {
  1097. global $_DB_DATAOBJECT;
  1098. $this->_connect();
  1099. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  1100. $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
  1101. $options = $_DB_DATAOBJECT['CONFIG'];
  1102. // if we dont have query vars.. - reset them.
  1103. if ($this->_query === false) {
  1104. $x = new DB_DataObject;
  1105. $this->_query = $x->_query;
  1106. }
  1107. foreach ($keys as $k => $v) {
  1108. // index keys is an indexed array
  1109. /* these filter checks are a bit suspicious..
  1110. - need to check that update really wants to work this way */
  1111. if ($filter) {
  1112. if (!in_array($k, $filter)) {
  1113. continue;
  1114. }
  1115. }
  1116. if ($negative_filter) {
  1117. if (in_array($k, $negative_filter)) {
  1118. continue;
  1119. }
  1120. }
  1121. if (!isset($this->$k)) {
  1122. continue;
  1123. }
  1124. $kSql = $quoteIdentifiers
  1125. ? ($DB->quoteIdentifier($this->tableName()) . '.' . $DB->quoteIdentifier($k))
  1126. : "{$this->tableName()}.{$k}";
  1127. if (is_object($this->$k) && is_a($this->$k, 'DB_DataObject_Cast')) {
  1128. $dbtype = $DB->dsn["phptype"];
  1129. $value = $this->$k->toString($v, $DB);
  1130. if ((new PEAR)->isError($value)) {
  1131. $this->raiseError($value->getMessage(), DB_DATAOBJECT_ERROR_INVALIDARG);
  1132. return false;
  1133. }
  1134. if ((strtolower($value) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
  1135. $this->whereAdd(" $kSql IS NULL");
  1136. continue;
  1137. }
  1138. $this->whereAdd(" $kSql = $value");
  1139. continue;
  1140. }
  1141. if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this, $k)) {
  1142. $this->whereAdd(" $kSql IS NULL");
  1143. continue;
  1144. }
  1145. if ($v & DB_DATAOBJECT_STR) {
  1146. $this->whereAdd(" $kSql = " . $this->_quote((string)(
  1147. ($v & DB_DATAOBJECT_BOOL) ?
  1148. // this is thanks to the braindead idea of postgres to
  1149. // use t/f for boolean.
  1150. (($this->$k === 'f') ? 0 : (int)(bool)$this->$k) :
  1151. $this->$k
  1152. )));
  1153. continue;
  1154. }
  1155. if (is_numeric($this->$k)) {
  1156. $this->whereAdd(" $kSql = {$this->$k}");
  1157. continue;
  1158. }
  1159. /* this is probably an error condition! */
  1160. $this->whereAdd(" $kSql = " . intval($this->$k));
  1161. }
  1162. return "";
  1163. }
  1164. /**
  1165. * Adds a condition to the WHERE statement, defaults to AND
  1166. *
  1167. * $object->whereAdd(); //reset or cleaer ewhwer
  1168. * $object->whereAdd("ID > 20");
  1169. * $object->whereAdd("age > 20","OR");
  1170. *
  1171. * @param bool $cond condition
  1172. * @param string $logic optional logic "OR" (defaults to "AND")
  1173. * @return string|PEAR::Error - previous condition or Error when invalid args found
  1174. * @access public
  1175. */
  1176. public function whereAdd($cond = false, $logic = 'AND')
  1177. {
  1178. // for PHP5.2.3 - there is a bug with setting array properties of an object.
  1179. $_query = $this->_query;
  1180. if (!isset($this->_query) || ($_query === false)) {
  1181. return $this->raiseError(
  1182. "You cannot do two queries on the same object (clone it before finding)",
  1183. DB_DATAOBJECT_ERROR_INVALIDARGS
  1184. );
  1185. }
  1186. if ($cond === false) {
  1187. $r = $this->_query['condition'];
  1188. $_query['condition'] = '';
  1189. $this->_query = $_query;
  1190. return preg_replace('/^\s+WHERE\s+/', '', $r);
  1191. }
  1192. // check input...= 0 or ' ' == error!
  1193. if (!trim($cond)) {
  1194. return $this->raiseError("WhereAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
  1195. }
  1196. $r = $_query['condition'];
  1197. if ($_query['condition']) {
  1198. $_query['condition'] .= " {$logic} ( {$cond} )";
  1199. $this->_query = $_query;
  1200. return $r;
  1201. }
  1202. $_query['condition'] = " WHERE ( {$cond} ) ";
  1203. $this->_query = $_query;
  1204. return $r;
  1205. }
  1206. /**
  1207. * Evaluate whether or not a value is set to null, taking the 'disable_null_strings' option into account.
  1208. * If the value is a string set to "null" and the "disable_null_strings" option is not set to
  1209. * true, then the value is considered to be null.
  1210. * If the value is actually a PHP NULL value, and "disable_null_strings" has been set to
  1211. * the value "full", then it will also be considered null. - this can not differenticate between not set
  1212. *
  1213. *
  1214. * @param object|array $obj_or_ar
  1215. * @param string|false $prop prperty
  1216. * @access private
  1217. * @return bool object
  1218. */
  1219. public function _is_null($obj_or_ar, $prop)
  1220. {
  1221. global $_DB_DATAOBJECT;
  1222. $isset = $prop === false ? isset($obj_or_ar) :
  1223. (is_array($obj_or_ar) ? isset($obj_or_ar[$prop]) : isset($obj_or_ar->$prop));
  1224. $value = $isset ?
  1225. ($prop === false ? $obj_or_ar :
  1226. (is_array($obj_or_ar) ? $obj_or_ar[$prop] : $obj_or_ar->$prop))
  1227. : null;
  1228. $options = $_DB_DATAOBJECT['CONFIG'];
  1229. $null_strings = !isset($options['disable_null_strings'])
  1230. || $options['disable_null_strings'] === false;
  1231. $crazy_null = isset($options['disable_null_strings'])
  1232. && is_string($options['disable_null_strings'])
  1233. && strtolower($options['disable_null_strings'] === 'full');
  1234. if ($null_strings && $isset && is_string($value) && (strtolower($value) === 'null')) {
  1235. return true;
  1236. }
  1237. if ($crazy_null && !$isset) {
  1238. return true;
  1239. }
  1240. return false;
  1241. }
  1242. /**
  1243. * backend wrapper for quoting, as MDB2 and DB do it differently...
  1244. *
  1245. * @access private
  1246. * @param $str
  1247. * @return string quoted
  1248. */
  1249. public function _quote($str)
  1250. {
  1251. global $_DB_DATAOBJECT;
  1252. return (empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
  1253. ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB'))
  1254. ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quoteSmart($str)
  1255. : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quote($str);
  1256. }
  1257. /**
  1258. * get/set an associative array of table columns
  1259. *
  1260. * @access public
  1261. * @param array key=>type array
  1262. * @return array (associative)
  1263. */
  1264. public function table()
  1265. {
  1266. // for temporary storage of database fields..
  1267. // note this is not declared as we dont want to bloat the print_r output
  1268. $args = func_get_args();
  1269. if (count($args)) {
  1270. $this->_database_fields = $args[0];
  1271. }
  1272. if (isset($this->_database_fields)) {
  1273. return $this->_database_fields;
  1274. }
  1275. global $_DB_DATAOBJECT;
  1276. if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
  1277. $this->_connect();
  1278. }
  1279. if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
  1280. return $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()];
  1281. }
  1282. $this->databaseStructure();
  1283. $ret = array();
  1284. if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
  1285. $ret = $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()];
  1286. }
  1287. return $ret;
  1288. }
  1289. /**
  1290. * build the basic select query.
  1291. *
  1292. * @access private
  1293. */
  1294. public function _build_select()
  1295. {
  1296. global $_DB_DATAOBJECT;
  1297. $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
  1298. if ($quoteIdentifiers) {
  1299. $this->_connect();
  1300. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  1301. }
  1302. $tn = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
  1303. if (!empty($this->_query['derive_table']) && !empty($this->_query['derive_select'])) {
  1304. // this is a derived select..
  1305. // not much support in the api yet..
  1306. $sql = 'SELECT ' .
  1307. $this->_query['derive_select']
  1308. . ' FROM ( SELECT' .
  1309. $this->_query['data_select'] . " \n" .
  1310. " FROM $tn " . $this->_query['useindex'] . " \n" .
  1311. $this->_join . " \n" .
  1312. $this->_query['condition'] . " \n" .
  1313. $this->_query['group_by'] . " \n" .
  1314. $this->_query['having'] . " \n" .
  1315. ') ' . $this->_query['derive_table'];
  1316. return $sql;
  1317. }
  1318. $sql = 'SELECT ' .
  1319. $this->_query['data_select'] . " \n" .
  1320. " FROM $tn " . $this->_query['useindex'] . " \n" .
  1321. $this->_join . " \n" .
  1322. $this->_query['condition'] . " \n" .
  1323. $this->_query['group_by'] . " \n" .
  1324. $this->_query['having'] . " \n";
  1325. return $sql;
  1326. }
  1327. /* ============================================================== */
  1328. /* Table definition layer (started of very private but 'came out'*/
  1329. /* ============================================================== */
  1330. /**
  1331. * sends query to database - this is the private one that must work
  1332. * - internal functions use this rather than $this->query()
  1333. *
  1334. * @param string $string
  1335. * @access private
  1336. * @return mixed none or PEAR_Error
  1337. */
  1338. public function _query($string)
  1339. {
  1340. global $_DB_DATAOBJECT;
  1341. $this->_connect();
  1342. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  1343. $options = $_DB_DATAOBJECT['CONFIG'];
  1344. $_DB_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ?
  1345. 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
  1346. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1347. $this->debug($string, $log = "QUERY");
  1348. }
  1349. if (
  1350. strtoupper($string) == 'BEGIN' ||
  1351. strtoupper($string) == 'START TRANSACTION'
  1352. ) {
  1353. if ($_DB_driver == 'DB') {
  1354. $DB->autoCommit(false);
  1355. $DB->simpleQuery('BEGIN');
  1356. } else {
  1357. $DB->beginTransaction();
  1358. }
  1359. return true;
  1360. }
  1361. if (strtoupper($string) == 'COMMIT') {
  1362. $res = $DB->commit();
  1363. if ($_DB_driver == 'DB') {
  1364. $DB->autoCommit(true);
  1365. }
  1366. return $res;
  1367. }
  1368. if (strtoupper($string) == 'ROLLBACK') {
  1369. $DB->rollback();
  1370. if ($_DB_driver == 'DB') {
  1371. $DB->autoCommit(true);
  1372. }
  1373. return true;
  1374. }
  1375. if (!empty($options['debug_ignore_updates']) &&
  1376. (strtolower(substr(trim($string), 0, 6)) != 'select') &&
  1377. (strtolower(substr(trim($string), 0, 4)) != 'show') &&
  1378. (strtolower(substr(trim($string), 0, 8)) != 'describe')) {
  1379. $this->debug('Disabling Update as you are in debug mode');
  1380. return $this->raiseError("Disabling Update as you are in debug mode", null);
  1381. }
  1382. //if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 1) {
  1383. // this will only work when PEAR:DB supports it.
  1384. //$this->debug($DB->getAll('explain ' .$string,DB_DATAOBJECT_FETCHMODE_ASSOC), $log="sql",2);
  1385. //}
  1386. // some sim
  1387. $t = explode(' ', microtime());
  1388. $_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0] + $t[1];
  1389. for ($tries = 0; $tries < 3; $tries++) {
  1390. if ($_DB_driver == 'DB') {
  1391. $result = $DB->query($string);
  1392. } else {
  1393. switch (strtolower(substr(trim($string), 0, 6))) {
  1394. case 'insert':
  1395. case 'update':
  1396. case 'delete':
  1397. $result = $DB->exec($string);
  1398. break;
  1399. default:
  1400. $result = $DB->query($string);
  1401. break;
  1402. }
  1403. }
  1404. // see if we got a failure.. - try again a few times..
  1405. if (!is_object($result) || !is_a($result, 'PEAR_Error')) {
  1406. break;
  1407. }
  1408. if ($result->getCode() != -14) { // *DB_ERROR_NODBSELECTED
  1409. break; // not a connection error..
  1410. }
  1411. sleep(1); // wait before retyring..
  1412. $DB->connect($DB->dsn);
  1413. }
  1414. if (is_object($result) && is_a($result, 'PEAR_Error')) {
  1415. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1416. $this->debug($result->toString(), "Query Error", 1);
  1417. }
  1418. $this->N = false;
  1419. return $this->raiseError($result);
  1420. }
  1421. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1422. $t = explode(' ', microtime());
  1423. $_DB_DATAOBJECT['QUERYENDTIME'] = $t[0] + $t[1];
  1424. $this->debug('QUERY DONE IN ' . ($t[0] + $t[1] - $time) . " seconds", 'query', 1);
  1425. }
  1426. switch (strtolower(substr(trim($string), 0, 6))) {
  1427. case 'insert':
  1428. case 'update':
  1429. case 'delete':
  1430. if ($_DB_driver == 'DB') {
  1431. // pear DB specific
  1432. return $DB->affectedRows();
  1433. }
  1434. return $result;
  1435. }
  1436. if (is_object($result)) {
  1437. // lets hope that copying the result object is OK!
  1438. $_DB_resultid = $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ']++;
  1439. $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result;
  1440. $this->_DB_resultid = $_DB_resultid;
  1441. }
  1442. $this->N = 0;
  1443. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1444. $this->debug(serialize($result), 'RESULT', 5);
  1445. }
  1446. if (method_exists($result, 'numRows')) {
  1447. if ($_DB_driver == 'DB') {
  1448. $DB->expectError(DB_ERROR_UNSUPPORTED);
  1449. } else {
  1450. $DB->expectError(MDB2_ERROR_UNSUPPORTED);
  1451. }
  1452. $this->N = $result->numRows();
  1453. //var_dump($this->N);
  1454. if (is_object($this->N) && is_a($this->N, 'PEAR_Error')) {
  1455. $this->N = true;
  1456. }
  1457. $DB->popExpect();
  1458. }
  1459. return null;
  1460. }
  1461. /**
  1462. * fetches next row into this objects var's
  1463. *
  1464. * returns 1 on success 0 on failure
  1465. *
  1466. *
  1467. *
  1468. * Example
  1469. * $object = new mytable();
  1470. * $object->name = "fred";
  1471. * $object->find();
  1472. * $store = array();
  1473. * while ($object->fetch()) {
  1474. * echo $this->ID;
  1475. * $store[] = $object; // builds an array of object lines.
  1476. * }
  1477. *
  1478. * to add features to a fetch
  1479. * function fetch () {
  1480. * $ret = parent::fetch();
  1481. * $this->date_formated = date('dmY',$this->date);
  1482. * return $ret;
  1483. * }
  1484. *
  1485. * @access public
  1486. * @return boolean on success
  1487. */
  1488. public function fetch()
  1489. {
  1490. global $_DB_DATAOBJECT;
  1491. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  1492. DB_DataObject::_loadConfig();
  1493. }
  1494. if (empty($this->N)) {
  1495. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1496. $this->debug("No data returned from FIND (eg. N is 0)", "FETCH", 3);
  1497. }
  1498. return false;
  1499. }
  1500. if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) ||
  1501. !is_object($result = $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
  1502. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1503. $this->debug('fetched on object after fetch completed (no results found)');
  1504. }
  1505. return false;
  1506. }
  1507. $array = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ASSOC);
  1508. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1509. $this->debug(serialize($array), "FETCH");
  1510. }
  1511. // fetched after last row..
  1512. if ($array === null) {
  1513. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1514. $t = explode(' ', microtime());
  1515. $this->debug(
  1516. "Last Data Fetch'ed after " .
  1517. ($t[0] + $t[1] - $_DB_DATAOBJECT['QUERYENDTIME']) .
  1518. " seconds",
  1519. "FETCH",
  1520. 1
  1521. );
  1522. }
  1523. // reduce the memory usage a bit... (but leave the id in, so count() works ok on it)
  1524. unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
  1525. // we need to keep a copy of resultfields locally so toArray() still works
  1526. // however we dont want to keep it in the global cache..
  1527. if (!empty($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
  1528. $this->_resultFields = $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid];
  1529. unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
  1530. }
  1531. // this is probably end of data!!
  1532. //DB_DataObject::raiseError("fetch: no data returned", DB_DATAOBJECT_ERROR_NODATA);
  1533. return false;
  1534. }
  1535. // make sure resultFields is always empty..
  1536. $this->_resultFields = false;
  1537. if (!isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
  1538. // note: we dont declare this to keep the print_r size down.
  1539. $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] = array_flip(array_keys($array));
  1540. }
  1541. $replace = array('.', ' ');
  1542. foreach ($array as $k => $v) {
  1543. // use strpos as str_replace is slow.
  1544. $kk = (strpos($k, '.') === false && strpos($k, ' ') === false) ?
  1545. $k : str_replace($replace, '_', $k);
  1546. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1547. $this->debug("$kk = " . $array[$k], "fetchrow LINE", 3);
  1548. }
  1549. $this->$kk = $array[$k];
  1550. }
  1551. // set link flag
  1552. $this->_link_loaded = false;
  1553. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  1554. $this->debug("{$this->tableName()} DONE", "fetchrow", 2);
  1555. }
  1556. if (($this->_query !== false) && empty($_DB_DATAOBJECT['CONFIG']['keep_query_after_fetch'])) {
  1557. $this->_query = false;
  1558. }
  1559. return true;
  1560. }
  1561. /**
  1562. * Get the value of the primary id
  1563. *
  1564. * While I normally use 'id' as the PRIMARY KEY value, some database use
  1565. * {table}_id as the column name.
  1566. *
  1567. * To save a bit of typing,
  1568. *
  1569. * $id = $do->pid();
  1570. *
  1571. * @return bool|the
  1572. */
  1573. public function pid()
  1574. {
  1575. $keys = $this->keys();
  1576. if (!$keys) {
  1577. $this->raiseError(
  1578. "No Keys available for {$this->tableName()}",
  1579. DB_DATAOBJECT_ERROR_INVALIDCONFIG
  1580. );
  1581. return false;
  1582. }
  1583. $k = $keys[0];
  1584. if (empty($this->$k)) { // we do not
  1585. $this->raiseError(
  1586. "pid() called on Object where primary key value not available",
  1587. DB_DATAOBJECT_ERROR_NODATA
  1588. );
  1589. return false;
  1590. }
  1591. return $this->$k;
  1592. }
  1593. /**
  1594. * fetches all results as an array,
  1595. *
  1596. * return format is dependant on args.
  1597. * if selectAdd() has not been called on the object, then it will add the correct columns to the query.
  1598. *
  1599. * A) Array of values (eg. a list of 'id')
  1600. *
  1601. * $x = DB_DataObject::factory('mytable');
  1602. * $x->whereAdd('something = 1')
  1603. * $ar = $x->fetchAll('id');
  1604. * -- returns array(1,2,3,4,5)
  1605. *
  1606. * B) Array of values (not from table)
  1607. *
  1608. * $x = DB_DataObject::factory('mytable');
  1609. * $x->whereAdd('something = 1');
  1610. * $x->selectAdd();
  1611. * $x->selectAdd('distinct(group_id) as group_id');
  1612. * $ar = $x->fetchAll('group_id');
  1613. * -- returns array(1,2,3,4,5)
  1614. * *
  1615. * C) A key=>value associative array
  1616. *
  1617. * $x = DB_DataObject::factory('mytable');
  1618. * $x->whereAdd('something = 1')
  1619. * $ar = $x->fetchAll('id','name');
  1620. * -- returns array(1=>'fred',2=>'blogs',3=> .......
  1621. *
  1622. * D) array of objects
  1623. * $x = DB_DataObject::factory('mytable');
  1624. * $x->whereAdd('something = 1');
  1625. * $ar = $x->fetchAll();
  1626. *
  1627. * E) array of arrays (for example)
  1628. * $x = DB_DataObject::factory('mytable');
  1629. * $x->whereAdd('something = 1');
  1630. * $ar = $x->fetchAll(false,false,'toArray');
  1631. *
  1632. *
  1633. * @param string|false $k key
  1634. * @param string|false $v value
  1635. * @param string|false $method method to call on each result to get array value (eg. 'toArray')
  1636. * @access public
  1637. * @return array format dependant on arguments, may be empty
  1638. */
  1639. public function fetchAll($k = false, $v = false, $method = false)
  1640. {
  1641. // should it even do this!!!?!?
  1642. if ($k !== false &&
  1643. ( // only do this is we have not been explicit..
  1644. empty($this->_query['data_select']) ||
  1645. ($this->_query['data_select'] == '*')
  1646. )
  1647. ) {
  1648. $this->selectAdd();
  1649. $this->selectAdd($k);
  1650. if ($v !== false) {
  1651. $this->selectAdd($v);
  1652. }
  1653. }
  1654. $this->find();
  1655. $ret = array();
  1656. while ($this->fetch()) {
  1657. if ($v !== false) {
  1658. $ret[$this->$k] = $this->$v;
  1659. continue;
  1660. }
  1661. $ret[] = $k === false ?
  1662. ($method == false ? clone($this) : $this->$method())
  1663. : $this->$k;
  1664. }
  1665. return $ret;
  1666. }
  1667. /**
  1668. * Adds a select columns
  1669. *
  1670. * $object->selectAdd(); // resets select to nothing!
  1671. * $object->selectAdd("*"); // default select
  1672. * $object->selectAdd("unixtime(DATE) as udate");
  1673. * $object->selectAdd("DATE");
  1674. *
  1675. * to prepend distict:
  1676. * $object->selectAdd('distinct ' . $object->selectAdd());
  1677. *
  1678. * @param string $k
  1679. * @access public
  1680. * @return mixed null or old string if you reset it.
  1681. */
  1682. public function selectAdd($k = null)
  1683. {
  1684. if ($this->_query === false) {
  1685. $this->raiseError(
  1686. "You cannot do two queries on the same object (copy it before finding)",
  1687. DB_DATAOBJECT_ERROR_INVALIDARGS
  1688. );
  1689. return false;
  1690. }
  1691. if ($k === null) {
  1692. $old = $this->_query['data_select'];
  1693. $this->_query['data_select'] = '';
  1694. return $old;
  1695. }
  1696. // check input...= 0 or ' ' == error!
  1697. if (!trim($k)) {
  1698. return $this->raiseError("selectAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
  1699. }
  1700. if ($this->_query['data_select']) {
  1701. $this->_query['data_select'] .= ', ';
  1702. }
  1703. $this->_query['data_select'] .= " $k ";
  1704. return null;
  1705. }
  1706. /**
  1707. * Adds a 'IN' condition to the WHERE statement
  1708. *
  1709. * $object->whereAddIn('id', $array, 'int'); //minimal usage
  1710. * $object->whereAddIn('price', $array, 'float', 'OR'); // cast to float, and call whereAdd with 'OR'
  1711. * $object->whereAddIn('name', $array, 'string'); // quote strings
  1712. *
  1713. * @param string $key key column to match
  1714. * @param array $list list of values to match
  1715. * @param string $type string|int|integer|float|bool cast to type.
  1716. * @param string $logic optional logic to call whereAdd with eg. "OR" (defaults to "AND")
  1717. * @access public
  1718. * @return string|PEAR::Error - previous condition or Error when invalid args found
  1719. */
  1720. public function whereAddIn($key, $list, $type, $logic = 'AND')
  1721. {
  1722. $not = '';
  1723. if ($key[0] == '!') {
  1724. $not = 'NOT ';
  1725. $key = substr($key, 1);
  1726. }
  1727. // fix type for short entry.
  1728. $type = $type == 'int' ? 'integer' : $type;
  1729. if ($type == 'string') {
  1730. $this->_connect();
  1731. }
  1732. $ar = array();
  1733. foreach ($list as $k) {
  1734. settype($k, $type);
  1735. $ar[] = $type == 'string' ? $this->_quote($k) : $k;
  1736. }
  1737. if (!$ar) {
  1738. return $not ? $this->_query['condition'] : $this->whereAdd("1=0");
  1739. }
  1740. return $this->whereAdd("$key $not IN (" . implode(',', $ar) . ')', $logic);
  1741. }
  1742. /* =========================================================== */
  1743. /* Major Private Methods - the core part! */
  1744. /* =========================================================== */
  1745. /**
  1746. * Adds a order by condition
  1747. *
  1748. * $object->orderBy(); //clears order by
  1749. * $object->orderBy("ID");
  1750. * $object->orderBy("ID,age");
  1751. *
  1752. * @param bool $order Order
  1753. * @return bool|error|none|PEAR
  1754. * @access public
  1755. */
  1756. public function orderBy($order = false)
  1757. {
  1758. if ($this->_query === false) {
  1759. $this->raiseError(
  1760. "You cannot do two queries on the same object (copy it before finding)",
  1761. DB_DATAOBJECT_ERROR_INVALIDARGS
  1762. );
  1763. return false;
  1764. }
  1765. if ($order === false) {
  1766. $this->_query['order_by'] = '';
  1767. return null;
  1768. }
  1769. // check input...= 0 or ' ' == error!
  1770. if (!trim($order)) {
  1771. return $this->raiseError("orderBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
  1772. }
  1773. if (!$this->_query['order_by']) {
  1774. $this->_query['order_by'] = " ORDER BY {$order} ";
  1775. return null;
  1776. }
  1777. $this->_query['order_by'] .= " , {$order}";
  1778. return null;
  1779. }
  1780. /**
  1781. * Adds a group by condition
  1782. *
  1783. * $object->groupBy(); //reset the grouping
  1784. * $object->groupBy("ID DESC");
  1785. * $object->groupBy("ID,age");
  1786. *
  1787. * @param bool $group Grouping
  1788. * @return bool|none|PEAR
  1789. * @access public
  1790. */
  1791. public function groupBy($group = false)
  1792. {
  1793. if ($this->_query === false) {
  1794. $this->raiseError(
  1795. "You cannot do two queries on the same object (copy it before finding)",
  1796. DB_DATAOBJECT_ERROR_INVALIDARGS
  1797. );
  1798. return false;
  1799. }
  1800. if ($group === false) {
  1801. $this->_query['group_by'] = '';
  1802. return null;
  1803. }
  1804. // check input...= 0 or ' ' == error!
  1805. if (!trim($group)) {
  1806. return $this->raiseError("groupBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
  1807. }
  1808. if (!$this->_query['group_by']) {
  1809. $this->_query['group_by'] = " GROUP BY {$group} ";
  1810. return null;
  1811. }
  1812. $this->_query['group_by'] .= " , {$group}";
  1813. return null;
  1814. }
  1815. /**
  1816. * Adds a having clause
  1817. *
  1818. * $object->having(); //reset the grouping
  1819. * $object->having("sum(value) > 0 ");
  1820. *
  1821. * @param bool $having condition
  1822. * @return bool|none|PEAR
  1823. * @access public
  1824. */
  1825. public function having($having = false)
  1826. {
  1827. if ($this->_query === false) {
  1828. $this->raiseError(
  1829. "You cannot do two queries on the same object (copy it before finding)",
  1830. DB_DATAOBJECT_ERROR_INVALIDARGS
  1831. );
  1832. return false;
  1833. }
  1834. if ($having === false) {
  1835. $this->_query['having'] = '';
  1836. return null;
  1837. }
  1838. // check input...= 0 or ' ' == error!
  1839. if (!trim($having)) {
  1840. return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
  1841. }
  1842. if (!$this->_query['having']) {
  1843. $this->_query['having'] = " HAVING {$having} ";
  1844. return null;
  1845. }
  1846. $this->_query['having'] .= " AND {$having}";
  1847. return null;
  1848. }
  1849. /**
  1850. * Adds a using Index
  1851. *
  1852. * $object->useIndex(); //reset the use Index
  1853. * $object->useIndex("some_index");
  1854. *
  1855. * Note do not put unfiltered user input into theis method.
  1856. * This is mysql specific at present? - might need altering to support other databases.
  1857. *
  1858. * @param bool $index index or indexes to use.
  1859. * @return bool|none|PEAR
  1860. * @access public
  1861. */
  1862. public function useIndex($index = false)
  1863. {
  1864. if ($this->_query === false) {
  1865. $this->raiseError(
  1866. "You cannot do two queries on the same object (copy it before finding)",
  1867. DB_DATAOBJECT_ERROR_INVALIDARGS
  1868. );
  1869. return false;
  1870. }
  1871. if ($index === false) {
  1872. $this->_query['useindex'] = '';
  1873. return null;
  1874. }
  1875. // check input...= 0 or ' ' == error!
  1876. if ((is_string($index) && !trim($index)) || (is_array($index) && !count($index))) {
  1877. return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
  1878. }
  1879. $index = is_array($index) ? implode(', ', $index) : $index;
  1880. if (!$this->_query['useindex']) {
  1881. $this->_query['useindex'] = " USE INDEX ({$index}) ";
  1882. return null;
  1883. }
  1884. $this->_query['useindex'] = substr($this->_query['useindex'], 0, -2) . ", {$index}) ";
  1885. return null;
  1886. }
  1887. /**
  1888. * Sets the Limit
  1889. *
  1890. * $boject->limit(); // clear limit
  1891. * $object->limit(12);
  1892. * $object->limit(12,10);
  1893. *
  1894. * Note this will emit an error on databases other than mysql/postgress
  1895. * as there is no 'clean way' to implement it. - you should consider refering to
  1896. * your database manual to decide how you want to implement it.
  1897. *
  1898. * @param string $a limit start (or number), or blank to reset
  1899. * @param string $b number
  1900. * @return bool|none|PEAR
  1901. * @access public
  1902. */
  1903. public function limit($a = null, $b = null)
  1904. {
  1905. if ($this->_query === false) {
  1906. $this->raiseError(
  1907. "You cannot do two queries on the same object (copy it before finding)",
  1908. DB_DATAOBJECT_ERROR_INVALIDARGS
  1909. );
  1910. return false;
  1911. }
  1912. if ($a === null) {
  1913. $this->_query['limit_start'] = '';
  1914. $this->_query['limit_count'] = '';
  1915. return null;
  1916. }
  1917. // check input...= 0 or ' ' == error!
  1918. if ((!is_int($a) && ((string)((int)$a) !== (string)$a))
  1919. || (($b !== null) && (!is_int($b) && ((string)((int)$b) !== (string)$b)))) {
  1920. return $this->raiseError("limit: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
  1921. }
  1922. global $_DB_DATAOBJECT;
  1923. $this->_connect();
  1924. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  1925. $this->_query['limit_start'] = ($b == null) ? 0 : (int)$a;
  1926. $this->_query['limit_count'] = ($b == null) ? (int)$a : (int)$b;
  1927. return null;
  1928. }
  1929. /**
  1930. * Insert the current objects variables into the database
  1931. *
  1932. * Returns the ID of the inserted element (if auto increment or sequences are used.)
  1933. *
  1934. * for example
  1935. *
  1936. * Designed to be extended
  1937. *
  1938. * $object = new mytable();
  1939. * $object->name = "fred";
  1940. * echo $object->insert();
  1941. *
  1942. * @access public
  1943. * @return mixed false on failure, int when auto increment or sequence used, otherwise true on success
  1944. */
  1945. public function insert()
  1946. {
  1947. global $_DB_DATAOBJECT;
  1948. // we need to write to the connection (For nextid) - so us the real
  1949. // one not, a copyied on (as ret-by-ref fails with overload!)
  1950. if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
  1951. $this->_connect();
  1952. }
  1953. $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
  1954. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  1955. $items = $this->table();
  1956. if (!$items) {
  1957. $this->raiseError(
  1958. "insert:No table definition for {$this->tableName()}",
  1959. DB_DATAOBJECT_ERROR_INVALIDCONFIG
  1960. );
  1961. return false;
  1962. }
  1963. $options = $_DB_DATAOBJECT['CONFIG'];
  1964. $datasaved = 1;
  1965. $leftq = '';
  1966. $rightq = '';
  1967. $seqKeys = isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()]) ?
  1968. $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] :
  1969. $this->sequenceKey();
  1970. $key = isset($seqKeys[0]) ? $seqKeys[0] : false;
  1971. $useNative = isset($seqKeys[1]) ? $seqKeys[1] : false;
  1972. $seq = isset($seqKeys[2]) ? $seqKeys[2] : false;
  1973. $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["phptype"];
  1974. // nativeSequences or Sequences..
  1975. // big check for using sequences
  1976. if (($key !== false) && !$useNative) {
  1977. if (!$seq) {
  1978. $keyvalue = $DB->nextId($this->tableName());
  1979. } else {
  1980. $f = $DB->getOption('seqname_format');
  1981. $DB->setOption('seqname_format', '%s');
  1982. $keyvalue = $DB->nextId($seq);
  1983. $DB->setOption('seqname_format', $f);
  1984. }
  1985. if ((new PEAR)->isError($keyvalue)) {
  1986. $this->raiseError($keyvalue->toString(), DB_DATAOBJECT_ERROR_INVALIDCONFIG);
  1987. return false;
  1988. }
  1989. $this->$key = $keyvalue;
  1990. }
  1991. // if we haven't set disable_null_strings to "full"
  1992. $ignore_null = !isset($options['disable_null_strings'])
  1993. || !is_string($options['disable_null_strings'])
  1994. || strtolower($options['disable_null_strings']) !== 'full';
  1995. foreach ($items as $k => $v) {
  1996. // if we are using autoincrement - skip the column...
  1997. if ($key && ($k == $key) && $useNative) {
  1998. continue;
  1999. }
  2000. // Ignore INTEGERS which aren't set to a value - or empty string..
  2001. if ((!isset($this->$k) || ($v == 1 && $this->$k === ''))
  2002. && $ignore_null
  2003. ) {
  2004. continue;
  2005. }
  2006. // dont insert data into mysql timestamps
  2007. // use query() if you really want to do this!!!!
  2008. if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
  2009. continue;
  2010. }
  2011. if ($leftq) {
  2012. $leftq .= ', ';
  2013. $rightq .= ', ';
  2014. }
  2015. $leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ') : "$k ");
  2016. if (is_object($this->$k) && is_a($this->$k, 'DB_DataObject_Cast')) {
  2017. $value = $this->$k->toString($v, $DB);
  2018. if ((new PEAR)->isError($value)) {
  2019. $this->raiseError($value->toString(), DB_DATAOBJECT_ERROR_INVALIDARGS);
  2020. return false;
  2021. }
  2022. $rightq .= $value;
  2023. continue;
  2024. }
  2025. if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this, $k)) {
  2026. $rightq .= " NULL ";
  2027. continue;
  2028. }
  2029. // DATE is empty... on a col. that can be null..
  2030. // note: this may be usefull for time as well..
  2031. if (!$this->$k &&
  2032. (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
  2033. !($v & DB_DATAOBJECT_NOTNULL)) {
  2034. $rightq .= " NULL ";
  2035. continue;
  2036. }
  2037. if ($v & DB_DATAOBJECT_STR) {
  2038. $rightq .= $this->_quote((string)(
  2039. ($v & DB_DATAOBJECT_BOOL) ?
  2040. // this is thanks to the braindead idea of postgres to
  2041. // use t/f for boolean.
  2042. (($this->$k === 'f') ? 0 : (int)(bool)$this->$k) :
  2043. $this->$k
  2044. )) . " ";
  2045. continue;
  2046. }
  2047. if (is_numeric($this->$k)) {
  2048. $rightq .= " {$this->$k} ";
  2049. continue;
  2050. }
  2051. /* flag up string values - only at debug level... !!!??? */
  2052. if (is_object($this->$k) || is_array($this->$k)) {
  2053. $this->debug('ODD DATA: ' . $k . ' ' . print_r($this->$k, true), 'ERROR');
  2054. }
  2055. // at present we only cast to integers
  2056. // - V2 may store additional data about float/int
  2057. $rightq .= ' ' . intval($this->$k) . ' ';
  2058. }
  2059. // not sure why we let empty insert here.. - I guess to generate a blank row..
  2060. if ($leftq || $useNative) {
  2061. $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
  2062. if (($dbtype == 'pgsql') && empty($leftq)) {
  2063. $r = $this->_query("INSERT INTO {$table} DEFAULT VALUES");
  2064. } else {
  2065. $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
  2066. }
  2067. if ((new PEAR)->isError($r)) {
  2068. $this->raiseError($r);
  2069. return false;
  2070. }
  2071. if ($r < 1) {
  2072. return 0;
  2073. }
  2074. // now do we have an integer key!
  2075. if ($key && $useNative) {
  2076. switch ($dbtype) {
  2077. case 'mysql':
  2078. case 'mysqli':
  2079. $method = "{$dbtype}_insert_id";
  2080. $this->$key = $method(
  2081. $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection
  2082. );
  2083. break;
  2084. case 'mssql':
  2085. // note this is not really thread safe - you should wrapp it with
  2086. // transactions = eg.
  2087. // $db->query('BEGIN');
  2088. // $db->insert();
  2089. // $db->query('COMMIT');
  2090. $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
  2091. $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
  2092. $mssql_key = $DB->$method("SELECT @@IDENTITY");
  2093. if ((new PEAR)->isError($mssql_key)) {
  2094. $this->raiseError($mssql_key);
  2095. return false;
  2096. }
  2097. $this->$key = $mssql_key;
  2098. break;
  2099. case 'pgsql':
  2100. if (!$seq) {
  2101. $seq = $DB->getSequenceName(strtolower($this->tableName()));
  2102. }
  2103. $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
  2104. $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
  2105. $pgsql_key = $DB->$method("SELECT currval('" . $seq . "')");
  2106. if ((new PEAR)->isError($pgsql_key)) {
  2107. $this->raiseError($pgsql_key);
  2108. return false;
  2109. }
  2110. $this->$key = $pgsql_key;
  2111. break;
  2112. case 'ifx':
  2113. $this->$key = array_shift(
  2114. ifx_fetch_row(
  2115. ifx_query(
  2116. "select DBINFO('sqlca.sqlerrd1') FROM systables where tabid=1",
  2117. $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection,
  2118. IFX_SCROLL
  2119. ),
  2120. "FIRST"
  2121. )
  2122. );
  2123. break;
  2124. }
  2125. }
  2126. if (isset($_DB_DATAOBJECT['CACHE'][strtolower(get_class($this))])) {
  2127. $this->_clear_cache();
  2128. }
  2129. if ($key) {
  2130. return $this->$key;
  2131. }
  2132. return true;
  2133. }
  2134. $this->raiseError("insert: No Data specifed for query", DB_DATAOBJECT_ERROR_NODATA);
  2135. return false;
  2136. }
  2137. /**
  2138. * get/set an sequence key
  2139. *
  2140. * by default it returns the first key from keys()
  2141. * set usage: $do->sequenceKey('id',true);
  2142. *
  2143. * override this to return array(false,false) if table has no real sequence key.
  2144. *
  2145. * @param string optional the key sequence/autoinc. key
  2146. * @param boolean optional use native increment. default false
  2147. * @param false|string optional native sequence name
  2148. * @access public
  2149. * @return array (column,use_native,sequence_name)
  2150. */
  2151. public function sequenceKey()
  2152. {
  2153. global $_DB_DATAOBJECT;
  2154. // call setting
  2155. if (!$this->_database) {
  2156. $this->_connect();
  2157. }
  2158. if (!isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database])) {
  2159. $_DB_DATAOBJECT['SEQUENCE'][$this->_database] = array();
  2160. }
  2161. $args = func_get_args();
  2162. if (count($args)) {
  2163. $args[1] = isset($args[1]) ? $args[1] : false;
  2164. $args[2] = isset($args[2]) ? $args[2] : false;
  2165. $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = $args;
  2166. }
  2167. if (isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()])) {
  2168. return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()];
  2169. }
  2170. // end call setting (eg. $do->sequenceKeys(a,b,c); )
  2171. $keys = $this->keys();
  2172. if (!$keys) {
  2173. return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()]
  2174. = array(false, false, false);
  2175. }
  2176. $table = $this->table();
  2177. $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'];
  2178. $usekey = $keys[0];
  2179. $seqname = false;
  2180. if (!empty($_DB_DATAOBJECT['CONFIG']['sequence_' . $this->tableName()])) {
  2181. $seqname = $_DB_DATAOBJECT['CONFIG']['sequence_' . $this->tableName()];
  2182. if (strpos($seqname, ':') !== false) {
  2183. list($usekey, $seqname) = explode(':', $seqname);
  2184. }
  2185. }
  2186. // if the key is not an integer - then it's not a sequence or native
  2187. if (empty($table[$usekey]) || !($table[$usekey] & DB_DATAOBJECT_INT)) {
  2188. return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false, false, false);
  2189. }
  2190. if (!empty($_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'])) {
  2191. $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'];
  2192. if (is_string($ignore) && (strtoupper($ignore) == 'ALL')) {
  2193. return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false, false, $seqname);
  2194. }
  2195. if (is_string($ignore)) {
  2196. $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'] = explode(',', $ignore);
  2197. }
  2198. if (in_array($this->tableName(), $ignore)) {
  2199. return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false, false, $seqname);
  2200. }
  2201. }
  2202. $realkeys = $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName() . "__keys"];
  2203. // if you are using an old ini file - go back to old behaviour...
  2204. if (is_numeric($realkeys[$usekey])) {
  2205. $realkeys[$usekey] = 'N';
  2206. }
  2207. // multiple unique primary keys without a native sequence...
  2208. if (($realkeys[$usekey] == 'K') && (count($keys) > 1)) {
  2209. return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false, false, $seqname);
  2210. }
  2211. // use native sequence keys...
  2212. // technically postgres native here...
  2213. // we need to get the new improved tabledata sorted out first.
  2214. // support named sequence keys.. - currently postgres only..
  2215. if (in_array($dbtype, array('pgsql')) &&
  2216. ($table[$usekey] & DB_DATAOBJECT_INT) &&
  2217. isset($realkeys[$usekey]) && strlen($realkeys[$usekey]) > 1) {
  2218. return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey, true, $realkeys[$usekey]);
  2219. }
  2220. if (in_array($dbtype, array('pgsql', 'mysql', 'mysqli', 'mssql', 'ifx')) &&
  2221. ($table[$usekey] & DB_DATAOBJECT_INT) &&
  2222. isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
  2223. ) {
  2224. return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey, true, $seqname);
  2225. }
  2226. // if not a native autoinc, and we have not assumed all primary keys are sequence
  2227. if (($realkeys[$usekey] != 'N') &&
  2228. !empty($_DB_DATAOBJECT['CONFIG']['dont_use_pear_sequences'])) {
  2229. return array(false, false, false);
  2230. }
  2231. // I assume it's going to try and be a nextval DB sequence.. (not native)
  2232. return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey, false, $seqname);
  2233. }
  2234. /**
  2235. * clear the cache values for this class - normally done on insert/update etc.
  2236. *
  2237. * @access private
  2238. * @return void
  2239. */
  2240. public function _clear_cache()
  2241. {
  2242. global $_DB_DATAOBJECT;
  2243. $class = strtolower(get_class($this));
  2244. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  2245. $this->debug("Clearing Cache for " . $class, 1);
  2246. }
  2247. if (!empty($_DB_DATAOBJECT['CACHE'][$class])) {
  2248. unset($_DB_DATAOBJECT['CACHE'][$class]);
  2249. }
  2250. }
  2251. /**
  2252. * Updates current objects variables into the database
  2253. * uses the keys() to decide how to update
  2254. * Returns the true on success
  2255. *
  2256. * for example
  2257. *
  2258. * $object = DB_DataObject::factory('mytable');
  2259. * $object->get("ID",234);
  2260. * $object->email="testing@test.com";
  2261. * if(!$object->update())
  2262. * echo "UPDATE FAILED";
  2263. *
  2264. * to only update changed items :
  2265. * $dataobject->get(132);
  2266. * $original = $dataobject; // clone/copy it..
  2267. * $dataobject->setFrom($_POST);
  2268. * if ($dataobject->validate()) {
  2269. * $dataobject->update($original);
  2270. * } // otherwise an error...
  2271. *
  2272. * performing global updates:
  2273. * $object = DB_DataObject::factory('mytable');
  2274. * $object->status = "dead";
  2275. * $object->whereAdd('age > 150');
  2276. * $object->update(DB_DATAOBJECT_WHEREADD_ONLY);
  2277. *
  2278. * @param bool $dataObject
  2279. * @return int rows affected or false on failure
  2280. * @access public
  2281. */
  2282. public function update($dataObject = false)
  2283. {
  2284. global $_DB_DATAOBJECT;
  2285. // connect will load the config!
  2286. $this->_connect();
  2287. $original_query = $this->_query;
  2288. $items = $this->table();
  2289. // only apply update against sequence key if it is set?????
  2290. $seq = $this->sequenceKey();
  2291. if ($seq[0] !== false) {
  2292. $keys = array($seq[0]);
  2293. if (!isset($this->{$keys[0]}) && $dataObject !== true) {
  2294. $this->raiseError("update: trying to perform an update without
  2295. the key set, and argument to update is not
  2296. DB_DATAOBJECT_WHEREADD_ONLY
  2297. " . print_r(array('seq' => $seq, 'keys' => $keys), true), DB_DATAOBJECT_ERROR_INVALIDARGS);
  2298. return false;
  2299. }
  2300. } else {
  2301. $keys = $this->keys();
  2302. }
  2303. if (!$items) {
  2304. $this->raiseError("update:No table definition for {$this->tableName()}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
  2305. return false;
  2306. }
  2307. $datasaved = 1;
  2308. $settings = '';
  2309. $this->_connect();
  2310. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  2311. $dbtype = $DB->dsn["phptype"];
  2312. $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
  2313. $options = $_DB_DATAOBJECT['CONFIG'];
  2314. $ignore_null = !isset($options['disable_null_strings'])
  2315. || !is_string($options['disable_null_strings'])
  2316. || strtolower($options['disable_null_strings']) !== 'full';
  2317. foreach ($items as $k => $v) {
  2318. // I think this is ignoring empty vlalues
  2319. if ((!isset($this->$k) || ($v == 1 && $this->$k === ''))
  2320. && $ignore_null
  2321. ) {
  2322. continue;
  2323. }
  2324. // ignore stuff thats
  2325. // dont write things that havent changed..
  2326. if (($dataObject !== false) && isset($dataObject->$k) && ($dataObject->$k === $this->$k)) {
  2327. continue;
  2328. }
  2329. // - dont write keys to left.!!!
  2330. if (in_array($k, $keys)) {
  2331. continue;
  2332. }
  2333. // dont insert data into mysql timestamps
  2334. // use query() if you really want to do this!!!!
  2335. if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
  2336. continue;
  2337. }
  2338. if ($settings) {
  2339. $settings .= ', ';
  2340. }
  2341. $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
  2342. if (is_object($this->$k) && is_a($this->$k, 'DB_DataObject_Cast')) {
  2343. $value = $this->$k->toString($v, $DB);
  2344. if ((new PEAR)->isError($value)) {
  2345. $this->raiseError($value->getMessage(), DB_DATAOBJECT_ERROR_INVALIDARG);
  2346. return false;
  2347. }
  2348. $settings .= "$kSql = $value ";
  2349. continue;
  2350. }
  2351. // special values ... at least null is handled...
  2352. if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this, $k)) {
  2353. $settings .= "$kSql = NULL ";
  2354. continue;
  2355. }
  2356. // DATE is empty... on a col. that can be null..
  2357. // note: this may be usefull for time as well..
  2358. if (!$this->$k &&
  2359. (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
  2360. !($v & DB_DATAOBJECT_NOTNULL)) {
  2361. $settings .= "$kSql = NULL ";
  2362. continue;
  2363. }
  2364. if ($v & DB_DATAOBJECT_STR) {
  2365. $settings .= "$kSql = " . $this->_quote((string)(
  2366. ($v & DB_DATAOBJECT_BOOL) ?
  2367. // this is thanks to the braindead idea of postgres to
  2368. // use t/f for boolean.
  2369. (($this->$k === 'f') ? 0 : (int)(bool)$this->$k) :
  2370. $this->$k
  2371. )) . ' ';
  2372. continue;
  2373. }
  2374. if (is_numeric($this->$k)) {
  2375. $settings .= "$kSql = {$this->$k} ";
  2376. continue;
  2377. }
  2378. // at present we only cast to integers
  2379. // - V2 may store additional data about float/int
  2380. $settings .= "$kSql = " . intval($this->$k) . ' ';
  2381. }
  2382. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  2383. $this->debug("got keys as " . serialize($keys), 3);
  2384. }
  2385. if ($dataObject !== true) {
  2386. $this->_build_condition($items, $keys);
  2387. } else {
  2388. // prevent wiping out of data!
  2389. if (empty($this->_query['condition'])) {
  2390. $this->raiseError("update: global table update not available
  2391. do \$do->whereAdd('1=1'); if you really want to do that.
  2392. ", DB_DATAOBJECT_ERROR_INVALIDARGS);
  2393. return false;
  2394. }
  2395. }
  2396. // echo " $settings, $this->condition ";
  2397. if ($settings && isset($this->_query) && $this->_query['condition']) {
  2398. $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
  2399. $r = $this->_query("UPDATE {$table} SET {$settings} {$this->_query['condition']} ");
  2400. // restore original query conditions.
  2401. $this->_query = $original_query;
  2402. if ((new PEAR)->isError($r)) {
  2403. $this->raiseError($r);
  2404. return false;
  2405. }
  2406. if ($r < 1) {
  2407. return 0;
  2408. }
  2409. $this->_clear_cache();
  2410. return $r;
  2411. }
  2412. // restore original query conditions.
  2413. $this->_query = $original_query;
  2414. // if you manually specified a dataobject, and there where no changes - then it's ok..
  2415. if ($dataObject !== false) {
  2416. return true;
  2417. }
  2418. $this->raiseError(
  2419. "update: No Data specifed for query $settings , {$this->_query['condition']}",
  2420. DB_DATAOBJECT_ERROR_NODATA
  2421. );
  2422. return false;
  2423. }
  2424. /**
  2425. * Deletes items from table which match current objects variables
  2426. *
  2427. * Returns the true on success
  2428. *
  2429. * for example
  2430. *
  2431. * Designed to be extended
  2432. *
  2433. * $object = new mytable();
  2434. * $object->ID=123;
  2435. * echo $object->delete(); // builds a conditon
  2436. *
  2437. * $object = new mytable();
  2438. * $object->whereAdd('age > 12');
  2439. * $object->limit(1);
  2440. * $object->orderBy('age DESC');
  2441. * $object->delete(true); // dont use object vars, use the conditions, limit and order.
  2442. *
  2443. * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
  2444. * we will build the condition only using the whereAdd's. Default is to
  2445. * build the condition only using the object parameters.
  2446. *
  2447. * @access public
  2448. * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
  2449. */
  2450. public function delete($useWhere = false)
  2451. {
  2452. global $_DB_DATAOBJECT;
  2453. // connect will load the config!
  2454. $this->_connect();
  2455. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  2456. $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
  2457. $extra_cond = ' ' . (isset($this->_query['order_by']) ? $this->_query['order_by'] : '');
  2458. if (!$useWhere) {
  2459. $keys = $this->keys();
  2460. $this->_query = array(); // as it's probably unset!
  2461. $this->_query['condition'] = ''; // default behaviour not to use where condition
  2462. $this->_build_condition($this->table(), $keys);
  2463. // if primary keys are not set then use data from rest of object.
  2464. if (!$this->_query['condition']) {
  2465. $this->_build_condition($this->table(), array(), $keys);
  2466. }
  2467. $extra_cond = '';
  2468. }
  2469. // don't delete without a condition
  2470. if (($this->_query !== false) && $this->_query['condition']) {
  2471. $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
  2472. $sql = "DELETE ";
  2473. // using a joined delete. - with useWhere..
  2474. $sql .= (!empty($this->_join) && $useWhere) ?
  2475. "{$table} FROM {$table} {$this->_join} " :
  2476. "FROM {$table} ";
  2477. $sql .= $this->_query['condition'] . $extra_cond;
  2478. // add limit..
  2479. if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
  2480. if (!isset($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
  2481. ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
  2482. // pear DB
  2483. $sql = $DB->modifyLimitQuery($sql, $this->_query['limit_start'], $this->_query['limit_count']);
  2484. } else {
  2485. // MDB2
  2486. $DB->setLimit($this->_query['limit_count'], $this->_query['limit_start']);
  2487. }
  2488. }
  2489. $r = $this->_query($sql);
  2490. if ((new PEAR)->isError($r)) {
  2491. $this->raiseError($r);
  2492. return false;
  2493. }
  2494. if ($r < 1) {
  2495. return 0;
  2496. }
  2497. $this->_clear_cache();
  2498. return $r;
  2499. } else {
  2500. $this->raiseError("delete: No condition specifed for query", DB_DATAOBJECT_ERROR_NODATA);
  2501. return false;
  2502. }
  2503. }
  2504. /**
  2505. * fetches a specific row into this object variables
  2506. *
  2507. * Not recommended - better to use fetch()
  2508. *
  2509. * Returens true on success
  2510. *
  2511. * @param int $row row
  2512. * @access public
  2513. * @return boolean true on success
  2514. */
  2515. public function fetchRow($row = null)
  2516. {
  2517. global $_DB_DATAOBJECT;
  2518. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  2519. $this->_loadConfig();
  2520. }
  2521. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  2522. $this->debug("{$this->tableName()} $row of {$this->N}", "fetchrow", 3);
  2523. }
  2524. if (!$this->tableName()) {
  2525. $this->raiseError("fetchrow: No table", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
  2526. return false;
  2527. }
  2528. if ($row === null) {
  2529. $this->raiseError("fetchrow: No row specified", DB_DATAOBJECT_ERROR_INVALIDARGS);
  2530. return false;
  2531. }
  2532. if (!$this->N) {
  2533. $this->raiseError("fetchrow: No results avaiable", DB_DATAOBJECT_ERROR_NODATA);
  2534. return false;
  2535. }
  2536. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  2537. $this->debug("{$this->tableName()} $row of {$this->N}", "fetchrow", 3);
  2538. }
  2539. $result = $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
  2540. $array = $result->fetchrow(DB_DATAOBJECT_FETCHMODE_ASSOC, $row);
  2541. if (!is_array($array)) {
  2542. $this->raiseError("fetchrow: No results available", DB_DATAOBJECT_ERROR_NODATA);
  2543. return false;
  2544. }
  2545. $replace = array('.', ' ');
  2546. foreach ($array as $k => $v) {
  2547. // use strpos as str_replace is slow.
  2548. $kk = (strpos($k, '.') === false && strpos($k, ' ') === false) ?
  2549. $k : str_replace($replace, '_', $k);
  2550. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  2551. $this->debug("$kk = " . $array[$k], "fetchrow LINE", 3);
  2552. }
  2553. $this->$kk = $array[$k];
  2554. }
  2555. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  2556. $this->debug("{$this->tableName()} DONE", "fetchrow", 3);
  2557. }
  2558. return true;
  2559. }
  2560. /**
  2561. * Find the number of results from a simple query
  2562. *
  2563. * for example
  2564. *
  2565. * $object = new mytable();
  2566. * $object->name = "fred";
  2567. * echo $object->count();
  2568. * echo $object->count(true); // dont use object vars.
  2569. * echo $object->count('distinct mycol'); count distinct mycol.
  2570. * echo $object->count('distinct mycol',true); // dont use object vars.
  2571. * echo $object->count('distinct'); // count distinct id (eg. the primary key)
  2572. *
  2573. *
  2574. * @param bool|string (optional)
  2575. * (true|false => see below not on whereAddonly)
  2576. * (string)
  2577. * "DISTINCT" => does a distinct count on the tables 'key' column
  2578. * otherwise => normally it counts primary keys - you can use
  2579. * this to do things like $do->count('distinct mycol');
  2580. *
  2581. * @param bool $whereAddOnly (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
  2582. * we will build the condition only using the whereAdd's. Default is to
  2583. * build the condition using the object parameters as well.
  2584. *
  2585. * @access public
  2586. * @return int
  2587. */
  2588. public function count($countWhat = false, $whereAddOnly = false)
  2589. {
  2590. global $_DB_DATAOBJECT;
  2591. if (is_bool($countWhat)) {
  2592. $whereAddOnly = $countWhat;
  2593. }
  2594. $t = clone($this);
  2595. $items = $t->table();
  2596. $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
  2597. if (!isset($t->_query)) {
  2598. $this->raiseError(
  2599. "You cannot do run count after you have run fetch()",
  2600. DB_DATAOBJECT_ERROR_INVALIDARGS
  2601. );
  2602. return false;
  2603. }
  2604. $this->_connect();
  2605. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  2606. if (!$whereAddOnly && $items) {
  2607. $t->_build_condition($items);
  2608. }
  2609. $keys = $this->keys();
  2610. if (empty($keys[0]) && (!is_string($countWhat) || (strtoupper($countWhat) == 'DISTINCT'))) {
  2611. $this->raiseError(
  2612. "You cannot do run count without keys - use \$do->count('id'), or use \$do->count('distinct id')';",
  2613. DB_DATAOBJECT_ERROR_INVALIDARGS,
  2614. PEAR_ERROR_DIE
  2615. );
  2616. return false;
  2617. }
  2618. $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->tableName()) : $this->tableName());
  2619. $key_col = empty($keys[0]) ? '' : (($quoteIdentifiers ? $DB->quoteIdentifier($keys[0]) : $keys[0]));
  2620. $as = ($quoteIdentifiers ? $DB->quoteIdentifier('DATAOBJECT_NUM') : 'DATAOBJECT_NUM');
  2621. // support distinct on default keys.
  2622. $countWhat = (strtoupper($countWhat) == 'DISTINCT') ?
  2623. "DISTINCT {$table}.{$key_col}" : $countWhat;
  2624. $countWhat = is_string($countWhat) ? $countWhat : "{$table}.{$key_col}";
  2625. $r = $t->_query(
  2626. "SELECT count({$countWhat}) as $as
  2627. FROM $table {$t->_join} {$t->_query['condition']}"
  2628. );
  2629. if ((new PEAR)->isError($r)) {
  2630. return false;
  2631. }
  2632. $result = $_DB_DATAOBJECT['RESULTS'][$t->_DB_resultid];
  2633. $l = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ORDERED);
  2634. // free the results - essential on oracle.
  2635. $t->free();
  2636. if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
  2637. $this->debug('Count returned ' . $l[0], 1);
  2638. }
  2639. return (int)$l[0];
  2640. }
  2641. /**
  2642. * Free global arrays associated with this object.
  2643. *
  2644. *
  2645. * @access public
  2646. * @return none
  2647. */
  2648. public function free()
  2649. {
  2650. global $_DB_DATAOBJECT;
  2651. if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
  2652. unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
  2653. }
  2654. if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
  2655. unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
  2656. }
  2657. // clear the staticGet cache as well.
  2658. $this->_clear_cache();
  2659. // this is a huge bug in DB!
  2660. if (isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
  2661. $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows = array();
  2662. }
  2663. if (is_array($this->_link_loaded)) {
  2664. foreach ($this->_link_loaded as $do) {
  2665. if (
  2666. !empty($this->{$do}) &&
  2667. is_object($this->{$do}) &&
  2668. method_exists($this->{$do}, 'free')
  2669. ) {
  2670. $this->{$do}->free();
  2671. }
  2672. }
  2673. }
  2674. return null;
  2675. }
  2676. /**
  2677. * sends raw query to database
  2678. *
  2679. * Since _query has to be a private 'non overwriteable method', this is a relay
  2680. *
  2681. * @param string $string SQL Query
  2682. * @access public
  2683. * @return void or DB_Error
  2684. */
  2685. public function query($string)
  2686. {
  2687. return $this->_query($string);
  2688. }
  2689. /**
  2690. * an escape wrapper around DB->escapeSimple()
  2691. * can be used when adding manual queries or clauses
  2692. * eg.
  2693. * $object->query("select * from xyz where abc like '". $object->escape($_GET['name']) . "'");
  2694. *
  2695. * @param string $string value to be escaped
  2696. * @param bool $likeEscape escapes % and _ as well. - so like queries can be protected.
  2697. * @access public
  2698. * @return string
  2699. */
  2700. public function escape($string, $likeEscape = false)
  2701. {
  2702. global $_DB_DATAOBJECT;
  2703. $this->_connect();
  2704. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  2705. // mdb2 uses escape...
  2706. $dd = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
  2707. $ret = ($dd == 'DB') ? $DB->escapeSimple($string) : $DB->escape($string);
  2708. if ($likeEscape) {
  2709. $ret = str_replace(array('_', '%'), array('\_', '\%'), $ret);
  2710. }
  2711. return $ret;
  2712. }
  2713. /**
  2714. * Return or assign the name of the current database
  2715. *
  2716. * @param string optional database name to set
  2717. * @access public
  2718. * @return string The name of the current database
  2719. */
  2720. public function database()
  2721. {
  2722. $args = func_get_args();
  2723. if (count($args)) {
  2724. $this->_database = $args[0];
  2725. } else {
  2726. $this->_connect();
  2727. }
  2728. return $this->_database;
  2729. }
  2730. /**
  2731. * generic getter/setter for links
  2732. *
  2733. * This is the new 'recommended' way to get get/set linked objects.
  2734. * must be used with links.ini
  2735. *
  2736. * usage:
  2737. * get:
  2738. * $obj = $do->link('company_id');
  2739. * $obj = $do->link(array('local_col', 'linktable:linked_col'));
  2740. *
  2741. * set:
  2742. * $do->link('company_id',0);
  2743. * $do->link('company_id',$obj);
  2744. * $do->link('company_id', array($obj));
  2745. *
  2746. * example function
  2747. *
  2748. * function company() {
  2749. * $this->link(array('company_id','company:id'), func_get_args());
  2750. * }
  2751. *
  2752. *
  2753. *
  2754. * @param $field
  2755. * @param array $set_args
  2756. * @return mixed true or false on setting, object on getting
  2757. * @author Alan Knowles
  2758. * @access public
  2759. */
  2760. public function link($field, $set_args = array())
  2761. {
  2762. //require_once 'DB/DataObject/Links.php';
  2763. require_once 'Links.php';
  2764. $l = new DB_DataObject_Links($this);
  2765. return $l->link($field, $set_args);
  2766. }
  2767. /**
  2768. * load related objects
  2769. *
  2770. * Generally not recommended to use this.
  2771. * The generator should support creating getter_setter methods which are better suited.
  2772. *
  2773. * Relies on <dbname>.links.ini
  2774. *
  2775. * Sets properties on the calling dataobject you can change what
  2776. * object vars the links are stored in by changeing the format parameter
  2777. *
  2778. *
  2779. * @param string format (default _%s) where %s is the table name.
  2780. * @return boolean , true on success
  2781. * @author Tim White <tim@cyface.com>
  2782. * @access public
  2783. */
  2784. public function getLinks($format = '_%s')
  2785. {
  2786. //require_once 'DB/DataObject/Links.php';
  2787. require_once 'Links.php';
  2788. $l = new DB_DataObject_Links($this);
  2789. return $l->applyLinks($format);
  2790. }
  2791. /**
  2792. * deprecited : @use link()
  2793. * @param $row
  2794. * @param null $table
  2795. * @param bool $link
  2796. * @return mixed
  2797. */
  2798. public function getLink($row, $table = null, $link = false)
  2799. {
  2800. //require_once 'DB/DataObject/Links.php';
  2801. require_once 'Links.php';
  2802. $l = new DB_DataObject_Links($this);
  2803. return $l->getLink($row, $table === null ? false : $table, $link);
  2804. }
  2805. /**
  2806. * getLinkArray
  2807. * Fetch an array of related objects. This should be used in conjunction with a <dbname>.links.ini file configuration (see the introduction on linking for details on this).
  2808. * You may also use this with all parameters to specify, the column and related table.
  2809. * This is highly dependant on naming columns 'correctly' :)
  2810. * using colname = xxxxx_yyyyyy
  2811. * xxxxxx = related table; (yyyyy = user defined..)
  2812. * looks up table xxxxx, for value id=$this->xxxxx
  2813. * stores it in $this->_xxxxx_yyyyy
  2814. *
  2815. * @access public
  2816. * @param $row
  2817. * @param string $table - name of table to look up value in
  2818. * @return array - array of results (empty array on failure)
  2819. *
  2820. * Example - Getting the related objects
  2821. *
  2822. * $person = new DataObjects_Person;
  2823. * $person->get(12);
  2824. * $children = $person->getLinkArray('children');
  2825. *
  2826. * echo 'There are ', count($children), ' descendant(s):<br />';
  2827. * foreach ($children as $child) {
  2828. * echo $child->name, '<br />';
  2829. * }
  2830. */
  2831. public function getLinkArray($row, $table = null)
  2832. {
  2833. //require_once 'DB/DataObject/Links.php';
  2834. require_once 'Links.php';
  2835. $l = new DB_DataObject_Links($this);
  2836. return $l->getLinkArray($row, $table === null ? false : $table);
  2837. }
  2838. /**
  2839. * unionAdd - adds another dataobject to this, building a unioned query.
  2840. *
  2841. * usage:
  2842. * $doTable1 = DB_DataObject::factory("table1");
  2843. * $doTable2 = DB_DataObject::factory("table2");
  2844. *
  2845. * $doTable1->selectAdd();
  2846. * $doTable1->selectAdd("col1,col2");
  2847. * $doTable1->whereAdd("col1 > 100");
  2848. * $doTable1->orderBy("col1");
  2849. *
  2850. * $doTable2->selectAdd();
  2851. * $doTable2->selectAdd("col1, col2");
  2852. * $doTable2->whereAdd("col2 = 'v'");
  2853. *
  2854. * $doTable1->unionAdd($doTable2);
  2855. * $doTable1->find();
  2856. *
  2857. * Note: this model may be a better way to implement joinAdd?, eg. do the building in find?
  2858. *
  2859. *
  2860. * @param $obj object|false the union object or false to reset
  2861. * @param string $is_all string 'ALL' to do all.
  2862. * @return false|mixed|object
  2863. */
  2864. public function unionAdd($obj, $is_all = '')
  2865. {
  2866. if ($obj === false) {
  2867. $ret = $this->_query['unions'];
  2868. $this->_query['unions'] = array();
  2869. return $ret;
  2870. }
  2871. $this->_query['unions'][] = array($obj, 'UNION ' . $is_all . ' ');
  2872. return $obj;
  2873. }
  2874. /**
  2875. * autoJoin - using the links.ini file, it builds a query with all the joins
  2876. * usage:
  2877. * $x = DB_DataObject::factory('mytable');
  2878. * $x->autoJoin();
  2879. * $x->get(123);
  2880. * will result in all of the joined data being added to the fetched object..
  2881. *
  2882. * $x = DB_DataObject::factory('mytable');
  2883. * $x->autoJoin();
  2884. * $ar = $x->fetchAll();
  2885. * will result in an array containing all the data from the table, and any joined tables..
  2886. *
  2887. * $x = DB_DataObject::factory('mytable');
  2888. * $jdata = $x->autoJoin();
  2889. * $x->selectAdd(); //reset..
  2890. * foreach($_REQUEST['requested_cols'] as $c) {
  2891. * if (!isset($jdata[$c])) continue; // ignore columns not available..
  2892. * $x->selectAdd( $jdata[$c] . ' as ' . $c);
  2893. * }
  2894. * $ar = $x->fetchAll();
  2895. * will result in only the columns requested being fetched...
  2896. *
  2897. *
  2898. *
  2899. * @param array Configuration
  2900. * exclude Array of columns to exclude from results (eg. modified_by_id)
  2901. * links The equivilant links.ini data for this table eg.
  2902. * array( 'person_id' => 'person:id', .... )
  2903. * include Array of columns to include
  2904. * distinct Array of distinct columns.
  2905. *
  2906. * @return array info about joins
  2907. * cols => map of resulting {joined_tablename}.{joined_table_column_name}
  2908. * join_names => map of resulting {join_name_as}.{joined_table_column_name}
  2909. * count => the column to count on.
  2910. * @access public
  2911. */
  2912. public function autoJoin($cfg = array())
  2913. {
  2914. global $_DB_DATAOBJECT;
  2915. //var_Dump($cfg);exit;
  2916. $pre_links = $this->links();
  2917. if (!empty($cfg['links'])) {
  2918. $this->links(array_merge($pre_links, $cfg['links']));
  2919. }
  2920. $map = $this->links();
  2921. $this->databaseStructure();
  2922. $dbstructure = $_DB_DATAOBJECT['INI'][$this->_database];
  2923. //print_r($map);
  2924. $tabdef = $this->table();
  2925. // we need this as normally it's only cleared by an empty selectAs call.
  2926. $keys = array_keys($tabdef);
  2927. if (!empty($cfg['exclude'])) {
  2928. $keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
  2929. }
  2930. if (!empty($cfg['include'])) {
  2931. $keys = array_intersect($keys, $cfg['include']);
  2932. }
  2933. $selectAs = array();
  2934. if (!empty($keys)) {
  2935. $selectAs = array(array($keys, '%s', false));
  2936. }
  2937. $ret = array(
  2938. 'cols' => array(),
  2939. 'join_names' => array(),
  2940. 'count' => false,
  2941. );
  2942. $has_distinct = false;
  2943. if (!empty($cfg['distinct']) && $keys) {
  2944. // reset the columsn?
  2945. $cols = array();
  2946. //echo '<PRE>' ;print_r($xx);exit;
  2947. foreach ($keys as $c) {
  2948. //var_dump($c);
  2949. if ($cfg['distinct'] == $c) {
  2950. $has_distinct = 'DISTINCT( ' . $this->tableName() . '.' . $c . ') as ' . $c;
  2951. $ret['count'] = 'DISTINCT ' . $this->tableName() . '.' . $c . '';
  2952. continue;
  2953. }
  2954. // cols is in our filtered keys...
  2955. $cols = $c;
  2956. }
  2957. // apply our filtered version, which excludes the distinct column.
  2958. $selectAs = empty($cols) ? array() : array(array(array($cols), '%s', false));
  2959. }
  2960. foreach ($keys as $k) {
  2961. $ret['cols'][$k] = $this->tableName() . '.' . $k;
  2962. }
  2963. foreach ($map as $ocl => $info) {
  2964. list($tab, $col) = explode(':', $info);
  2965. // what about multiple joins on the same table!!!
  2966. // if links point to a table that does not exist - ignore.
  2967. if (!isset($dbstructure[$tab])) {
  2968. continue;
  2969. }
  2970. $xx = DB_DataObject::factory($tab);
  2971. if (!is_object($xx) || !is_a($xx, 'DB_DataObject')) {
  2972. continue;
  2973. }
  2974. // skip columns that are excluded.
  2975. // we ignore include here... - as
  2976. // this is borked ... for multiple jions..
  2977. $this->joinAdd($xx, 'LEFT', 'join_' . $ocl . '_' . $col, $ocl);
  2978. if (!empty($cfg['exclude']) && in_array($ocl, $cfg['exclude'])) {
  2979. continue;
  2980. }
  2981. $tabdef = $xx->table();
  2982. $table = $xx->tableName();
  2983. $keys = array_keys($tabdef);
  2984. if (!empty($cfg['exclude'])) {
  2985. $keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
  2986. foreach ($keys as $k) {
  2987. if (in_array($ocl . '_' . $k, $cfg['exclude'])) {
  2988. $keys = array_diff($keys, $k); // removes the k..
  2989. }
  2990. }
  2991. }
  2992. if (!empty($cfg['include'])) {
  2993. // include will basically be BASECOLNAME_joinedcolname
  2994. $nkeys = array();
  2995. foreach ($keys as $k) {
  2996. if (in_array(sprintf($ocl . '_%s', $k), $cfg['include'])) {
  2997. $nkeys[] = $k;
  2998. }
  2999. }
  3000. $keys = $nkeys;
  3001. }
  3002. if (empty($keys)) {
  3003. continue;
  3004. }
  3005. // got distinct, and not yet found it..
  3006. if (!$has_distinct && !empty($cfg['distinct'])) {
  3007. $cols = array();
  3008. foreach ($keys as $c) {
  3009. $tn = sprintf($ocl . '_%s', $c);
  3010. if ($tn == $cfg['distinct']) {
  3011. $has_distinct = 'DISTINCT( ' . 'join_' . $ocl . '_' . $col . '.' . $c . ') as ' . $tn;
  3012. $ret['count'] = 'DISTINCT join_' . $ocl . '_' . $col . '.' . $c;
  3013. // var_dump($this->countWhat );
  3014. continue;
  3015. }
  3016. $cols[] = $c;
  3017. }
  3018. if (!empty($cols)) {
  3019. $selectAs[] = array($cols, $ocl . '_%s', 'join_' . $ocl . '_' . $col);
  3020. }
  3021. } else {
  3022. $selectAs[] = array($keys, $ocl . '_%s', 'join_' . $ocl . '_' . $col);
  3023. }
  3024. foreach ($keys as $k) {
  3025. $ret['cols'][sprintf('%s_%s', $ocl, $k)] = $tab . '.' . $k;
  3026. $ret['join_names'][sprintf('%s_%s', $ocl, $k)] = sprintf('join_%s_%s.%s', $ocl, $col, $k);
  3027. }
  3028. }
  3029. // fill in the select details..
  3030. $this->selectAdd();
  3031. if ($has_distinct) {
  3032. $this->selectAdd($has_distinct);
  3033. }
  3034. foreach ($selectAs as $ar) {
  3035. $this->selectAs($ar[0], $ar[1], $ar[2]);
  3036. }
  3037. // restore links..
  3038. $this->links($pre_links);
  3039. return $ret;
  3040. }
  3041. /**
  3042. * Get the links associate array as defined by the links.ini file.
  3043. *
  3044. *
  3045. * Experimental... -
  3046. * Should look a bit like
  3047. * [local_col_name] => "related_tablename:related_col_name"
  3048. *
  3049. * @return array|null
  3050. * array = if there are links defined for this table.
  3051. * empty array - if there is a links.ini file, but no links on this table
  3052. * false - if no links.ini exists for this database (hence try auto_links).
  3053. * @access public
  3054. * @see DB_DataObject::getLinks(), DB_DataObject::getLink()
  3055. */
  3056. public function links()
  3057. {
  3058. global $_DB_DATAOBJECT;
  3059. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  3060. $this->_loadConfig();
  3061. }
  3062. // have to connect.. -> otherwise things break later.
  3063. $this->_connect();
  3064. // alias for shorter code..
  3065. $lcfg = &$_DB_DATAOBJECT['LINKS'];
  3066. $cfg = $_DB_DATAOBJECT['CONFIG'];
  3067. if ($args = func_get_args()) {
  3068. // an associative array was specified, that updates the current
  3069. // schema... - be careful doing this
  3070. if (empty($lcfg[$this->_database])) {
  3071. $lcfg[$this->_database] = array();
  3072. }
  3073. $lcfg[$this->_database][$this->tableName()] = $args[0];
  3074. }
  3075. // loaded and available.
  3076. if (isset($lcfg[$this->_database][$this->tableName()])) {
  3077. return $lcfg[$this->_database][$this->tableName()];
  3078. }
  3079. // loaded
  3080. if (isset($lcfg[$this->_database])) {
  3081. // either no file, or empty..
  3082. return $lcfg[$this->_database] === false ? null : array();
  3083. }
  3084. // links are same place as schema by default.
  3085. $schemas = isset($cfg['schema_location']) ?
  3086. array("{$cfg['schema_location']}/{$this->_database}.ini") :
  3087. array();
  3088. // if ini_* is set look there instead.
  3089. // and support multiple locations.
  3090. if (isset($cfg["ini_{$this->_database}"])) {
  3091. $schemas = is_array($cfg["ini_{$this->_database}"]) ?
  3092. $cfg["ini_{$this->_database}"] :
  3093. explode(PATH_SEPARATOR, $cfg["ini_{$this->_database}"]);
  3094. }
  3095. // default to not available.
  3096. $lcfg[$this->_database] = false;
  3097. foreach ($schemas as $ini) {
  3098. $links = isset($cfg["links_{$this->_database}"]) ?
  3099. $cfg["links_{$this->_database}"] :
  3100. str_replace('.ini', '.links.ini', $ini);
  3101. // file really exists..
  3102. if (!file_exists($links) || !is_file($links)) {
  3103. if (!empty($cfg['debug'])) {
  3104. $this->debug("Missing links.ini file: $links", "links", 1);
  3105. }
  3106. continue;
  3107. }
  3108. // set to empty array - as we have at least one file now..
  3109. $lcfg[$this->_database] = empty($lcfg[$this->_database]) ? array() : $lcfg[$this->_database];
  3110. // merge schema file into lcfg..
  3111. $lcfg[$this->_database] = array_merge(
  3112. $lcfg[$this->_database],
  3113. parse_ini_file($links, true)
  3114. );
  3115. if (!empty($cfg['debug'])) {
  3116. $this->debug("Loaded links.ini file: $links", "links", 1);
  3117. }
  3118. }
  3119. if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
  3120. foreach ($lcfg[$this->_database] as $k => $v) {
  3121. $nk = strtolower($k);
  3122. // results in duplicate cols.. but not a big issue..
  3123. $lcfg[$this->_database][$nk] = isset($lcfg[$this->_database][$nk])
  3124. ? $lcfg[$this->_database][$nk] : array();
  3125. foreach ($v as $kk => $vv) {
  3126. //var_Dump($vv);exit;
  3127. $vv = explode(':', $vv);
  3128. $vv[0] = strtolower($vv[0]);
  3129. $lcfg[$this->_database][$nk][$kk] = implode(':', $vv);
  3130. }
  3131. }
  3132. }
  3133. //echo '<PRE>';print_r($lcfg);exit;
  3134. // if there is no link data at all on the file!
  3135. // we return null.
  3136. if ($lcfg[$this->_database] === false) {
  3137. return null;
  3138. }
  3139. if (isset($lcfg[$this->_database][$this->tableName()])) {
  3140. return $lcfg[$this->_database][$this->tableName()];
  3141. }
  3142. return array();
  3143. }
  3144. /**
  3145. * joinAdd - adds another dataobject to this, building a joined query.
  3146. *
  3147. * example (requires links.ini to be set up correctly)
  3148. * // get all the images for product 24
  3149. * $i = new DataObject_Image();
  3150. * $pi = new DataObjects_Product_image();
  3151. * $pi->product_id = 24; // set the product id to 24
  3152. * $i->joinAdd($pi); // add the product_image connectoin
  3153. * $i->find();
  3154. * while ($i->fetch()) {
  3155. * // do stuff
  3156. * }
  3157. * // an example with 2 joins
  3158. * // get all the images linked with products or productgroups
  3159. * $i = new DataObject_Image();
  3160. * $pi = new DataObject_Product_image();
  3161. * $pgi = new DataObject_Productgroup_image();
  3162. * $i->joinAdd($pi);
  3163. * $i->joinAdd($pgi);
  3164. * $i->find();
  3165. * while ($i->fetch()) {
  3166. * // do stuff
  3167. * }
  3168. *
  3169. *
  3170. * @param bool $obj object |array the joining object (no value resets the join)
  3171. * If you use an array here it should be in the format:
  3172. * array('local_column','remotetable:remote_column');
  3173. * if remotetable does not have a definition, you should
  3174. * use @ to hide the include error message..
  3175. * array('local_column', $dataobject , 'remote_column');
  3176. * if array has 3 args, then second is assumed to be the linked dataobject.
  3177. *
  3178. * @param string $joinType string | array
  3179. * 'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates
  3180. * just select ... from a,b,c with no join and
  3181. * links are added as where items.
  3182. *
  3183. * If second Argument is array, it is assumed to be an associative
  3184. * array with arguments matching below = eg.
  3185. * 'joinType' => 'INNER',
  3186. * 'joinAs' => '...'
  3187. * 'joinCol' => ....
  3188. * 'useWhereAsOn' => false,
  3189. *
  3190. * @param bool $joinAs string if you want to select the table as anther name
  3191. * useful when you want to select multiple columsn
  3192. * from a secondary table.
  3193. * @param bool $joinCol string The column on This objects table to match (needed
  3194. * if this table links to the child object in
  3195. * multiple places eg.
  3196. * user->friend (is a link to another user)
  3197. * user->mother (is a link to another user..)
  3198. *
  3199. * optional 'useWhereAsOn' bool default false;
  3200. * convert the where argments from the object being added
  3201. * into ON arguments.
  3202. *
  3203. *
  3204. * @return error|none
  3205. * @access public
  3206. * @author Stijn de Reede <sjr@gmx.co.uk>
  3207. */
  3208. public function joinAdd($obj = false, $joinType = 'INNER', $joinAs = false, $joinCol = false)
  3209. {
  3210. global $_DB_DATAOBJECT;
  3211. if ($obj === false) {
  3212. $this->_join = '';
  3213. return null;
  3214. }
  3215. //echo '<PRE>'; print_r(func_get_args());
  3216. $useWhereAsOn = false;
  3217. // support for 2nd argument as an array of options
  3218. if (is_array($joinType)) {
  3219. // new options can now go in here... (dont forget to document them)
  3220. $useWhereAsOn = !empty($joinType['useWhereAsOn']);
  3221. $joinCol = isset($joinType['joinCol']) ? $joinType['joinCol'] : $joinCol;
  3222. $joinAs = isset($joinType['joinAs']) ? $joinType['joinAs'] : $joinAs;
  3223. $joinType = isset($joinType['joinType']) ? $joinType['joinType'] : 'INNER';
  3224. }
  3225. // support for array as first argument
  3226. // this assumes that you dont have a links.ini for the specified table.
  3227. // and it doesnt exist as am extended dataobject!! - experimental.
  3228. $ofield = false; // object field
  3229. $tfield = false; // this field
  3230. $toTable = false;
  3231. if (is_array($obj)) {
  3232. $tfield = $obj[0];
  3233. if (count($obj) == 3) {
  3234. $ofield = $obj[2];
  3235. $obj = $obj[1];
  3236. } else {
  3237. list($toTable, $ofield) = explode(':', $obj[1]);
  3238. $obj = is_string($toTable) ? DB_DataObject::factory($toTable) : $toTable;
  3239. if (!$obj || !is_object($obj) || is_a($obj, 'PEAR_Error')) {
  3240. $obj = new DB_DataObject;
  3241. $obj->__table = $toTable;
  3242. }
  3243. $obj->_connect();
  3244. }
  3245. // set the table items to nothing.. - eg. do not try and match
  3246. // things in the child table...???
  3247. $items = array();
  3248. }
  3249. if (!is_object($obj) || !is_a($obj, 'DB_DataObject')) {
  3250. return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA, PEAR_ERROR_DIE);
  3251. }
  3252. /* make sure $this->_database is set. */
  3253. $this->_connect();
  3254. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  3255. /// CHANGED 26 JUN 2009 - we prefer links from our local table over the remote one.
  3256. /* otherwise see if there are any links from this table to the obj. */
  3257. //print_r($this->links());
  3258. if (($ofield === false) && ($links = $this->links())) {
  3259. // this enables for support for arrays of links in ini file.
  3260. // link contains this_column[] = linked_table:linked_column
  3261. // or standard way.
  3262. // link contains this_column = linked_table:linked_column
  3263. foreach ($links as $k => $linkVar) {
  3264. if (!is_array($linkVar)) {
  3265. $linkVar = array($linkVar);
  3266. }
  3267. foreach ($linkVar as $v) {
  3268. /* link contains {this column} = {linked table}:{linked column} */
  3269. $ar = explode(':', $v);
  3270. // Feature Request #4266 - Allow joins with multiple keys
  3271. if (strpos($k, ',') !== false) {
  3272. $k = explode(',', $k);
  3273. }
  3274. if (strpos($ar[1], ',') !== false) {
  3275. $ar[1] = explode(',', $ar[1]);
  3276. }
  3277. if ($ar[0] != $obj->tableName()) {
  3278. continue;
  3279. }
  3280. if ($joinCol !== false) {
  3281. if ($k == $joinCol) {
  3282. // got it!?
  3283. $tfield = $k;
  3284. $ofield = $ar[1];
  3285. break;
  3286. }
  3287. continue;
  3288. }
  3289. $tfield = $k;
  3290. $ofield = $ar[1];
  3291. break;
  3292. }
  3293. }
  3294. }
  3295. /* look up the links for obj table */
  3296. //print_r($obj->links());
  3297. if (!$ofield && ($olinks = $obj->links())) {
  3298. foreach ($olinks as $k => $linkVar) {
  3299. /* link contains {this column} = array ( {linked table}:{linked column} )*/
  3300. if (!is_array($linkVar)) {
  3301. $linkVar = array($linkVar);
  3302. }
  3303. foreach ($linkVar as $v) {
  3304. /* link contains {this column} = {linked table}:{linked column} */
  3305. $ar = explode(':', $v);
  3306. // Feature Request #4266 - Allow joins with multiple keys
  3307. $links_key_array = strpos($k, ',');
  3308. if ($links_key_array !== false) {
  3309. $k = explode(',', $k);
  3310. }
  3311. $ar_array = strpos($ar[1], ',');
  3312. if ($ar_array !== false) {
  3313. $ar[1] = explode(',', $ar[1]);
  3314. }
  3315. if ($ar[0] != $this->tableName()) {
  3316. continue;
  3317. }
  3318. // you have explictly specified the column
  3319. // and the col is listed here..
  3320. // not sure if 1:1 table could cause probs here..
  3321. if ($joinCol !== false) {
  3322. $this->raiseError(
  3323. "joinAdd: You cannot target a join column in the " .
  3324. "'link from' table ({$obj->tableName()}). " .
  3325. "Either remove the fourth argument to joinAdd() " .
  3326. "({$joinCol}), or alter your links.ini file.",
  3327. DB_DATAOBJECT_ERROR_NODATA
  3328. );
  3329. return false;
  3330. }
  3331. $ofield = $k;
  3332. $tfield = $ar[1];
  3333. break;
  3334. }
  3335. }
  3336. }
  3337. // finally if these two table have column names that match do a join by default on them
  3338. if (($ofield === false) && $joinCol) {
  3339. $ofield = $joinCol;
  3340. $tfield = $joinCol;
  3341. }
  3342. /* did I find a conneciton between them? */
  3343. if ($ofield === false) {
  3344. $this->raiseError(
  3345. "joinAdd: {$obj->tableName()} has no link with {$this->tableName()}",
  3346. DB_DATAOBJECT_ERROR_NODATA
  3347. );
  3348. return false;
  3349. }
  3350. $joinType = strtoupper($joinType);
  3351. // we default to joining as the same name (this is remvoed later..)
  3352. if ($joinAs === false) {
  3353. $joinAs = $obj->tableName();
  3354. }
  3355. $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
  3356. $options = $_DB_DATAOBJECT['CONFIG'];
  3357. // not sure how portable adding database prefixes is..
  3358. $objTable = $quoteIdentifiers ?
  3359. $DB->quoteIdentifier($obj->tableName()) :
  3360. $obj->tableName();
  3361. $dbPrefix = '';
  3362. if (strlen($obj->_database) && in_array($DB->dsn['phptype'], array('mysql', 'mysqli'))) {
  3363. $dbPrefix = ($quoteIdentifiers
  3364. ? $DB->quoteIdentifier($obj->_database)
  3365. : $obj->_database) . '.';
  3366. }
  3367. // if they are the same, then dont add a prefix...
  3368. if ($obj->_database == $this->_database) {
  3369. $dbPrefix = '';
  3370. }
  3371. // as far as we know only mysql supports database prefixes..
  3372. // prefixing the database name is now the default behaviour,
  3373. // as it enables joining mutiple columns from multiple databases...
  3374. // prefix database (quoted if neccessary..)
  3375. $objTable = $dbPrefix . $objTable;
  3376. $cond = '';
  3377. // if obj only a dataobject - eg. no extended class has been defined..
  3378. // it obvioulsy cant work out what child elements might exist...
  3379. // until we get on the fly querying of tables..
  3380. // note: we have already checked that it is_a(db_dataobject earlier)
  3381. if (strtolower(get_class($obj)) != 'db_dataobject') {
  3382. // now add where conditions for anything that is set in the object
  3383. $items = $obj->table();
  3384. // will return an array if no items..
  3385. // only fail if we where expecting it to work (eg. not joined on a array)
  3386. if (!$items) {
  3387. $this->raiseError(
  3388. "joinAdd: No table definition for {$obj->tableName()}",
  3389. DB_DATAOBJECT_ERROR_INVALIDCONFIG
  3390. );
  3391. return false;
  3392. }
  3393. $ignore_null = !isset($options['disable_null_strings'])
  3394. || !is_string($options['disable_null_strings'])
  3395. || strtolower($options['disable_null_strings']) !== 'full';
  3396. foreach ($items as $k => $v) {
  3397. if (!isset($obj->$k) && $ignore_null) {
  3398. continue;
  3399. }
  3400. $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
  3401. if (DB_DataObject::_is_null($obj, $k)) {
  3402. $obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
  3403. continue;
  3404. }
  3405. if ($v & DB_DATAOBJECT_STR) {
  3406. $obj->whereAdd("{$joinAs}.{$kSql} = " . $this->_quote((string)(
  3407. ($v & DB_DATAOBJECT_BOOL) ?
  3408. // this is thanks to the braindead idea of postgres to
  3409. // use t/f for boolean.
  3410. (($obj->$k === 'f') ? 0 : (int)(bool)$obj->$k) :
  3411. $obj->$k
  3412. )));
  3413. continue;
  3414. }
  3415. if (is_numeric($obj->$k)) {
  3416. $obj->whereAdd("{$joinAs}.{$kSql} = {$obj->$k}");
  3417. continue;
  3418. }
  3419. if (is_object($obj->$k) && is_a($obj->$k, 'DB_DataObject_Cast')) {
  3420. $value = $obj->$k->toString($v, $DB);
  3421. if ((new PEAR)->isError($value)) {
  3422. $this->raiseError($value->getMessage(), DB_DATAOBJECT_ERROR_INVALIDARG);
  3423. return false;
  3424. }
  3425. $obj->whereAdd("{$joinAs}.{$kSql} = $value");
  3426. continue;
  3427. }
  3428. /* this is probably an error condition! */
  3429. $obj->whereAdd("{$joinAs}.{$kSql} = 0");
  3430. }
  3431. if ($this->_query === false) {
  3432. $this->raiseError(
  3433. "joinAdd can not be run from a object that has had a query run on it,
  3434. clone the object or create a new one and use setFrom()",
  3435. DB_DATAOBJECT_ERROR_INVALIDARGS
  3436. );
  3437. return false;
  3438. }
  3439. }
  3440. // and finally merge the whereAdd from the child..
  3441. if ($obj->_query['condition']) {
  3442. $cond = preg_replace('/^\sWHERE/i', '', $obj->_query['condition']);
  3443. if (!$useWhereAsOn) {
  3444. $this->whereAdd($cond);
  3445. }
  3446. }
  3447. // nested (join of joined objects..)
  3448. $appendJoin = '';
  3449. if ($obj->_join) {
  3450. // postgres allows nested queries, with ()'s
  3451. // not sure what the results are with other databases..
  3452. // may be unpredictable..
  3453. if (in_array($DB->dsn["phptype"], array('pgsql'))) {
  3454. $objTable = "($objTable {$obj->_join})";
  3455. } else {
  3456. $appendJoin = $obj->_join;
  3457. }
  3458. }
  3459. // fix for #2216
  3460. // add the joinee object's conditions to the ON clause instead of the WHERE clause
  3461. if ($useWhereAsOn && strlen($cond)) {
  3462. $appendJoin = ' AND ' . $cond . ' ' . $appendJoin;
  3463. }
  3464. $table = $this->tableName();
  3465. if ($quoteIdentifiers) {
  3466. $joinAs = $DB->quoteIdentifier($joinAs);
  3467. $table = $DB->quoteIdentifier($table);
  3468. $ofield = (is_array($ofield)) ? array_map(array($DB, 'quoteIdentifier'), $ofield) : $DB->quoteIdentifier($ofield);
  3469. $tfield = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield);
  3470. }
  3471. // add database prefix if they are different databases
  3472. $fullJoinAs = '';
  3473. $addJoinAs = ($quoteIdentifiers ? $DB->quoteIdentifier($obj->tableName()) : $obj->tableName()) != $joinAs;
  3474. if ($addJoinAs) {
  3475. // join table a AS b - is only supported by a few databases and is probably not needed
  3476. // , however since it makes the whole Statement alot clearer we are leaving it in
  3477. // for those databases.
  3478. $fullJoinAs = in_array($DB->dsn["phptype"], array('mysql', 'mysqli', 'pgsql')) ? "AS {$joinAs}" : $joinAs;
  3479. } else {
  3480. // if
  3481. $joinAs = $dbPrefix . $joinAs;
  3482. }
  3483. switch ($joinType) {
  3484. case 'INNER':
  3485. case 'LEFT':
  3486. case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
  3487. // Feature Request #4266 - Allow joins with multiple keys
  3488. $jadd = "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
  3489. //$this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
  3490. if (is_array($ofield)) {
  3491. $key_count = count($ofield);
  3492. for ($i = 0; $i < $key_count; $i++) {
  3493. if ($i == 0) {
  3494. $jadd .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
  3495. } else {
  3496. $jadd .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
  3497. }
  3498. }
  3499. $jadd .= ' ' . $appendJoin . ' ';
  3500. } else {
  3501. $jadd .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
  3502. }
  3503. // jadd avaliable for debugging join build.
  3504. //echo $jadd ."\n";
  3505. $this->_join .= $jadd;
  3506. break;
  3507. case '': // this is just a standard multitable select..
  3508. $this->_join .= "\n , {$objTable} {$fullJoinAs} {$appendJoin}";
  3509. $this->whereAdd("{$joinAs}.{$ofield}={$table}.{$tfield}");
  3510. }
  3511. return true;
  3512. }
  3513. /**
  3514. * Adds multiple Columns or objects to select with formating.
  3515. *
  3516. * $object->selectAs(null); // adds "table.colnameA as colnameA,table.colnameB as colnameB,......"
  3517. * // note with null it will also clear the '*' default select
  3518. * $object->selectAs(array('a','b'),'%s_x'); // adds "a as a_x, b as b_x"
  3519. * $object->selectAs(array('a','b'),'ddd_%s','ccc'); // adds "ccc.a as ddd_a, ccc.b as ddd_b"
  3520. * $object->selectAdd($object,'prefix_%s'); // calls $object->get_table and adds it all as
  3521. * objectTableName.colnameA as prefix_colnameA
  3522. *
  3523. * @param array|object|null the array or object to take column names from.
  3524. * @param string $format
  3525. * @param bool $tableName
  3526. * @return bool|void
  3527. * @access public
  3528. */
  3529. public function selectAs($from = null, $format = '%s', $tableName = false)
  3530. {
  3531. global $_DB_DATAOBJECT;
  3532. if ($this->_query === false) {
  3533. $this->raiseError(
  3534. "You cannot do two queries on the same object (copy it before finding)",
  3535. DB_DATAOBJECT_ERROR_INVALIDARGS
  3536. );
  3537. return false;
  3538. }
  3539. if ($from === null) {
  3540. // blank the '*'
  3541. $this->selectAdd();
  3542. $from = $this;
  3543. }
  3544. $table = $this->tableName();
  3545. if (is_object($from)) {
  3546. $table = $from->tableName();
  3547. $from = array_keys($from->table());
  3548. }
  3549. if ($tableName !== false) {
  3550. $table = $tableName;
  3551. }
  3552. $s = '%s';
  3553. if (!empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers'])) {
  3554. $this->_connect();
  3555. $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  3556. $s = $DB->quoteIdentifier($s);
  3557. $format = $DB->quoteIdentifier($format);
  3558. }
  3559. foreach ($from as $k) {
  3560. $this->selectAdd(sprintf("{$s}.{$s} as {$format}", $table, $k, $k));
  3561. }
  3562. $this->_query['data_select'] .= "\n";
  3563. }
  3564. /**
  3565. * Factory method for calling DB_DataObject_Cast
  3566. *
  3567. * if used with 1 argument DB_DataObject_Cast::sql($value) is called
  3568. *
  3569. * if used with 2 arguments DB_DataObject_Cast::$value($callvalue) is called
  3570. * valid first arguments are: blob, string, date, sql
  3571. *
  3572. * eg. $member->updated = $member->sqlValue('NOW()');
  3573. *
  3574. *
  3575. * might handle more arguments for escaping later...
  3576. *
  3577. *
  3578. * @param string $value (or type if used with 2 arguments)
  3579. * @return mixed
  3580. */
  3581. public function sqlValue($value)
  3582. {
  3583. $method = 'sql';
  3584. if (func_num_args() == 2) {
  3585. $method = $value;
  3586. $value = func_get_arg(1);
  3587. }
  3588. //require_once 'DB/DataObject/Cast.php';
  3589. require_once 'Cast.php';
  3590. return call_user_func(array('DB_DataObject_Cast', $method), $value);
  3591. }
  3592. /* ----------------------- Debugger ------------------ */
  3593. /**
  3594. * Copies items that are in the table definitions from an
  3595. * array or object into the current object
  3596. * will not override key values.
  3597. *
  3598. *
  3599. * @param array | object $from
  3600. * @param string $format eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
  3601. * @param boolean $skipEmpty (dont assign empty values if a column is empty (eg. '' / 0 etc...)
  3602. * @access public
  3603. * @return array|true
  3604. */
  3605. public function setFrom($from, $format = '%s', $skipEmpty = false)
  3606. {
  3607. global $_DB_DATAOBJECT;
  3608. $keys = $this->keys();
  3609. $items = $this->table();
  3610. if (!$items) {
  3611. $this->raiseError(
  3612. "setFrom:Could not find table definition for {$this->tableName()}",
  3613. DB_DATAOBJECT_ERROR_INVALIDCONFIG
  3614. );
  3615. return null;
  3616. }
  3617. $overload_return = array();
  3618. foreach (array_keys($items) as $k) {
  3619. if (in_array($k, $keys)) {
  3620. continue; // dont overwrite keys
  3621. }
  3622. if (!$k) {
  3623. continue; // ignore empty keys!!! what
  3624. }
  3625. $chk = is_object($from) &&
  3626. (
  3627. version_compare(phpversion(), "5.1.0", ">=") ?
  3628. property_exists($from, sprintf($format, $k)) : // php5.1
  3629. array_key_exists(sprintf($format, $k), get_class_vars($from)) //older
  3630. );
  3631. // if from has property ($format($k)
  3632. if ($chk) {
  3633. $kk = (strtolower($k) == 'from') ? '_from' : $k;
  3634. if (method_exists($this, 'set' . $kk)) {
  3635. $ret = $this->{'set' . $kk}($from->{sprintf($format, $k)});
  3636. if (is_string($ret)) {
  3637. $overload_return[$k] = $ret;
  3638. }
  3639. continue;
  3640. }
  3641. $this->$k = $from->{sprintf($format, $k)};
  3642. continue;
  3643. }
  3644. if (is_object($from)) {
  3645. continue;
  3646. }
  3647. if (empty($from[sprintf($format, $k)]) && $skipEmpty) {
  3648. continue;
  3649. }
  3650. if (!isset($from[sprintf($format, $k)]) && !DB_DataObject::_is_null($from, sprintf($format, $k))) {
  3651. continue;
  3652. }
  3653. $kk = (strtolower($k) == 'from') ? '_from' : $k;
  3654. if (method_exists($this, 'set' . $kk)) {
  3655. $ret = $this->{'set' . $kk}($from[sprintf($format, $k)]);
  3656. if (is_string($ret)) {
  3657. $overload_return[$k] = $ret;
  3658. }
  3659. continue;
  3660. }
  3661. $val = $from[sprintf($format, $k)];
  3662. if (is_a($val, 'DB_DataObject_Cast')) {
  3663. $this->$k = $val;
  3664. continue;
  3665. }
  3666. if (is_object($val) || is_array($val)) {
  3667. continue;
  3668. }
  3669. $ret = $this->fromValue($k, $val);
  3670. if ($ret !== true) {
  3671. $overload_return[$k] = 'Not A Valid Value';
  3672. }
  3673. //$this->$k = $from[sprintf($format,$k)];
  3674. }
  3675. if ($overload_return) {
  3676. return $overload_return;
  3677. }
  3678. return true;
  3679. }
  3680. /**
  3681. * standard set* implementation.
  3682. *
  3683. * takes data and uses it to set dates/strings etc.
  3684. * normally called from __call..
  3685. *
  3686. * Current supports
  3687. * date = using (standard time format, or unixtimestamp).... so you could create a method :
  3688. * function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
  3689. *
  3690. * time = using strtotime
  3691. * datetime = using same as date - accepts iso standard or unixtimestamp.
  3692. * string = typecast only..
  3693. *
  3694. * TODO: add formater:: eg. d/m/Y for date! ???
  3695. *
  3696. * @param string column of database
  3697. * @param mixed value to assign
  3698. *
  3699. * @return true| false (False on error)
  3700. * @access public
  3701. * @see DB_DataObject::_call
  3702. */
  3703. public function fromValue($col, $value)
  3704. {
  3705. global $_DB_DATAOBJECT;
  3706. $options = $_DB_DATAOBJECT['CONFIG'];
  3707. $cols = $this->table();
  3708. // dont know anything about this col..
  3709. if (!isset($cols[$col]) || is_a($value, 'DB_DataObject_Cast')) {
  3710. $this->$col = $value;
  3711. return true;
  3712. }
  3713. //echo "FROM VALUE $col, {$cols[$col]}, $value\n";
  3714. switch (true) {
  3715. // set to null and column is can be null...
  3716. case ((!($cols[$col] & DB_DATAOBJECT_NOTNULL)) && DB_DataObject::_is_null($value, false)):
  3717. case (is_object($value) && is_a($value, 'DB_DataObject_Cast')):
  3718. $this->$col = $value;
  3719. return true;
  3720. // fail on setting null on a not null field..
  3721. case (($cols[$col] & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($value, false)):
  3722. return false;
  3723. case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
  3724. // empty values get set to '' (which is inserted/updated as NULl
  3725. if (!$value) {
  3726. $this->$col = '';
  3727. }
  3728. if (is_numeric($value)) {
  3729. $this->$col = date('Y-m-d H:i:s', $value);
  3730. return true;
  3731. }
  3732. // eak... - no way to validate date time otherwise...
  3733. $this->$col = (string)$value;
  3734. return true;
  3735. case ($cols[$col] & DB_DATAOBJECT_DATE):
  3736. // empty values get set to '' (which is inserted/updated as NULl
  3737. if (!$value) {
  3738. $this->$col = '';
  3739. return true;
  3740. }
  3741. if (is_numeric($value)) {
  3742. $this->$col = date('Y-m-d', $value);
  3743. return true;
  3744. }
  3745. // try date!!!!
  3746. require_once 'Date.php';
  3747. $x = new Date($value);
  3748. $this->$col = $x->format("%Y-%m-%d");
  3749. return true;
  3750. case ($cols[$col] & DB_DATAOBJECT_TIME):
  3751. // empty values get set to '' (which is inserted/updated as NULl
  3752. if (!$value) {
  3753. $this->$col = '';
  3754. }
  3755. $guess = strtotime($value);
  3756. if ($guess != -1) {
  3757. $this->$col = date('H:i:s', $guess);
  3758. return $return = true;
  3759. }
  3760. // otherwise an error in type...
  3761. return false;
  3762. case ($cols[$col] & DB_DATAOBJECT_STR):
  3763. $this->$col = (string)$value;
  3764. return true;
  3765. // todo : floats numerics and ints...
  3766. default:
  3767. $this->$col = $value;
  3768. return true;
  3769. }
  3770. }
  3771. /**
  3772. * Returns an associative array from the current data
  3773. * (kind of oblivates the idea behind DataObjects, but
  3774. * is usefull if you use it with things like QuickForms.
  3775. *
  3776. * you can use the format to return things like user[key]
  3777. * by sending it $object->toArray('user[%s]')
  3778. *
  3779. * will also return links converted to arrays.
  3780. *
  3781. * @param string sprintf format for array
  3782. * @param bool||number [true = elemnts that have a value set],
  3783. * [false = table + returned colums] ,
  3784. * [0 = returned columsn only]
  3785. *
  3786. * @access public
  3787. * @return array of key => value for row
  3788. */
  3789. public function toArray($format = '%s', $hideEmpty = false)
  3790. {
  3791. global $_DB_DATAOBJECT;
  3792. // we use false to ignore sprintf.. (speed up..)
  3793. $format = $format == '%s' ? false : $format;
  3794. $ret = array();
  3795. $rf = ($this->_resultFields !== false) ? $this->_resultFields :
  3796. (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ?
  3797. $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] : false);
  3798. $ar = ($rf !== false) ?
  3799. (($hideEmpty === 0) ? $rf : array_merge($rf, $this->table())) :
  3800. $this->table();
  3801. foreach ($ar as $k => $v) {
  3802. if (!isset($this->$k)) {
  3803. if (!$hideEmpty) {
  3804. $ret[$format === false ? $k : sprintf($format, $k)] = '';
  3805. }
  3806. continue;
  3807. }
  3808. // call the overloaded getXXXX() method. - except getLink and getLinks
  3809. if (method_exists($this, 'get' . $k) && !in_array(strtolower($k), array('links', 'link'))) {
  3810. $ret[$format === false ? $k : sprintf($format, $k)] = $this->{'get' . $k}();
  3811. continue;
  3812. }
  3813. // should this call toValue() ???
  3814. $ret[$format === false ? $k : sprintf($format, $k)] = $this->$k;
  3815. }
  3816. if (!$this->_link_loaded) {
  3817. return $ret;
  3818. }
  3819. foreach ($this->_link_loaded as $k) {
  3820. $ret[$format === false ? $k : sprintf($format, $k)] = $this->$k->toArray();
  3821. }
  3822. return $ret;
  3823. }
  3824. /**
  3825. * validate the values of the object (usually prior to inserting/updating..)
  3826. *
  3827. * Note: This was always intended as a simple validation routine.
  3828. * It lacks understanding of field length, whether you are inserting or updating (and hence null key values)
  3829. *
  3830. * This should be moved to another class: DB_DataObject_Validate
  3831. * FEEL FREE TO SEND ME YOUR VERSION FOR CONSIDERATION!!!
  3832. *
  3833. * Usage:
  3834. * if (is_array($ret = $obj->validate())) { ... there are problems with the data ... }
  3835. *
  3836. * Logic:
  3837. * - defaults to only testing strings/numbers if numbers or strings are the correct type and null values are correct
  3838. * - validate Column methods : "validate{ROWNAME}()" are called if they are defined.
  3839. * These methods should return
  3840. * true = everything ok
  3841. * false|object = something is wrong!
  3842. *
  3843. * - This method loads and uses the PEAR Validate Class.
  3844. *
  3845. *
  3846. * @access public
  3847. * @return array|bool
  3848. */
  3849. public function validate()
  3850. {
  3851. global $_DB_DATAOBJECT;
  3852. require_once 'Validate.php';
  3853. $table = $this->table();
  3854. $ret = array();
  3855. $seq = $this->sequenceKey();
  3856. $options = $_DB_DATAOBJECT['CONFIG'];
  3857. foreach ($table as $key => $val) {
  3858. // call user defined validation always...
  3859. $method = "Validate" . ucfirst($key);
  3860. if (method_exists($this, $method)) {
  3861. $ret[$key] = $this->$method();
  3862. continue;
  3863. }
  3864. // if not null - and it's not set.......
  3865. if ($val & DB_DATAOBJECT_NOTNULL && DB_DataObject::_is_null($this, $key)) {
  3866. // dont check empty sequence key values..
  3867. if (($key == $seq[0]) && ($seq[1] == true)) {
  3868. continue;
  3869. }
  3870. $ret[$key] = false;
  3871. continue;
  3872. }
  3873. if (DB_DataObject::_is_null($this, $key)) {
  3874. if ($val & DB_DATAOBJECT_NOTNULL) {
  3875. $this->debug("'null' field used for '$key', but it is defined as NOT NULL", 'VALIDATION', 4);
  3876. $ret[$key] = false;
  3877. continue;
  3878. }
  3879. continue;
  3880. }
  3881. // ignore things that are not set. ?
  3882. if (!isset($this->$key)) {
  3883. continue;
  3884. }
  3885. // if the string is empty.. assume it is ok..
  3886. if (!is_object($this->$key) && !is_array($this->$key) && !strlen((string)$this->$key)) {
  3887. continue;
  3888. }
  3889. // dont try and validate cast objects - assume they are problably ok..
  3890. if (is_object($this->$key) && is_a($this->$key, 'DB_DataObject_Cast')) {
  3891. continue;
  3892. }
  3893. // at this point if you have set something to an object, and it's not expected
  3894. // the Validate will probably break!!... - rightly so! (your design is broken,
  3895. // so issuing a runtime error like PEAR_Error is probably not appropriate..
  3896. switch (true) {
  3897. // todo: date time.....
  3898. case ($val & DB_DATAOBJECT_STR):
  3899. $ret[$key] = (new Validate)->string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
  3900. break;
  3901. case ($val & DB_DATAOBJECT_INT):
  3902. $ret[$key] = (new Validate)->number($this->$key, array('decimal' => '.'));
  3903. break;
  3904. }
  3905. }
  3906. // if any of the results are false or an object (eg. PEAR_Error).. then return the array..
  3907. foreach ($ret as $key => $val) {
  3908. if ($val !== true) {
  3909. return $ret;
  3910. }
  3911. }
  3912. return true; // everything is OK.
  3913. }
  3914. /**
  3915. * Gets the DB object related to an object - so you can use funky peardb stuf with it :)
  3916. *
  3917. * @access public
  3918. * @return bool|object
  3919. */
  3920. public function getDatabaseConnection()
  3921. {
  3922. global $_DB_DATAOBJECT;
  3923. if (($e = $this->_connect()) !== true) {
  3924. return $e;
  3925. }
  3926. if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
  3927. $r = false;
  3928. return $r;
  3929. }
  3930. return $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
  3931. }
  3932. /**
  3933. * Gets the DB result object related to the objects active query
  3934. * - so you can use funky pear stuff with it - like pager for example.. :)
  3935. *
  3936. * @access public
  3937. * @return bool|object
  3938. */
  3939. public function getDatabaseResult()
  3940. {
  3941. global $_DB_DATAOBJECT;
  3942. $this->_connect();
  3943. if (!isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
  3944. $r = false;
  3945. return $r;
  3946. }
  3947. return $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
  3948. }
  3949. /**
  3950. * Overload Extension support
  3951. * - enables setCOLNAME/getCOLNAME
  3952. * if you define a set/get method for the item it will be called.
  3953. * otherwise it will just return/set the value.
  3954. * NOTE this currently means that a few Names are NO-NO's
  3955. * eg. links,link,linksarray, from, Databaseconnection,databaseresult
  3956. *
  3957. * note
  3958. * - set is automatically called by setFrom.
  3959. * - get is automatically called by toArray()
  3960. *
  3961. * setters return true on success. = strings on failure
  3962. * getters return the value!
  3963. *
  3964. * this fires off trigger_error - if any problems.. pear_error,
  3965. * has problems with 4.3.2RC2 here
  3966. *
  3967. * @access public
  3968. * @param $method
  3969. * @param $params
  3970. * @param $return
  3971. * @return true?
  3972. * @throws ReflectionException
  3973. * @see overload
  3974. */
  3975. public function _call($method, $params, &$return)
  3976. {
  3977. //$this->debug("ATTEMPTING OVERLOAD? $method");
  3978. // ignore constructors : - mm
  3979. if (strtolower($method) == strtolower(get_class($this))) {
  3980. return true;
  3981. }
  3982. $type = strtolower(substr($method, 0, 3));
  3983. $class = get_class($this);
  3984. if (($type != 'set') && ($type != 'get')) {
  3985. return false;
  3986. }
  3987. // deal with naming conflick of setFrom = this is messy ATM!
  3988. if (strtolower($method) == 'set_from') {
  3989. $return = $this->toValue('from', isset($params[0]) ? $params[0] : null);
  3990. return true;
  3991. }
  3992. $element = substr($method, 3);
  3993. // dont you just love php's case insensitivity!!!!
  3994. $array = array_keys(get_class_vars($class));
  3995. /* php5 version which segfaults on 5.0.3 */
  3996. if (class_exists('ReflectionClass')) {
  3997. $reflection = new ReflectionClass($class);
  3998. $array = array_keys($reflection->getdefaultProperties());
  3999. }
  4000. if (!in_array($element, $array)) {
  4001. // munge case
  4002. foreach ($array as $k) {
  4003. $case[strtolower($k)] = $k;
  4004. }
  4005. if ((substr(phpversion(), 0, 1) == 5) && isset($case[strtolower($element)])) {
  4006. trigger_error("PHP5 set/get calls should match the case of the variable", E_USER_WARNING);
  4007. $element = strtolower($element);
  4008. }
  4009. // does it really exist?
  4010. if (!isset($case[$element])) {
  4011. return false;
  4012. }
  4013. // use the mundged case
  4014. $element = $case[$element]; // real case !
  4015. }
  4016. if ($type == 'get') {
  4017. $return = $this->toValue($element, isset($params[0]) ? $params[0] : null);
  4018. return true;
  4019. }
  4020. $return = $this->fromValue($element, $params[0]);
  4021. return true;
  4022. }
  4023. /**
  4024. * standard get* implementation.
  4025. *
  4026. * with formaters..
  4027. * supported formaters:
  4028. * date/time : %d/%m/%Y (eg. php strftime) or pear::Date
  4029. * numbers : %02d (eg. sprintf)
  4030. * NOTE you will get unexpected results with times like 0000-00-00 !!!
  4031. *
  4032. *
  4033. *
  4034. * @param string column of database
  4035. * @param format foramt
  4036. *
  4037. * @return string|true
  4038. * @access public
  4039. * @see DB_DataObject::_call(),strftime(),Date::format()
  4040. */
  4041. public function toValue($col, $format = null)
  4042. {
  4043. if (is_null($format)) {
  4044. return $this->$col;
  4045. }
  4046. $cols = $this->table();
  4047. switch (true) {
  4048. case (($cols[$col] & DB_DATAOBJECT_DATE) && ($cols[$col] & DB_DATAOBJECT_TIME)):
  4049. if (!$this->$col) {
  4050. return '';
  4051. }
  4052. $guess = strtotime($this->$col);
  4053. if ($guess != -1) {
  4054. return strftime($format, $guess);
  4055. }
  4056. // eak... - no way to validate date time otherwise...
  4057. return $this->$col;
  4058. case ($cols[$col] & DB_DATAOBJECT_DATE):
  4059. if (!$this->$col) {
  4060. return '';
  4061. }
  4062. $guess = strtotime($this->$col);
  4063. if ($guess != -1) {
  4064. return strftime($format, $guess);
  4065. }
  4066. // try date!!!!
  4067. require_once 'Date.php';
  4068. $x = new Date($this->$col);
  4069. return $x->format($format);
  4070. case ($cols[$col] & DB_DATAOBJECT_TIME):
  4071. if (!$this->$col) {
  4072. return '';
  4073. }
  4074. $guess = strtotime($this->$col);
  4075. if ($guess > -1) {
  4076. return strftime($format, $guess);
  4077. }
  4078. // otherwise an error in type...
  4079. return $this->$col;
  4080. case ($cols[$col] & DB_DATAOBJECT_MYSQLTIMESTAMP):
  4081. if (!$this->$col) {
  4082. return '';
  4083. }
  4084. require_once 'Date.php';
  4085. $x = new Date($this->$col);
  4086. return $x->format($format);
  4087. case ($cols[$col] & DB_DATAOBJECT_BOOL):
  4088. if ($cols[$col] & DB_DATAOBJECT_STR) {
  4089. // it's a 't'/'f' !
  4090. return ($this->$col === 't');
  4091. }
  4092. return (bool)$this->$col;
  4093. default:
  4094. return sprintf($format, $this->col);
  4095. }
  4096. }
  4097. /**
  4098. * autoload Class relating to a table
  4099. * (deprecited - use ::factory)
  4100. *
  4101. * @param string $table table
  4102. * @access private
  4103. * @return string classname on Success
  4104. */
  4105. public function staticAutoloadTable($table)
  4106. {
  4107. global $_DB_DATAOBJECT;
  4108. if (empty($_DB_DATAOBJECT['CONFIG'])) {
  4109. DB_DataObject::_loadConfig();
  4110. }
  4111. $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
  4112. $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
  4113. $class = $p . preg_replace('/[^A-Z0-9]/i', '_', ucfirst($table));
  4114. $ce = substr(phpversion(), 0, 1) > 4 ? class_exists($class, false) : class_exists($class);
  4115. $class = $ce ? $class : DB_DataObject::_autoloadClass($class);
  4116. return $class;
  4117. }
  4118. /* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
  4119. public function _get_table()
  4120. {
  4121. return $this->table();
  4122. }
  4123. public function _get_keys()
  4124. {
  4125. return $this->keys();
  4126. }
  4127. }
  4128. // technially 4.3.2RC1 was broken!!
  4129. // looks like 4.3.3 may have problems too....
  4130. if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
  4131. if ((phpversion() != '4.3.2-RC1') && (version_compare(phpversion(), "4.3.1") > 0)) {
  4132. if (version_compare(phpversion(), "5") < 0) {
  4133. overload('DB_DataObject');
  4134. }
  4135. $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;
  4136. }
  4137. }