DataObject.php 170 KB

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