DataObject.php 166 KB

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