DataObject.php 165 KB

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