DataObject.php 172 KB

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