adodb.inc.php 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812
  1. <?php
  2. /*
  3. * Set tabs to 4 for best viewing.
  4. *
  5. * Latest version is available at http://adodb.sourceforge.net
  6. *
  7. * This is the main include file for ADOdb.
  8. * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
  9. *
  10. * The ADOdb files are formatted so that doxygen can be used to generate documentation.
  11. * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
  12. */
  13. /**
  14. \mainpage
  15. @version V4.60 24 Jan 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my). All rights reserved.
  16. Released under both BSD license and Lesser GPL library license. You can choose which license
  17. you prefer.
  18. PHP's database access functions are not standardised. This creates a need for a database
  19. class library to hide the differences between the different database API's (encapsulate
  20. the differences) so we can easily switch databases.
  21. We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
  22. Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
  23. ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
  24. other databases via ODBC.
  25. Latest Download at http://php.weblogs.com/adodb<br>
  26. Manual is at http://php.weblogs.com/adodb_manual
  27. */
  28. if (!defined('_ADODB_LAYER')) {
  29. define('_ADODB_LAYER',1);
  30. //==============================================================================================
  31. // CONSTANT DEFINITIONS
  32. //==============================================================================================
  33. /**
  34. * Set ADODB_DIR to the directory where this file resides...
  35. * This constant was formerly called $ADODB_RootPath
  36. */
  37. if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
  38. //==============================================================================================
  39. // GLOBAL VARIABLES
  40. //==============================================================================================
  41. GLOBAL
  42. $ADODB_vers, // database version
  43. $ADODB_COUNTRECS, // count number of records returned - slows down query
  44. $ADODB_CACHE_DIR, // directory to cache recordsets
  45. $ADODB_EXTENSION, // ADODB extension installed
  46. $ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
  47. $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
  48. //==============================================================================================
  49. // GLOBAL SETUP
  50. //==============================================================================================
  51. $ADODB_EXTENSION = defined('ADODB_EXTENSION');
  52. //********************************************************//
  53. /*
  54. Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
  55. Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
  56. 0 = ignore empty fields. All empty fields in array are ignored.
  57. 1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
  58. 2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
  59. 3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values.
  60. */
  61. define('ADODB_FORCE_IGNORE',0);
  62. define('ADODB_FORCE_NULL',1);
  63. define('ADODB_FORCE_EMPTY',2);
  64. define('ADODB_FORCE_VALUE',3);
  65. //********************************************************//
  66. if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
  67. define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
  68. // allow [ ] @ ` " and . in table names
  69. define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
  70. // prefetching used by oracle
  71. if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
  72. /*
  73. Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
  74. This currently works only with mssql, odbc, oci8po and ibase derived drivers.
  75. 0 = assoc lowercase field names. $rs->fields['orderid']
  76. 1 = assoc uppercase field names. $rs->fields['ORDERID']
  77. 2 = use native-case field names. $rs->fields['OrderID']
  78. */
  79. define('ADODB_FETCH_DEFAULT',0);
  80. define('ADODB_FETCH_NUM',1);
  81. define('ADODB_FETCH_ASSOC',2);
  82. define('ADODB_FETCH_BOTH',3);
  83. if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
  84. // PHP's version scheme makes converting to numbers difficult - workaround
  85. $_adodb_ver = (float) PHP_VERSION;
  86. if ($_adodb_ver >= 5.0) {
  87. define('ADODB_PHPVER',0x5000);
  88. } else if ($_adodb_ver > 4.299999) { # 4.3
  89. define('ADODB_PHPVER',0x4300);
  90. } else if ($_adodb_ver > 4.199999) { # 4.2
  91. define('ADODB_PHPVER',0x4200);
  92. } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
  93. define('ADODB_PHPVER',0x4050);
  94. } else {
  95. define('ADODB_PHPVER',0x4000);
  96. }
  97. }
  98. //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  99. /**
  100. Accepts $src and $dest arrays, replacing string $data
  101. */
  102. function ADODB_str_replace($src, $dest, $data)
  103. {
  104. if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
  105. $s = reset($src);
  106. $d = reset($dest);
  107. while ($s !== false) {
  108. $data = str_replace($s,$d,$data);
  109. $s = next($src);
  110. $d = next($dest);
  111. }
  112. return $data;
  113. }
  114. function ADODB_Setup()
  115. {
  116. GLOBAL
  117. $ADODB_vers, // database version
  118. $ADODB_COUNTRECS, // count number of records returned - slows down query
  119. $ADODB_CACHE_DIR, // directory to cache recordsets
  120. $ADODB_FETCH_MODE,
  121. $ADODB_FORCE_TYPE;
  122. $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
  123. $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
  124. if (!isset($ADODB_CACHE_DIR)) {
  125. $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
  126. } else {
  127. // do not accept url based paths, eg. http:/ or ftp:/
  128. if (strpos($ADODB_CACHE_DIR,'://') !== false)
  129. die("Illegal path http:// or ftp://");
  130. }
  131. // Initialize random number generator for randomizing cache flushes
  132. srand(((double)microtime())*1000000);
  133. /**
  134. * ADODB version as a string.
  135. */
  136. $ADODB_vers = 'V4.60 24 Jan 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
  137. /**
  138. * Determines whether recordset->RecordCount() is used.
  139. * Set to false for highest performance -- RecordCount() will always return -1 then
  140. * for databases that provide "virtual" recordcounts...
  141. */
  142. if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
  143. }
  144. //==============================================================================================
  145. // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
  146. //==============================================================================================
  147. ADODB_Setup();
  148. //==============================================================================================
  149. // CLASS ADOFieldObject
  150. //==============================================================================================
  151. /**
  152. * Helper class for FetchFields -- holds info on a column
  153. */
  154. class ADOFieldObject {
  155. var $name = '';
  156. var $max_length=0;
  157. var $type="";
  158. // additional fields by dannym... (danny_milo@yahoo.com)
  159. var $not_null = false;
  160. // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
  161. // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
  162. var $has_default = false; // this one I have done only in mysql and postgres for now ...
  163. // others to come (dannym)
  164. var $default_value; // default, if any, and supported. Check has_default first.
  165. }
  166. function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
  167. {
  168. //print "Errorno ($fn errno=$errno m=$errmsg) ";
  169. $thisConnection->_transOK = false;
  170. if ($thisConnection->_oldRaiseFn) {
  171. $fn = $thisConnection->_oldRaiseFn;
  172. $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
  173. }
  174. }
  175. //==============================================================================================
  176. // CLASS ADOConnection
  177. //==============================================================================================
  178. /**
  179. * Connection object. For connecting to databases, and executing queries.
  180. */
  181. class ADOConnection {
  182. //
  183. // PUBLIC VARS
  184. //
  185. var $dataProvider = 'native';
  186. var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
  187. var $database = ''; /// Name of database to be used.
  188. var $host = ''; /// The hostname of the database server
  189. var $user = ''; /// The username which is used to connect to the database server.
  190. var $password = ''; /// Password for the username. For security, we no longer store it.
  191. var $debug = false; /// if set to true will output sql statements
  192. var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
  193. var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
  194. var $substr = 'substr'; /// substring operator
  195. var $length = 'length'; /// string length operator
  196. var $random = 'rand()'; /// random function
  197. var $upperCase = 'upper'; /// uppercase function
  198. var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
  199. var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
  200. var $true = '1'; /// string that represents TRUE for a database
  201. var $false = '0'; /// string that represents FALSE for a database
  202. var $replaceQuote = "\\'"; /// string to use to replace quotes
  203. var $nameQuote = '"'; /// string to use to quote identifiers and names
  204. var $charSet=false; /// character set to use - only for interbase, postgres and oci8
  205. var $metaDatabasesSQL = '';
  206. var $metaTablesSQL = '';
  207. var $uniqueOrderBy = false; /// All order by columns have to be unique
  208. var $emptyDate = '&nbsp;';
  209. var $emptyTimeStamp = '&nbsp;';
  210. var $lastInsID = false;
  211. //--
  212. var $hasInsertID = false; /// supports autoincrement ID?
  213. var $hasAffectedRows = false; /// supports affected rows for update/delete?
  214. var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
  215. var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
  216. var $readOnly = false; /// this is a readonly database - used by phpLens
  217. var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
  218. var $hasGenID = false; /// can generate sequences using GenID();
  219. var $hasTransactions = true; /// has transactions
  220. //--
  221. var $genID = 0; /// sequence id used by GenID();
  222. var $raiseErrorFn = false; /// error function to call
  223. var $isoDates = false; /// accepts dates in ISO format
  224. var $cacheSecs = 3600; /// cache for 1 hour
  225. var $sysDate = false; /// name of function that returns the current date
  226. var $sysTimeStamp = false; /// name of function that returns the current timestamp
  227. var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
  228. var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
  229. var $numCacheHits = 0;
  230. var $numCacheMisses = 0;
  231. var $pageExecuteCountRows = true;
  232. var $uniqueSort = false; /// indicates that all fields in order by must be unique
  233. var $leftOuter = false; /// operator to use for left outer join in WHERE clause
  234. var $rightOuter = false; /// operator to use for right outer join in WHERE clause
  235. var $ansiOuter = false; /// whether ansi outer join syntax supported
  236. var $autoRollback = false; // autoRollback on PConnect().
  237. var $poorAffectedRows = false; // affectedRows not working or unreliable
  238. var $fnExecute = false;
  239. var $fnCacheExecute = false;
  240. var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
  241. var $rsPrefix = "ADORecordSet_";
  242. var $autoCommit = true; /// do not modify this yourself - actually private
  243. var $transOff = 0; /// temporarily disable transactions
  244. var $transCnt = 0; /// count of nested transactions
  245. var $fetchMode=false;
  246. //
  247. // PRIVATE VARS
  248. //
  249. var $_oldRaiseFn = false;
  250. var $_transOK = null;
  251. var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
  252. var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
  253. /// then returned by the errorMsg() function
  254. var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
  255. var $_queryID = false; /// This variable keeps the last created result link identifier
  256. var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
  257. var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
  258. var $_evalAll = false;
  259. var $_affected = false;
  260. var $_logsql = false;
  261. /**
  262. * Constructor
  263. */
  264. function ADOConnection()
  265. {
  266. die('Virtual Class -- cannot instantiate');
  267. }
  268. function Version()
  269. {
  270. global $ADODB_vers;
  271. return (float) substr($ADODB_vers,1);
  272. }
  273. /**
  274. Get server version info...
  275. @returns An array with 2 elements: $arr['string'] is the description string,
  276. and $arr[version] is the version (also a string).
  277. */
  278. function ServerInfo()
  279. {
  280. return array('description' => '', 'version' => '');
  281. }
  282. function IsConnected()
  283. {
  284. return !empty($this->_connectionID);
  285. }
  286. function _findvers($str)
  287. {
  288. if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
  289. else return '';
  290. }
  291. /**
  292. * All error messages go through this bottleneck function.
  293. * You can define your own handler by defining the function name in ADODB_OUTP.
  294. */
  295. function outp($msg,$newline=true)
  296. {
  297. global $HTTP_SERVER_VARS,$ADODB_FLUSH,$ADODB_OUTP;
  298. if (defined('ADODB_OUTP')) {
  299. $fn = ADODB_OUTP;
  300. $fn($msg,$newline);
  301. return;
  302. } else if (isset($ADODB_OUTP)) {
  303. $fn = $ADODB_OUTP;
  304. $fn($msg,$newline);
  305. return;
  306. }
  307. if ($newline) $msg .= "<br>\n";
  308. if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']) || !$newline) echo $msg;
  309. else echo strip_tags($msg);
  310. if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
  311. }
  312. function Time()
  313. {
  314. $rs =& $this->_Execute("select $this->sysTimeStamp");
  315. if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
  316. return false;
  317. }
  318. /**
  319. * Connect to database
  320. *
  321. * @param [argHostname] Host to connect to
  322. * @param [argUsername] Userid to login
  323. * @param [argPassword] Associated password
  324. * @param [argDatabaseName] database
  325. * @param [forceNew] force new connection
  326. *
  327. * @return true or false
  328. */
  329. function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
  330. {
  331. if ($argHostname != "") $this->host = $argHostname;
  332. if ($argUsername != "") $this->user = $argUsername;
  333. if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
  334. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  335. $this->_isPersistentConnection = false;
  336. if ($forceNew) {
  337. if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
  338. } else {
  339. if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
  340. }
  341. $err = $this->ErrorMsg();
  342. if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  343. if ($fn = $this->raiseErrorFn)
  344. $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  345. $this->_connectionID = false;
  346. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  347. return false;
  348. }
  349. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  350. {
  351. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
  352. }
  353. /**
  354. * Always force a new connection to database - currently only works with oracle
  355. *
  356. * @param [argHostname] Host to connect to
  357. * @param [argUsername] Userid to login
  358. * @param [argPassword] Associated password
  359. * @param [argDatabaseName] database
  360. *
  361. * @return true or false
  362. */
  363. function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  364. {
  365. return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
  366. }
  367. /**
  368. * Establish persistent connect to database
  369. *
  370. * @param [argHostname] Host to connect to
  371. * @param [argUsername] Userid to login
  372. * @param [argPassword] Associated password
  373. * @param [argDatabaseName] database
  374. *
  375. * @return return true or false
  376. */
  377. function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  378. {
  379. if (defined('ADODB_NEVER_PERSIST'))
  380. return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
  381. if ($argHostname != "") $this->host = $argHostname;
  382. if ($argUsername != "") $this->user = $argUsername;
  383. if ($argPassword != "") $this->password = $argPassword;
  384. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  385. $this->_isPersistentConnection = true;
  386. if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
  387. $err = $this->ErrorMsg();
  388. if (empty($err)) {
  389. $err = "Connection error to server '$argHostname' with user '$argUsername'";
  390. }
  391. if ($fn = $this->raiseErrorFn) {
  392. $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  393. }
  394. $this->_connectionID = false;
  395. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  396. return false;
  397. }
  398. // Format date column in sql string given an input format that understands Y M D
  399. function SQLDate($fmt, $col=false)
  400. {
  401. if (!$col) $col = $this->sysDate;
  402. return $col; // child class implement
  403. }
  404. /**
  405. * Should prepare the sql statement and return the stmt resource.
  406. * For databases that do not support this, we return the $sql. To ensure
  407. * compatibility with databases that do not support prepare:
  408. *
  409. * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
  410. * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
  411. * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
  412. *
  413. * @param sql SQL to send to database
  414. *
  415. * @return return FALSE, or the prepared statement, or the original sql if
  416. * if the database does not support prepare.
  417. *
  418. */
  419. function Prepare($sql)
  420. {
  421. return $sql;
  422. }
  423. /**
  424. * Some databases, eg. mssql require a different function for preparing
  425. * stored procedures. So we cannot use Prepare().
  426. *
  427. * Should prepare the stored procedure and return the stmt resource.
  428. * For databases that do not support this, we return the $sql. To ensure
  429. * compatibility with databases that do not support prepare:
  430. *
  431. * @param sql SQL to send to database
  432. *
  433. * @return return FALSE, or the prepared statement, or the original sql if
  434. * if the database does not support prepare.
  435. *
  436. */
  437. function PrepareSP($sql,$param=true)
  438. {
  439. return $this->Prepare($sql,$param);
  440. }
  441. /**
  442. * PEAR DB Compat
  443. */
  444. function Quote($s)
  445. {
  446. return $this->qstr($s,false);
  447. }
  448. /**
  449. Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
  450. */
  451. function QMagic($s)
  452. {
  453. return $this->qstr($s,get_magic_quotes_gpc());
  454. }
  455. function q(&$s)
  456. {
  457. $s = $this->qstr($s,false);
  458. }
  459. /**
  460. * PEAR DB Compat - do not use internally.
  461. */
  462. function ErrorNative()
  463. {
  464. return $this->ErrorNo();
  465. }
  466. /**
  467. * PEAR DB Compat - do not use internally.
  468. */
  469. function nextId($seq_name)
  470. {
  471. return $this->GenID($seq_name);
  472. }
  473. /**
  474. * Lock a row, will escalate and lock the table if row locking not supported
  475. * will normally free the lock at the end of the transaction
  476. *
  477. * @param $table name of table to lock
  478. * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
  479. */
  480. function RowLock($table,$where)
  481. {
  482. return false;
  483. }
  484. function CommitLock($table)
  485. {
  486. return $this->CommitTrans();
  487. }
  488. function RollbackLock($table)
  489. {
  490. return $this->RollbackTrans();
  491. }
  492. /**
  493. * PEAR DB Compat - do not use internally.
  494. *
  495. * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
  496. * for easy porting :-)
  497. *
  498. * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
  499. * @returns The previous fetch mode
  500. */
  501. function SetFetchMode($mode)
  502. {
  503. $old = $this->fetchMode;
  504. $this->fetchMode = $mode;
  505. if ($old === false) {
  506. global $ADODB_FETCH_MODE;
  507. return $ADODB_FETCH_MODE;
  508. }
  509. return $old;
  510. }
  511. /**
  512. * PEAR DB Compat - do not use internally.
  513. */
  514. function &Query($sql, $inputarr=false)
  515. {
  516. $rs = &$this->Execute($sql, $inputarr);
  517. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  518. return $rs;
  519. }
  520. /**
  521. * PEAR DB Compat - do not use internally
  522. */
  523. function &LimitQuery($sql, $offset, $count, $params=false)
  524. {
  525. $rs = &$this->SelectLimit($sql, $count, $offset, $params);
  526. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  527. return $rs;
  528. }
  529. /**
  530. * PEAR DB Compat - do not use internally
  531. */
  532. function Disconnect()
  533. {
  534. return $this->Close();
  535. }
  536. /*
  537. Returns placeholder for parameter, eg.
  538. $DB->Param('a')
  539. will return ':a' for Oracle, and '?' for most other databases...
  540. For databases that require positioned params, eg $1, $2, $3 for postgresql,
  541. pass in Param(false) before setting the first parameter.
  542. */
  543. function Param($name,$type='C')
  544. {
  545. return '?';
  546. }
  547. /*
  548. InParameter and OutParameter are self-documenting versions of Parameter().
  549. */
  550. function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  551. {
  552. return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
  553. }
  554. /*
  555. */
  556. function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  557. {
  558. return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
  559. }
  560. /*
  561. Usage in oracle
  562. $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
  563. $db->Parameter($stmt,$id,'myid');
  564. $db->Parameter($stmt,$group,'group',64);
  565. $db->Execute();
  566. @param $stmt Statement returned by Prepare() or PrepareSP().
  567. @param $var PHP variable to bind to
  568. @param $name Name of stored procedure variable name to bind to.
  569. @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
  570. @param [$maxLen] Holds an maximum length of the variable.
  571. @param [$type] The data type of $var. Legal values depend on driver.
  572. */
  573. function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
  574. {
  575. return false;
  576. }
  577. /**
  578. Improved method of initiating a transaction. Used together with CompleteTrans().
  579. Advantages include:
  580. a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
  581. Only the outermost block is treated as a transaction.<br>
  582. b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
  583. c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
  584. are disabled, making it backward compatible.
  585. */
  586. function StartTrans($errfn = 'ADODB_TransMonitor')
  587. {
  588. if ($this->transOff > 0) {
  589. $this->transOff += 1;
  590. return;
  591. }
  592. $this->_oldRaiseFn = $this->raiseErrorFn;
  593. $this->raiseErrorFn = $errfn;
  594. $this->_transOK = true;
  595. if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
  596. $this->BeginTrans();
  597. $this->transOff = 1;
  598. }
  599. /**
  600. Used together with StartTrans() to end a transaction. Monitors connection
  601. for sql errors, and will commit or rollback as appropriate.
  602. @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
  603. and if set to false force rollback even if no SQL error detected.
  604. @returns true on commit, false on rollback.
  605. */
  606. function CompleteTrans($autoComplete = true)
  607. {
  608. if ($this->transOff > 1) {
  609. $this->transOff -= 1;
  610. return true;
  611. }
  612. $this->raiseErrorFn = $this->_oldRaiseFn;
  613. $this->transOff = 0;
  614. if ($this->_transOK && $autoComplete) {
  615. if (!$this->CommitTrans()) {
  616. $this->_transOK = false;
  617. if ($this->debug) ADOConnection::outp("Smart Commit failed");
  618. } else
  619. if ($this->debug) ADOConnection::outp("Smart Commit occurred");
  620. } else {
  621. $this->RollbackTrans();
  622. if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
  623. }
  624. return $this->_transOK;
  625. }
  626. /*
  627. At the end of a StartTrans/CompleteTrans block, perform a rollback.
  628. */
  629. function FailTrans()
  630. {
  631. if ($this->debug)
  632. if ($this->transOff == 0) {
  633. ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
  634. } else {
  635. ADOConnection::outp("FailTrans was called");
  636. adodb_backtrace();
  637. }
  638. $this->_transOK = false;
  639. }
  640. /**
  641. Check if transaction has failed, only for Smart Transactions.
  642. */
  643. function HasFailedTrans()
  644. {
  645. if ($this->transOff > 0) return $this->_transOK == false;
  646. return false;
  647. }
  648. /**
  649. * Execute SQL
  650. *
  651. * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
  652. * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
  653. * @return RecordSet or false
  654. */
  655. function &Execute($sql,$inputarr=false)
  656. {
  657. if ($this->fnExecute) {
  658. $fn = $this->fnExecute;
  659. $ret =& $fn($this,$sql,$inputarr);
  660. if (isset($ret)) return $ret;
  661. }
  662. if ($inputarr) {
  663. if (!is_array($inputarr)) $inputarr = array($inputarr);
  664. $element0 = reset($inputarr);
  665. # is_object check because oci8 descriptors can be passed in
  666. $array_2d = is_array($element0) && !is_object(reset($element0));
  667. if (!is_array($sql) && !$this->_bindInputArray) {
  668. $sqlarr = explode('?',$sql);
  669. if (!$array_2d) $inputarr = array($inputarr);
  670. foreach($inputarr as $arr) {
  671. $sql = ''; $i = 0;
  672. foreach($arr as $v) {
  673. $sql .= $sqlarr[$i];
  674. // from Ron Baldwin <ron.baldwin#sourceprose.com>
  675. // Only quote string types
  676. $typ = gettype($v);
  677. if ($typ == 'string')
  678. $sql .= $this->qstr($v);
  679. else if ($typ == 'double')
  680. $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
  681. else if ($v === null)
  682. $sql .= 'NULL';
  683. else
  684. $sql .= $v;
  685. $i += 1;
  686. }
  687. if (isset($sqlarr[$i])) {
  688. $sql .= $sqlarr[$i];
  689. if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
  690. } else if ($i != sizeof($sqlarr))
  691. ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql));
  692. $ret =& $this->_Execute($sql);
  693. if (!$ret) return $ret;
  694. }
  695. } else {
  696. if ($array_2d) {
  697. $stmt = $this->Prepare($sql);
  698. foreach($inputarr as $arr) {
  699. $ret =& $this->_Execute($stmt,$arr);
  700. if (!$ret) return $ret;
  701. }
  702. } else {
  703. $ret =& $this->_Execute($sql,$inputarr);
  704. }
  705. }
  706. } else {
  707. $ret =& $this->_Execute($sql,false);
  708. }
  709. return $ret;
  710. }
  711. function &_Execute($sql,$inputarr=false)
  712. {
  713. if ($this->debug) {
  714. global $ADODB_INCLUDED_LIB;
  715. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  716. $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
  717. } else {
  718. $this->_queryID = @$this->_query($sql,$inputarr);
  719. }
  720. /************************
  721. // OK, query executed
  722. *************************/
  723. if ($this->_queryID === false) { // error handling if query fails
  724. if ($this->debug == 99) adodb_backtrace(true,5);
  725. $fn = $this->raiseErrorFn;
  726. if ($fn) {
  727. $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
  728. }
  729. $false = false;
  730. return $false;
  731. }
  732. if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
  733. $rs =& new ADORecordSet_empty();
  734. return $rs;
  735. }
  736. // return real recordset from select statement
  737. $rsclass = $this->rsPrefix.$this->databaseType;
  738. $rs =& new $rsclass($this->_queryID,$this->fetchMode);
  739. $rs->connection = &$this; // Pablo suggestion
  740. $rs->Init();
  741. if (is_array($sql)) $rs->sql = $sql[0];
  742. else $rs->sql = $sql;
  743. if ($rs->_numOfRows <= 0) {
  744. global $ADODB_COUNTRECS;
  745. if ($ADODB_COUNTRECS) {
  746. if (!$rs->EOF) {
  747. $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
  748. $rs->_queryID = $this->_queryID;
  749. } else
  750. $rs->_numOfRows = 0;
  751. }
  752. }
  753. return $rs;
  754. }
  755. function CreateSequence($seqname='adodbseq',$startID=1)
  756. {
  757. if (empty($this->_genSeqSQL)) return false;
  758. return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  759. }
  760. function DropSequence($seqname='adodbseq')
  761. {
  762. if (empty($this->_dropSeqSQL)) return false;
  763. return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
  764. }
  765. /**
  766. * Generates a sequence id and stores it in $this->genID;
  767. * GenID is only available if $this->hasGenID = true;
  768. *
  769. * @param seqname name of sequence to use
  770. * @param startID if sequence does not exist, start at this ID
  771. * @return 0 if not supported, otherwise a sequence id
  772. */
  773. function GenID($seqname='adodbseq',$startID=1)
  774. {
  775. if (!$this->hasGenID) {
  776. return 0; // formerly returns false pre 1.60
  777. }
  778. $getnext = sprintf($this->_genIDSQL,$seqname);
  779. $holdtransOK = $this->_transOK;
  780. @($rs = $this->Execute($getnext));
  781. if (!$rs) {
  782. $this->_transOK = $holdtransOK; //if the status was ok before reset
  783. $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  784. $rs = $this->Execute($getnext);
  785. }
  786. if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
  787. else $this->genID = 0; // false
  788. if ($rs) $rs->Close();
  789. return $this->genID;
  790. }
  791. /**
  792. * @param $table string name of the table, not needed by all databases (eg. mysql), default ''
  793. * @param $column string name of the column, not needed by all databases (eg. mysql), default ''
  794. * @return the last inserted ID. Not all databases support this.
  795. */
  796. function Insert_ID($table='',$column='')
  797. {
  798. if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
  799. if ($this->hasInsertID) return $this->_insertid($table,$column);
  800. if ($this->debug) {
  801. ADOConnection::outp( '<p>Insert_ID error</p>');
  802. adodb_backtrace();
  803. }
  804. return false;
  805. }
  806. /**
  807. * Portable Insert ID. Pablo Roca <pabloroca#mvps.org>
  808. *
  809. * @return the last inserted ID. All databases support this. But aware possible
  810. * problems in multiuser environments. Heavy test this before deploying.
  811. */
  812. function PO_Insert_ID($table="", $id="")
  813. {
  814. if ($this->hasInsertID){
  815. return $this->Insert_ID($table,$id);
  816. } else {
  817. return $this->GetOne("SELECT MAX($id) FROM $table");
  818. }
  819. }
  820. /**
  821. * @return # rows affected by UPDATE/DELETE
  822. */
  823. function Affected_Rows()
  824. {
  825. if ($this->hasAffectedRows) {
  826. if ($this->fnExecute === 'adodb_log_sql') {
  827. if ($this->_logsql && $this->_affected !== false) return $this->_affected;
  828. }
  829. $val = $this->_affectedrows();
  830. return ($val < 0) ? false : $val;
  831. }
  832. if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
  833. return false;
  834. }
  835. /**
  836. * @return the last error message
  837. */
  838. function ErrorMsg()
  839. {
  840. return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
  841. }
  842. /**
  843. * @return the last error number. Normally 0 means no error.
  844. */
  845. function ErrorNo()
  846. {
  847. return ($this->_errorMsg) ? -1 : 0;
  848. }
  849. function MetaError($err=false)
  850. {
  851. include_once(ADODB_DIR."/adodb-error.inc.php");
  852. if ($err === false) $err = $this->ErrorNo();
  853. return adodb_error($this->dataProvider,$this->databaseType,$err);
  854. }
  855. function MetaErrorMsg($errno)
  856. {
  857. include_once(ADODB_DIR."/adodb-error.inc.php");
  858. return adodb_errormsg($errno);
  859. }
  860. /**
  861. * @returns an array with the primary key columns in it.
  862. */
  863. function MetaPrimaryKeys($table, $owner=false)
  864. {
  865. // owner not used in base class - see oci8
  866. $p = array();
  867. $objs =& $this->MetaColumns($table);
  868. if ($objs) {
  869. foreach($objs as $v) {
  870. if (!empty($v->primary_key))
  871. $p[] = $v->name;
  872. }
  873. }
  874. if (sizeof($p)) return $p;
  875. if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
  876. return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
  877. return false;
  878. }
  879. /**
  880. * @returns assoc array where keys are tables, and values are foreign keys
  881. */
  882. function MetaForeignKeys($table, $owner=false, $upper=false)
  883. {
  884. return false;
  885. }
  886. /**
  887. * Choose a database to connect to. Many databases do not support this.
  888. *
  889. * @param dbName is the name of the database to select
  890. * @return true or false
  891. */
  892. function SelectDB($dbName)
  893. {return false;}
  894. /**
  895. * Will select, getting rows from $offset (1-based), for $nrows.
  896. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  897. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  898. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  899. * eg.
  900. * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
  901. * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
  902. *
  903. * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
  904. * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
  905. *
  906. * @param sql
  907. * @param [offset] is the row to start calculations from (1-based)
  908. * @param [nrows] is the number of rows to get
  909. * @param [inputarr] array of bind variables
  910. * @param [secs2cache] is a private parameter only used by jlim
  911. * @return the recordset ($rs->databaseType == 'array')
  912. */
  913. function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
  914. {
  915. if ($this->hasTop && $nrows > 0) {
  916. // suggested by Reinhard Balling. Access requires top after distinct
  917. // Informix requires first before distinct - F Riosa
  918. $ismssql = (strpos($this->databaseType,'mssql') !== false);
  919. if ($ismssql) $isaccess = false;
  920. else $isaccess = (strpos($this->databaseType,'access') !== false);
  921. if ($offset <= 0) {
  922. // access includes ties in result
  923. if ($isaccess) {
  924. $sql = preg_replace(
  925. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
  926. if ($secs2cache>0) {
  927. $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
  928. } else {
  929. $ret =& $this->Execute($sql,$inputarr);
  930. }
  931. return $ret; // PHP5 fix
  932. } else if ($ismssql){
  933. $sql = preg_replace(
  934. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
  935. } else {
  936. $sql = preg_replace(
  937. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
  938. }
  939. } else {
  940. $nn = $nrows + $offset;
  941. if ($isaccess || $ismssql) {
  942. $sql = preg_replace(
  943. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  944. } else {
  945. $sql = preg_replace(
  946. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  947. }
  948. }
  949. }
  950. // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
  951. // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
  952. global $ADODB_COUNTRECS;
  953. $savec = $ADODB_COUNTRECS;
  954. $ADODB_COUNTRECS = false;
  955. if ($offset>0){
  956. if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  957. else $rs = &$this->Execute($sql,$inputarr);
  958. } else {
  959. if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  960. else $rs = &$this->Execute($sql,$inputarr);
  961. }
  962. $ADODB_COUNTRECS = $savec;
  963. if ($rs && !$rs->EOF) {
  964. $rs =& $this->_rs2rs($rs,$nrows,$offset);
  965. }
  966. //print_r($rs);
  967. return $rs;
  968. }
  969. /**
  970. * Create serializable recordset. Breaks rs link to connection.
  971. *
  972. * @param rs the recordset to serialize
  973. */
  974. function &SerializableRS(&$rs)
  975. {
  976. $rs2 =& $this->_rs2rs($rs);
  977. $ignore = false;
  978. $rs2->connection =& $ignore;
  979. return $rs2;
  980. }
  981. /**
  982. * Convert database recordset to an array recordset
  983. * input recordset's cursor should be at beginning, and
  984. * old $rs will be closed.
  985. *
  986. * @param rs the recordset to copy
  987. * @param [nrows] number of rows to retrieve (optional)
  988. * @param [offset] offset by number of rows (optional)
  989. * @return the new recordset
  990. */
  991. function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
  992. {
  993. if (! $rs) {
  994. $false = false;
  995. return $false;
  996. }
  997. $dbtype = $rs->databaseType;
  998. if (!$dbtype) {
  999. $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
  1000. return $rs;
  1001. }
  1002. if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
  1003. $rs->MoveFirst();
  1004. $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
  1005. return $rs;
  1006. }
  1007. $flds = array();
  1008. for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
  1009. $flds[] = $rs->FetchField($i);
  1010. }
  1011. $arr =& $rs->GetArrayLimit($nrows,$offset);
  1012. //print_r($arr);
  1013. if ($close) $rs->Close();
  1014. $arrayClass = $this->arrayClass;
  1015. $rs2 =& new $arrayClass();
  1016. $rs2->connection = &$this;
  1017. $rs2->sql = $rs->sql;
  1018. $rs2->dataProvider = $this->dataProvider;
  1019. $rs2->InitArrayFields($arr,$flds);
  1020. $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
  1021. return $rs2;
  1022. }
  1023. /*
  1024. * Return all rows. Compat with PEAR DB
  1025. */
  1026. function &GetAll($sql, $inputarr=false)
  1027. {
  1028. $arr =& $this->GetArray($sql,$inputarr);
  1029. return $arr;
  1030. }
  1031. function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
  1032. {
  1033. $rs =& $this->Execute($sql, $inputarr);
  1034. if (!$rs) {
  1035. $false = false;
  1036. return $false;
  1037. }
  1038. $arr =& $rs->GetAssoc($force_array,$first2cols);
  1039. return $arr;
  1040. }
  1041. function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
  1042. {
  1043. if (!is_numeric($secs2cache)) {
  1044. $first2cols = $force_array;
  1045. $force_array = $inputarr;
  1046. }
  1047. $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
  1048. if (!$rs) {
  1049. $false = false;
  1050. return $false;
  1051. }
  1052. $arr =& $rs->GetAssoc($force_array,$first2cols);
  1053. return $arr;
  1054. }
  1055. /**
  1056. * Return first element of first row of sql statement. Recordset is disposed
  1057. * for you.
  1058. *
  1059. * @param sql SQL statement
  1060. * @param [inputarr] input bind array
  1061. */
  1062. function GetOne($sql,$inputarr=false)
  1063. {
  1064. global $ADODB_COUNTRECS;
  1065. $crecs = $ADODB_COUNTRECS;
  1066. $ADODB_COUNTRECS = false;
  1067. $ret = false;
  1068. $rs = &$this->Execute($sql,$inputarr);
  1069. if ($rs) {
  1070. if (!$rs->EOF) $ret = reset($rs->fields);
  1071. $rs->Close();
  1072. }
  1073. $ADODB_COUNTRECS = $crecs;
  1074. return $ret;
  1075. }
  1076. function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
  1077. {
  1078. $ret = false;
  1079. $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1080. if ($rs) {
  1081. if (!$rs->EOF) $ret = reset($rs->fields);
  1082. $rs->Close();
  1083. }
  1084. return $ret;
  1085. }
  1086. function GetCol($sql, $inputarr = false, $trim = false)
  1087. {
  1088. $rv = false;
  1089. $rs = &$this->Execute($sql, $inputarr);
  1090. if ($rs) {
  1091. $rv = array();
  1092. if ($trim) {
  1093. while (!$rs->EOF) {
  1094. $rv[] = trim(reset($rs->fields));
  1095. $rs->MoveNext();
  1096. }
  1097. } else {
  1098. while (!$rs->EOF) {
  1099. $rv[] = reset($rs->fields);
  1100. $rs->MoveNext();
  1101. }
  1102. }
  1103. $rs->Close();
  1104. }
  1105. return $rv;
  1106. }
  1107. function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
  1108. {
  1109. $rv = false;
  1110. $rs = &$this->CacheExecute($secs, $sql, $inputarr);
  1111. if ($rs) {
  1112. if ($trim) {
  1113. while (!$rs->EOF) {
  1114. $rv[] = trim(reset($rs->fields));
  1115. $rs->MoveNext();
  1116. }
  1117. } else {
  1118. while (!$rs->EOF) {
  1119. $rv[] = reset($rs->fields);
  1120. $rs->MoveNext();
  1121. }
  1122. }
  1123. $rs->Close();
  1124. }
  1125. return $rv;
  1126. }
  1127. /*
  1128. Calculate the offset of a date for a particular database and generate
  1129. appropriate SQL. Useful for calculating future/past dates and storing
  1130. in a database.
  1131. If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
  1132. */
  1133. function OffsetDate($dayFraction,$date=false)
  1134. {
  1135. if (!$date) $date = $this->sysDate;
  1136. return '('.$date.'+'.$dayFraction.')';
  1137. }
  1138. /**
  1139. *
  1140. * @param sql SQL statement
  1141. * @param [inputarr] input bind array
  1142. */
  1143. function &GetArray($sql,$inputarr=false)
  1144. {
  1145. global $ADODB_COUNTRECS;
  1146. $savec = $ADODB_COUNTRECS;
  1147. $ADODB_COUNTRECS = false;
  1148. $rs =& $this->Execute($sql,$inputarr);
  1149. $ADODB_COUNTRECS = $savec;
  1150. if (!$rs)
  1151. if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  1152. else {
  1153. $false = false;
  1154. return $false;
  1155. }
  1156. $arr =& $rs->GetArray();
  1157. $rs->Close();
  1158. return $arr;
  1159. }
  1160. function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
  1161. {
  1162. return $this->CacheGetArray($secs2cache,$sql,$inputarr);
  1163. }
  1164. function &CacheGetArray($secs2cache,$sql=false,$inputarr=false)
  1165. {
  1166. global $ADODB_COUNTRECS;
  1167. $savec = $ADODB_COUNTRECS;
  1168. $ADODB_COUNTRECS = false;
  1169. $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
  1170. $ADODB_COUNTRECS = $savec;
  1171. if (!$rs)
  1172. if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  1173. else {
  1174. $false = false;
  1175. return $false;
  1176. }
  1177. $arr =& $rs->GetArray();
  1178. $rs->Close();
  1179. return $arr;
  1180. }
  1181. /**
  1182. * Return one row of sql statement. Recordset is disposed for you.
  1183. *
  1184. * @param sql SQL statement
  1185. * @param [inputarr] input bind array
  1186. */
  1187. function &GetRow($sql,$inputarr=false)
  1188. {
  1189. global $ADODB_COUNTRECS;
  1190. $crecs = $ADODB_COUNTRECS;
  1191. $ADODB_COUNTRECS = false;
  1192. $rs =& $this->Execute($sql,$inputarr);
  1193. $ADODB_COUNTRECS = $crecs;
  1194. if ($rs) {
  1195. if (!$rs->EOF) $arr = $rs->fields;
  1196. else $arr = array();
  1197. $rs->Close();
  1198. return $arr;
  1199. }
  1200. $false = false;
  1201. return $false;
  1202. }
  1203. function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
  1204. {
  1205. $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
  1206. if ($rs) {
  1207. $arr = false;
  1208. if (!$rs->EOF) $arr = $rs->fields;
  1209. $rs->Close();
  1210. return $arr;
  1211. }
  1212. $false = false;
  1213. return $false;
  1214. }
  1215. /**
  1216. * Insert or replace a single record. Note: this is not the same as MySQL's replace.
  1217. * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
  1218. * Also note that no table locking is done currently, so it is possible that the
  1219. * record be inserted twice by two programs...
  1220. *
  1221. * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
  1222. *
  1223. * $table table name
  1224. * $fieldArray associative array of data (you must quote strings yourself).
  1225. * $keyCol the primary key field name or if compound key, array of field names
  1226. * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
  1227. * but does not work with dates nor SQL functions.
  1228. * has_autoinc the primary key is an auto-inc field, so skip in insert.
  1229. *
  1230. * Currently blob replace not supported
  1231. *
  1232. * returns 0 = fail, 1 = update, 2 = insert
  1233. */
  1234. function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
  1235. {
  1236. global $ADODB_INCLUDED_LIB;
  1237. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  1238. return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
  1239. }
  1240. /**
  1241. * Will select, getting rows from $offset (1-based), for $nrows.
  1242. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  1243. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  1244. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  1245. * eg.
  1246. * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
  1247. * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
  1248. *
  1249. * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
  1250. *
  1251. * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
  1252. * @param sql
  1253. * @param [offset] is the row to start calculations from (1-based)
  1254. * @param [nrows] is the number of rows to get
  1255. * @param [inputarr] array of bind variables
  1256. * @return the recordset ($rs->databaseType == 'array')
  1257. */
  1258. function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
  1259. {
  1260. if (!is_numeric($secs2cache)) {
  1261. if ($sql === false) $sql = -1;
  1262. if ($offset == -1) $offset = false;
  1263. // sql, nrows, offset,inputarr
  1264. $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
  1265. } else {
  1266. if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
  1267. $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
  1268. }
  1269. return $rs;
  1270. }
  1271. /**
  1272. * Flush cached recordsets that match a particular $sql statement.
  1273. * If $sql == false, then we purge all files in the cache.
  1274. */
  1275. function CacheFlush($sql=false,$inputarr=false)
  1276. {
  1277. global $ADODB_CACHE_DIR;
  1278. if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
  1279. if (strncmp(PHP_OS,'WIN',3) === 0) {
  1280. $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
  1281. } else {
  1282. //$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f';
  1283. $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/';
  1284. // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
  1285. }
  1286. if ($this->debug) {
  1287. ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
  1288. } else {
  1289. exec($cmd);
  1290. }
  1291. return;
  1292. }
  1293. global $ADODB_INCLUDED_CSV;
  1294. if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
  1295. $f = $this->_gencachename($sql.serialize($inputarr),false);
  1296. adodb_write_file($f,''); // is adodb_write_file needed?
  1297. if (!@unlink($f)) {
  1298. if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
  1299. }
  1300. }
  1301. /**
  1302. * Private function to generate filename for caching.
  1303. * Filename is generated based on:
  1304. *
  1305. * - sql statement
  1306. * - database type (oci8, ibase, ifx, etc)
  1307. * - database name
  1308. * - userid
  1309. * - setFetchMode (adodb 4.23)
  1310. *
  1311. * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
  1312. * Assuming that we can have 50,000 files per directory with good performance,
  1313. * then we can scale to 12.8 million unique cached recordsets. Wow!
  1314. */
  1315. function _gencachename($sql,$createdir)
  1316. {
  1317. global $ADODB_CACHE_DIR;
  1318. static $notSafeMode;
  1319. if ($this->fetchMode === false) {
  1320. global $ADODB_FETCH_MODE;
  1321. $mode = $ADODB_FETCH_MODE;
  1322. } else {
  1323. $mode = $this->fetchMode;
  1324. }
  1325. $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
  1326. if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode');
  1327. $dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR;
  1328. if ($createdir && $notSafeMode && !file_exists($dir)) {
  1329. $oldu = umask(0);
  1330. if (!mkdir($dir,0771))
  1331. if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
  1332. umask($oldu);
  1333. }
  1334. return $dir.'/adodb_'.$m.'.cache';
  1335. }
  1336. /**
  1337. * Execute SQL, caching recordsets.
  1338. *
  1339. * @param [secs2cache] seconds to cache data, set to 0 to force query.
  1340. * This is an optional parameter.
  1341. * @param sql SQL statement to execute
  1342. * @param [inputarr] holds the input data to bind to
  1343. * @return RecordSet or false
  1344. */
  1345. function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
  1346. {
  1347. if (!is_numeric($secs2cache)) {
  1348. $inputarr = $sql;
  1349. $sql = $secs2cache;
  1350. $secs2cache = $this->cacheSecs;
  1351. }
  1352. global $ADODB_INCLUDED_CSV;
  1353. if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
  1354. if (is_array($sql)) $sql = $sql[0];
  1355. $md5file = $this->_gencachename($sql.serialize($inputarr),true);
  1356. $err = '';
  1357. if ($secs2cache > 0){
  1358. $rs = &csv2rs($md5file,$err,$secs2cache,$this->arrayClass);
  1359. $this->numCacheHits += 1;
  1360. } else {
  1361. $err='Timeout 1';
  1362. $rs = false;
  1363. $this->numCacheMisses += 1;
  1364. }
  1365. if (!$rs) {
  1366. // no cached rs found
  1367. if ($this->debug) {
  1368. if (get_magic_quotes_runtime()) {
  1369. ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
  1370. }
  1371. if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
  1372. }
  1373. $rs = &$this->Execute($sql,$inputarr);
  1374. if ($rs) {
  1375. $eof = $rs->EOF;
  1376. $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
  1377. $txt = _rs2serialize($rs,false,$sql); // serialize
  1378. if (!adodb_write_file($md5file,$txt,$this->debug)) {
  1379. if ($fn = $this->raiseErrorFn) {
  1380. $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
  1381. }
  1382. if ($this->debug) ADOConnection::outp( " Cache write error");
  1383. }
  1384. if ($rs->EOF && !$eof) {
  1385. $rs->MoveFirst();
  1386. //$rs = &csv2rs($md5file,$err);
  1387. $rs->connection = &$this; // Pablo suggestion
  1388. }
  1389. } else
  1390. @unlink($md5file);
  1391. } else {
  1392. $this->_errorMsg = '';
  1393. $this->_errorCode = 0;
  1394. if ($this->fnCacheExecute) {
  1395. $fn = $this->fnCacheExecute;
  1396. $fn($this, $secs2cache, $sql, $inputarr);
  1397. }
  1398. // ok, set cached object found
  1399. $rs->connection = &$this; // Pablo suggestion
  1400. if ($this->debug){
  1401. global $HTTP_SERVER_VARS;
  1402. $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
  1403. $ttl = $rs->timeCreated + $secs2cache - time();
  1404. $s = is_array($sql) ? $sql[0] : $sql;
  1405. if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
  1406. ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
  1407. }
  1408. }
  1409. return $rs;
  1410. }
  1411. /*
  1412. Similar to PEAR DB's autoExecute(), except that
  1413. $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
  1414. If $mode == 'UPDATE', then $where is compulsory as a safety measure.
  1415. $forceUpdate means that even if the data has not changed, perform update.
  1416. */
  1417. function AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false)
  1418. {
  1419. //$flds = array_keys($fields_values);
  1420. //$fldstr = implode(', ',$flds);
  1421. $sql = 'SELECT * FROM '.$table;
  1422. if ($where!==FALSE) $sql .= ' WHERE '.$where;
  1423. else if ($mode == 'UPDATE') {
  1424. ADOConnection::outp('AutoExecute: Illegal mode=UPDATE with empty WHERE clause');
  1425. return false;
  1426. }
  1427. $rs =& $this->SelectLimit($sql,1);
  1428. if (!$rs) return false; // table does not exist
  1429. switch((string) $mode) {
  1430. case 'UPDATE':
  1431. case '2':
  1432. $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
  1433. break;
  1434. case 'INSERT':
  1435. case '1':
  1436. $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
  1437. break;
  1438. default:
  1439. ADOConnection::outp("AutoExecute: Unknown mode=$mode");
  1440. return false;
  1441. }
  1442. if ($sql) return $this->Execute($sql);
  1443. return false;
  1444. }
  1445. /**
  1446. * Generates an Update Query based on an existing recordset.
  1447. * $arrFields is an associative array of fields with the value
  1448. * that should be assigned.
  1449. *
  1450. * Note: This function should only be used on a recordset
  1451. * that is run against a single table and sql should only
  1452. * be a simple select stmt with no groupby/orderby/limit
  1453. *
  1454. * "Jonathan Younger" <jyounger@unilab.com>
  1455. */
  1456. function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
  1457. {
  1458. global $ADODB_INCLUDED_LIB;
  1459. //********************************************************//
  1460. //This is here to maintain compatibility
  1461. //with older adodb versions. Sets force type to force nulls if $forcenulls is set.
  1462. if (!isset($force)) {
  1463. global $ADODB_FORCE_TYPE;
  1464. $force = $ADODB_FORCE_TYPE;
  1465. }
  1466. //********************************************************//
  1467. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  1468. return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
  1469. }
  1470. /**
  1471. * Generates an Insert Query based on an existing recordset.
  1472. * $arrFields is an associative array of fields with the value
  1473. * that should be assigned.
  1474. *
  1475. * Note: This function should only be used on a recordset
  1476. * that is run against a single table.
  1477. */
  1478. function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
  1479. {
  1480. global $ADODB_INCLUDED_LIB;
  1481. if (!isset($force)) {
  1482. global $ADODB_FORCE_TYPE;
  1483. $force = $ADODB_FORCE_TYPE;
  1484. }
  1485. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  1486. return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
  1487. }
  1488. /**
  1489. * Update a blob column, given a where clause. There are more sophisticated
  1490. * blob handling functions that we could have implemented, but all require
  1491. * a very complex API. Instead we have chosen something that is extremely
  1492. * simple to understand and use.
  1493. *
  1494. * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
  1495. *
  1496. * Usage to update a $blobvalue which has a primary key blob_id=1 into a
  1497. * field blobtable.blobcolumn:
  1498. *
  1499. * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
  1500. *
  1501. * Insert example:
  1502. *
  1503. * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1504. * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
  1505. */
  1506. function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  1507. {
  1508. return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
  1509. }
  1510. /**
  1511. * Usage:
  1512. * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
  1513. *
  1514. * $blobtype supports 'BLOB' and 'CLOB'
  1515. *
  1516. * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1517. * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
  1518. */
  1519. function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
  1520. {
  1521. $fd = fopen($path,'rb');
  1522. if ($fd === false) return false;
  1523. $val = fread($fd,filesize($path));
  1524. fclose($fd);
  1525. return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
  1526. }
  1527. function BlobDecode($blob)
  1528. {
  1529. return $blob;
  1530. }
  1531. function BlobEncode($blob)
  1532. {
  1533. return $blob;
  1534. }
  1535. function SetCharSet($charset)
  1536. {
  1537. return false;
  1538. }
  1539. function IfNull( $field, $ifNull )
  1540. {
  1541. return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
  1542. }
  1543. function LogSQL($enable=true)
  1544. {
  1545. include_once(ADODB_DIR.'/adodb-perf.inc.php');
  1546. if ($enable) $this->fnExecute = 'adodb_log_sql';
  1547. else $this->fnExecute = false;
  1548. $old = $this->_logsql;
  1549. $this->_logsql = $enable;
  1550. if ($enable && !$old) $this->_affected = false;
  1551. return $old;
  1552. }
  1553. function GetCharSet()
  1554. {
  1555. return false;
  1556. }
  1557. /**
  1558. * Usage:
  1559. * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
  1560. *
  1561. * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
  1562. * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
  1563. */
  1564. function UpdateClob($table,$column,$val,$where)
  1565. {
  1566. return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
  1567. }
  1568. /**
  1569. * Change the SQL connection locale to a specified locale.
  1570. * This is used to get the date formats written depending on the client locale.
  1571. */
  1572. function SetDateLocale($locale = 'En')
  1573. {
  1574. $this->locale = $locale;
  1575. switch ($locale)
  1576. {
  1577. case 'En':
  1578. $this->fmtDate="'Y-m-d'";
  1579. $this->fmtTimeStamp = "'Y-m-d H:i:s'";
  1580. break;
  1581. case 'Us':
  1582. $this->fmtDate = "'m-d-Y'";
  1583. $this->fmtTimeStamp = "'m-d-Y H:i:s'";
  1584. break;
  1585. case 'Nl':
  1586. case 'Fr':
  1587. case 'Ro':
  1588. case 'It':
  1589. $this->fmtDate="'d-m-Y'";
  1590. $this->fmtTimeStamp = "'d-m-Y H:i:s'";
  1591. break;
  1592. case 'Ge':
  1593. $this->fmtDate="'d.m.Y'";
  1594. $this->fmtTimeStamp = "'d.m.Y H:i:s'";
  1595. break;
  1596. default:
  1597. $this->fmtDate="'Y-m-d'";
  1598. $this->fmtTimeStamp = "'Y-m-d H:i:s'";
  1599. break;
  1600. }
  1601. }
  1602. /**
  1603. * Close Connection
  1604. */
  1605. function Close()
  1606. {
  1607. $rez = $this->_close();
  1608. $this->_connectionID = false;
  1609. return $rez;
  1610. }
  1611. /**
  1612. * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
  1613. *
  1614. * @return true if succeeded or false if database does not support transactions
  1615. */
  1616. function BeginTrans() {return false;}
  1617. /**
  1618. * If database does not support transactions, always return true as data always commited
  1619. *
  1620. * @param $ok set to false to rollback transaction, true to commit
  1621. *
  1622. * @return true/false.
  1623. */
  1624. function CommitTrans($ok=true)
  1625. { return true;}
  1626. /**
  1627. * If database does not support transactions, rollbacks always fail, so return false
  1628. *
  1629. * @return true/false.
  1630. */
  1631. function RollbackTrans()
  1632. { return false;}
  1633. /**
  1634. * return the databases that the driver can connect to.
  1635. * Some databases will return an empty array.
  1636. *
  1637. * @return an array of database names.
  1638. */
  1639. function MetaDatabases()
  1640. {
  1641. global $ADODB_FETCH_MODE;
  1642. if ($this->metaDatabasesSQL) {
  1643. $save = $ADODB_FETCH_MODE;
  1644. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1645. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1646. $arr = $this->GetCol($this->metaDatabasesSQL);
  1647. if (isset($savem)) $this->SetFetchMode($savem);
  1648. $ADODB_FETCH_MODE = $save;
  1649. return $arr;
  1650. }
  1651. return false;
  1652. }
  1653. /**
  1654. * @param ttype can either be 'VIEW' or 'TABLE' or false.
  1655. * If false, both views and tables are returned.
  1656. * "VIEW" returns only views
  1657. * "TABLE" returns only tables
  1658. * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
  1659. * @param mask is the input mask - only supported by oci8 and postgresql
  1660. *
  1661. * @return array of tables for current database.
  1662. */
  1663. function &MetaTables($ttype=false,$showSchema=false,$mask=false)
  1664. {
  1665. global $ADODB_FETCH_MODE;
  1666. $false = false;
  1667. if ($mask) {
  1668. return $false;
  1669. }
  1670. if ($this->metaTablesSQL) {
  1671. // complicated state saving by the need for backward compat
  1672. $save = $ADODB_FETCH_MODE;
  1673. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1674. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1675. $rs = $this->Execute($this->metaTablesSQL);
  1676. if (isset($savem)) $this->SetFetchMode($savem);
  1677. $ADODB_FETCH_MODE = $save;
  1678. if ($rs === false) return $false;
  1679. $arr =& $rs->GetArray();
  1680. $arr2 = array();
  1681. if ($hast = ($ttype && isset($arr[0][1]))) {
  1682. $showt = strncmp($ttype,'T',1);
  1683. }
  1684. for ($i=0; $i < sizeof($arr); $i++) {
  1685. if ($hast) {
  1686. if ($showt == 0) {
  1687. if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
  1688. } else {
  1689. if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
  1690. }
  1691. } else
  1692. $arr2[] = trim($arr[$i][0]);
  1693. }
  1694. $rs->Close();
  1695. return $arr2;
  1696. }
  1697. return $false;
  1698. }
  1699. function _findschema(&$table,&$schema)
  1700. {
  1701. if (!$schema && ($at = strpos($table,'.')) !== false) {
  1702. $schema = substr($table,0,$at);
  1703. $table = substr($table,$at+1);
  1704. }
  1705. }
  1706. /**
  1707. * List columns in a database as an array of ADOFieldObjects.
  1708. * See top of file for definition of object.
  1709. *
  1710. * @param table table name to query
  1711. * @param upper uppercase table name (required by some databases)
  1712. * @schema is optional database schema to use - not supported by all databases.
  1713. *
  1714. * @return array of ADOFieldObjects for current table.
  1715. */
  1716. function &MetaColumns($table,$upper=true)
  1717. {
  1718. global $ADODB_FETCH_MODE;
  1719. $false = false;
  1720. if (!empty($this->metaColumnsSQL)) {
  1721. $schema = false;
  1722. $this->_findschema($table,$schema);
  1723. $save = $ADODB_FETCH_MODE;
  1724. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1725. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1726. $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));
  1727. if (isset($savem)) $this->SetFetchMode($savem);
  1728. $ADODB_FETCH_MODE = $save;
  1729. if ($rs === false || $rs->EOF) return $false;
  1730. $retarr = array();
  1731. while (!$rs->EOF) { //print_r($rs->fields);
  1732. $fld =& new ADOFieldObject();
  1733. $fld->name = $rs->fields[0];
  1734. $fld->type = $rs->fields[1];
  1735. if (isset($rs->fields[3]) && $rs->fields[3]) {
  1736. if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
  1737. $fld->scale = $rs->fields[4];
  1738. if ($fld->scale>0) $fld->max_length += 1;
  1739. } else
  1740. $fld->max_length = $rs->fields[2];
  1741. if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
  1742. else $retarr[strtoupper($fld->name)] = $fld;
  1743. $rs->MoveNext();
  1744. }
  1745. $rs->Close();
  1746. return $retarr;
  1747. }
  1748. return $false;
  1749. }
  1750. /**
  1751. * List indexes on a table as an array.
  1752. * @param table table name to query
  1753. * @param primary true to only show primary keys. Not actually used for most databases
  1754. *
  1755. * @return array of indexes on current table. Each element represents an index, and is itself an associative array.
  1756. Array (
  1757. [name_of_index] => Array
  1758. (
  1759. [unique] => true or false
  1760. [columns] => Array
  1761. (
  1762. [0] => firstname
  1763. [1] => lastname
  1764. )
  1765. )
  1766. */
  1767. function &MetaIndexes($table, $primary = false, $owner = false)
  1768. {
  1769. $false = false;
  1770. return false;
  1771. }
  1772. /**
  1773. * List columns names in a table as an array.
  1774. * @param table table name to query
  1775. *
  1776. * @return array of column names for current table.
  1777. */
  1778. function &MetaColumnNames($table, $numIndexes=false)
  1779. {
  1780. $objarr =& $this->MetaColumns($table);
  1781. if (!is_array($objarr)) {
  1782. $false = false;
  1783. return $false;
  1784. }
  1785. $arr = array();
  1786. if ($numIndexes) {
  1787. $i = 0;
  1788. foreach($objarr as $v) $arr[$i++] = $v->name;
  1789. } else
  1790. foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
  1791. return $arr;
  1792. }
  1793. /**
  1794. * Different SQL databases used different methods to combine strings together.
  1795. * This function provides a wrapper.
  1796. *
  1797. * param s variable number of string parameters
  1798. *
  1799. * Usage: $db->Concat($str1,$str2);
  1800. *
  1801. * @return concatenated string
  1802. */
  1803. function Concat()
  1804. {
  1805. $arr = func_get_args();
  1806. return implode($this->concat_operator, $arr);
  1807. }
  1808. /**
  1809. * Converts a date "d" to a string that the database can understand.
  1810. *
  1811. * @param d a date in Unix date time format.
  1812. *
  1813. * @return date string in database date format
  1814. */
  1815. function DBDate($d)
  1816. {
  1817. if (empty($d) && $d !== 0) return 'null';
  1818. if (is_string($d) && !is_numeric($d)) {
  1819. if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
  1820. if ($this->isoDates) return "'$d'";
  1821. $d = ADOConnection::UnixDate($d);
  1822. }
  1823. return adodb_date($this->fmtDate,$d);
  1824. }
  1825. /**
  1826. * Converts a timestamp "ts" to a string that the database can understand.
  1827. *
  1828. * @param ts a timestamp in Unix date time format.
  1829. *
  1830. * @return timestamp string in database timestamp format
  1831. */
  1832. function DBTimeStamp($ts)
  1833. {
  1834. if (empty($ts) && $ts !== 0) return 'null';
  1835. # strlen(14) allows YYYYMMDDHHMMSS format
  1836. if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
  1837. return adodb_date($this->fmtTimeStamp,$ts);
  1838. if ($ts === 'null') return $ts;
  1839. if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
  1840. $ts = ADOConnection::UnixTimeStamp($ts);
  1841. return adodb_date($this->fmtTimeStamp,$ts);
  1842. }
  1843. /**
  1844. * Also in ADORecordSet.
  1845. * @param $v is a date string in YYYY-MM-DD format
  1846. *
  1847. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  1848. */
  1849. function UnixDate($v)
  1850. {
  1851. if (is_object($v)) {
  1852. // odbtp support
  1853. //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
  1854. return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
  1855. }
  1856. if (is_numeric($v) && strlen($v) !== 8) return $v;
  1857. if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
  1858. ($v), $rr)) return false;
  1859. if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
  1860. // h-m-s-MM-DD-YY
  1861. return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  1862. }
  1863. /**
  1864. * Also in ADORecordSet.
  1865. * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  1866. *
  1867. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  1868. */
  1869. function UnixTimeStamp($v)
  1870. {
  1871. if (is_object($v)) {
  1872. // odbtp support
  1873. //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
  1874. return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
  1875. }
  1876. if (!preg_match(
  1877. "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
  1878. ($v), $rr)) return false;
  1879. if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
  1880. // h-m-s-MM-DD-YY
  1881. if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  1882. return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
  1883. }
  1884. /**
  1885. * Also in ADORecordSet.
  1886. *
  1887. * Format database date based on user defined format.
  1888. *
  1889. * @param v is the character date in YYYY-MM-DD format, returned by database
  1890. * @param fmt is the format to apply to it, using date()
  1891. *
  1892. * @return a date formated as user desires
  1893. */
  1894. function UserDate($v,$fmt='Y-m-d',$gmt=false)
  1895. {
  1896. $tt = $this->UnixDate($v);
  1897. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  1898. if (($tt === false || $tt == -1) && $v != false) return $v;
  1899. else if ($tt == 0) return $this->emptyDate;
  1900. else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  1901. }
  1902. return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  1903. }
  1904. /**
  1905. *
  1906. * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
  1907. * @param fmt is the format to apply to it, using date()
  1908. *
  1909. * @return a timestamp formated as user desires
  1910. */
  1911. function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)
  1912. {
  1913. # strlen(14) allows YYYYMMDDHHMMSS format
  1914. if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
  1915. $tt = $this->UnixTimeStamp($v);
  1916. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  1917. if (($tt === false || $tt == -1) && $v != false) return $v;
  1918. if ($tt == 0) return $this->emptyTimeStamp;
  1919. return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  1920. }
  1921. /**
  1922. * Quotes a string, without prefixing nor appending quotes.
  1923. */
  1924. function addq($s,$magic_quotes=false)
  1925. {
  1926. if (!$magic_quotes) {
  1927. if ($this->replaceQuote[0] == '\\'){
  1928. // only since php 4.0.5
  1929. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  1930. //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  1931. }
  1932. return str_replace("'",$this->replaceQuote,$s);
  1933. }
  1934. // undo magic quotes for "
  1935. $s = str_replace('\\"','"',$s);
  1936. if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
  1937. return $s;
  1938. else {// change \' to '' for sybase/mssql
  1939. $s = str_replace('\\\\','\\',$s);
  1940. return str_replace("\\'",$this->replaceQuote,$s);
  1941. }
  1942. }
  1943. /**
  1944. * Correctly quotes a string so that all strings are escaped. We prefix and append
  1945. * to the string single-quotes.
  1946. * An example is $db->qstr("Don't bother",magic_quotes_runtime());
  1947. *
  1948. * @param s the string to quote
  1949. * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
  1950. * This undoes the stupidity of magic quotes for GPC.
  1951. *
  1952. * @return quoted string to be sent back to database
  1953. */
  1954. function qstr($s,$magic_quotes=false)
  1955. {
  1956. if (!$magic_quotes) {
  1957. if ($this->replaceQuote[0] == '\\'){
  1958. // only since php 4.0.5
  1959. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  1960. //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  1961. }
  1962. return "'".str_replace("'",$this->replaceQuote,$s)."'";
  1963. }
  1964. // undo magic quotes for "
  1965. $s = str_replace('\\"','"',$s);
  1966. if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
  1967. return "'$s'";
  1968. else {// change \' to '' for sybase/mssql
  1969. $s = str_replace('\\\\','\\',$s);
  1970. return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
  1971. }
  1972. }
  1973. /**
  1974. * Will select the supplied $page number from a recordset, given that it is paginated in pages of
  1975. * $nrows rows per page. It also saves two boolean values saying if the given page is the first
  1976. * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
  1977. *
  1978. * See readme.htm#ex8 for an example of usage.
  1979. *
  1980. * @param sql
  1981. * @param nrows is the number of rows per page to get
  1982. * @param page is the page number to get (1-based)
  1983. * @param [inputarr] array of bind variables
  1984. * @param [secs2cache] is a private parameter only used by jlim
  1985. * @return the recordset ($rs->databaseType == 'array')
  1986. *
  1987. * NOTE: phpLens uses a different algorithm and does not use PageExecute().
  1988. *
  1989. */
  1990. function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
  1991. {
  1992. global $ADODB_INCLUDED_LIB;
  1993. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  1994. if ($this->pageExecuteCountRows) $rs =& _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  1995. else $rs =& _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  1996. return $rs;
  1997. }
  1998. /**
  1999. * Will select the supplied $page number from a recordset, given that it is paginated in pages of
  2000. * $nrows rows per page. It also saves two boolean values saying if the given page is the first
  2001. * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
  2002. *
  2003. * @param secs2cache seconds to cache data, set to 0 to force query
  2004. * @param sql
  2005. * @param nrows is the number of rows per page to get
  2006. * @param page is the page number to get (1-based)
  2007. * @param [inputarr] array of bind variables
  2008. * @return the recordset ($rs->databaseType == 'array')
  2009. */
  2010. function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
  2011. {
  2012. /*switch($this->dataProvider) {
  2013. case 'postgres':
  2014. case 'mysql':
  2015. break;
  2016. default: $secs2cache = 0; break;
  2017. }*/
  2018. $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
  2019. return $rs;
  2020. }
  2021. } // end class ADOConnection
  2022. //==============================================================================================
  2023. // CLASS ADOFetchObj
  2024. //==============================================================================================
  2025. /**
  2026. * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
  2027. */
  2028. class ADOFetchObj {
  2029. };
  2030. //==============================================================================================
  2031. // CLASS ADORecordSet_empty
  2032. //==============================================================================================
  2033. /**
  2034. * Lightweight recordset when there are no records to be returned
  2035. */
  2036. class ADORecordSet_empty
  2037. {
  2038. var $dataProvider = 'empty';
  2039. var $databaseType = false;
  2040. var $EOF = true;
  2041. var $_numOfRows = 0;
  2042. var $fields = false;
  2043. var $connection = false;
  2044. function RowCount() {return 0;}
  2045. function RecordCount() {return 0;}
  2046. function PO_RecordCount(){return 0;}
  2047. function Close(){return true;}
  2048. function FetchRow() {return false;}
  2049. function FieldCount(){ return 0;}
  2050. function Init() {}
  2051. }
  2052. //==============================================================================================
  2053. // DATE AND TIME FUNCTIONS
  2054. //==============================================================================================
  2055. include_once(ADODB_DIR.'/adodb-time.inc.php');
  2056. //==============================================================================================
  2057. // CLASS ADORecordSet
  2058. //==============================================================================================
  2059. if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
  2060. else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
  2061. /**
  2062. * RecordSet class that represents the dataset returned by the database.
  2063. * To keep memory overhead low, this class holds only the current row in memory.
  2064. * No prefetching of data is done, so the RecordCount() can return -1 ( which
  2065. * means recordcount not known).
  2066. */
  2067. class ADORecordSet extends ADODB_BASE_RS {
  2068. /*
  2069. * public variables
  2070. */
  2071. var $dataProvider = "native";
  2072. var $fields = false; /// holds the current row data
  2073. var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
  2074. /// in other words, we use a text area for editing.
  2075. var $canSeek = false; /// indicates that seek is supported
  2076. var $sql; /// sql text
  2077. var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
  2078. var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
  2079. var $emptyDate = '&nbsp;'; /// what to display when $time==0
  2080. var $debug = false;
  2081. var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
  2082. var $bind = false; /// used by Fields() to hold array - should be private?
  2083. var $fetchMode; /// default fetch mode
  2084. var $connection = false; /// the parent connection
  2085. /*
  2086. * private variables
  2087. */
  2088. var $_numOfRows = -1; /** number of rows, or -1 */
  2089. var $_numOfFields = -1; /** number of fields in recordset */
  2090. var $_queryID = -1; /** This variable keeps the result link identifier. */
  2091. var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
  2092. var $_closed = false; /** has recordset been closed */
  2093. var $_inited = false; /** Init() should only be called once */
  2094. var $_obj; /** Used by FetchObj */
  2095. var $_names; /** Used by FetchObj */
  2096. var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */
  2097. var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */
  2098. var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */
  2099. var $_lastPageNo = -1;
  2100. var $_maxRecordCount = 0;
  2101. var $datetime = false;
  2102. /**
  2103. * Constructor
  2104. *
  2105. * @param queryID this is the queryID returned by ADOConnection->_query()
  2106. *
  2107. */
  2108. function ADORecordSet($queryID)
  2109. {
  2110. $this->_queryID = $queryID;
  2111. }
  2112. function Init()
  2113. {
  2114. if ($this->_inited) return;
  2115. $this->_inited = true;
  2116. if ($this->_queryID) @$this->_initrs();
  2117. else {
  2118. $this->_numOfRows = 0;
  2119. $this->_numOfFields = 0;
  2120. }
  2121. if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
  2122. $this->_currentRow = 0;
  2123. if ($this->EOF = ($this->_fetch() === false)) {
  2124. $this->_numOfRows = 0; // _numOfRows could be -1
  2125. }
  2126. } else {
  2127. $this->EOF = true;
  2128. }
  2129. }
  2130. /**
  2131. * Generate a SELECT tag string from a recordset, and return the string.
  2132. * If the recordset has 2 cols, we treat the 1st col as the containing
  2133. * the text to display to the user, and 2nd col as the return value. Default
  2134. * strings are compared with the FIRST column.
  2135. *
  2136. * @param name name of SELECT tag
  2137. * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
  2138. * @param [blank1stItem] true to leave the 1st item in list empty
  2139. * @param [multiple] true for listbox, false for popup
  2140. * @param [size] #rows to show for listbox. not used by popup
  2141. * @param [selectAttr] additional attributes to defined for SELECT tag.
  2142. * useful for holding javascript onChange='...' handlers.
  2143. & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
  2144. * column 0 (1st col) if this is true. This is not documented.
  2145. *
  2146. * @return HTML
  2147. *
  2148. * changes by glen.davies@cce.ac.nz to support multiple hilited items
  2149. */
  2150. function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
  2151. $size=0, $selectAttr='',$compareFields0=true)
  2152. {
  2153. global $ADODB_INCLUDED_LIB;
  2154. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  2155. return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
  2156. $size, $selectAttr,$compareFields0);
  2157. }
  2158. /**
  2159. * Generate a SELECT tag string from a recordset, and return the string.
  2160. * If the recordset has 2 cols, we treat the 1st col as the containing
  2161. * the text to display to the user, and 2nd col as the return value. Default
  2162. * strings are compared with the SECOND column.
  2163. *
  2164. */
  2165. function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
  2166. {
  2167. global $ADODB_INCLUDED_LIB;
  2168. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  2169. return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,
  2170. $size, $selectAttr,false);
  2171. }
  2172. /**
  2173. * return recordset as a 2-dimensional array.
  2174. *
  2175. * @param [nRows] is the number of rows to return. -1 means every row.
  2176. *
  2177. * @return an array indexed by the rows (0-based) from the recordset
  2178. */
  2179. function &GetArray($nRows = -1)
  2180. {
  2181. global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);
  2182. $results = array();
  2183. $cnt = 0;
  2184. while (!$this->EOF && $nRows != $cnt) {
  2185. $results[] = $this->fields;
  2186. $this->MoveNext();
  2187. $cnt++;
  2188. }
  2189. return $results;
  2190. }
  2191. function &GetAll($nRows = -1)
  2192. {
  2193. $arr =& $this->GetArray($nRows);
  2194. return $arr;
  2195. }
  2196. /*
  2197. * Some databases allow multiple recordsets to be returned. This function
  2198. * will return true if there is a next recordset, or false if no more.
  2199. */
  2200. function NextRecordSet()
  2201. {
  2202. return false;
  2203. }
  2204. /**
  2205. * return recordset as a 2-dimensional array.
  2206. * Helper function for ADOConnection->SelectLimit()
  2207. *
  2208. * @param offset is the row to start calculations from (1-based)
  2209. * @param [nrows] is the number of rows to return
  2210. *
  2211. * @return an array indexed by the rows (0-based) from the recordset
  2212. */
  2213. function &GetArrayLimit($nrows,$offset=-1)
  2214. {
  2215. if ($offset <= 0) {
  2216. $arr =& $this->GetArray($nrows);
  2217. return $arr;
  2218. }
  2219. $this->Move($offset);
  2220. $results = array();
  2221. $cnt = 0;
  2222. while (!$this->EOF && $nrows != $cnt) {
  2223. $results[$cnt++] = $this->fields;
  2224. $this->MoveNext();
  2225. }
  2226. return $results;
  2227. }
  2228. /**
  2229. * Synonym for GetArray() for compatibility with ADO.
  2230. *
  2231. * @param [nRows] is the number of rows to return. -1 means every row.
  2232. *
  2233. * @return an array indexed by the rows (0-based) from the recordset
  2234. */
  2235. function &GetRows($nRows = -1)
  2236. {
  2237. $arr =& $this->GetArray($nRows);
  2238. return $arr;
  2239. }
  2240. /**
  2241. * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
  2242. * The first column is treated as the key and is not included in the array.
  2243. * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
  2244. * $force_array == true.
  2245. *
  2246. * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
  2247. * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
  2248. * read the source.
  2249. *
  2250. * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
  2251. * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
  2252. *
  2253. * @return an associative array indexed by the first column of the array,
  2254. * or false if the data has less than 2 cols.
  2255. */
  2256. function &GetAssoc($force_array = false, $first2cols = false)
  2257. {
  2258. global $ADODB_EXTENSION;
  2259. $cols = $this->_numOfFields;
  2260. if ($cols < 2) {
  2261. $false = false;
  2262. return $false;
  2263. }
  2264. $numIndex = isset($this->fields[0]);
  2265. $results = array();
  2266. if (!$first2cols && ($cols > 2 || $force_array)) {
  2267. if ($ADODB_EXTENSION) {
  2268. if ($numIndex) {
  2269. while (!$this->EOF) {
  2270. $results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2271. adodb_movenext($this);
  2272. }
  2273. } else {
  2274. while (!$this->EOF) {
  2275. $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
  2276. adodb_movenext($this);
  2277. }
  2278. }
  2279. } else {
  2280. if ($numIndex) {
  2281. while (!$this->EOF) {
  2282. $results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2283. $this->MoveNext();
  2284. }
  2285. } else {
  2286. while (!$this->EOF) {
  2287. $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
  2288. $this->MoveNext();
  2289. }
  2290. }
  2291. }
  2292. } else {
  2293. if ($ADODB_EXTENSION) {
  2294. // return scalar values
  2295. if ($numIndex) {
  2296. while (!$this->EOF) {
  2297. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2298. $results[trim(($this->fields[0]))] = $this->fields[1];
  2299. adodb_movenext($this);
  2300. }
  2301. } else {
  2302. while (!$this->EOF) {
  2303. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2304. $v1 = trim(reset($this->fields));
  2305. $v2 = ''.next($this->fields);
  2306. $results[$v1] = $v2;
  2307. adodb_movenext($this);
  2308. }
  2309. }
  2310. } else {
  2311. if ($numIndex) {
  2312. while (!$this->EOF) {
  2313. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2314. $results[trim(($this->fields[0]))] = $this->fields[1];
  2315. $this->MoveNext();
  2316. }
  2317. } else {
  2318. while (!$this->EOF) {
  2319. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2320. $v1 = trim(reset($this->fields));
  2321. $v2 = ''.next($this->fields);
  2322. $results[$v1] = $v2;
  2323. $this->MoveNext();
  2324. }
  2325. }
  2326. }
  2327. }
  2328. return $results;
  2329. }
  2330. /**
  2331. *
  2332. * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
  2333. * @param fmt is the format to apply to it, using date()
  2334. *
  2335. * @return a timestamp formated as user desires
  2336. */
  2337. function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
  2338. {
  2339. if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
  2340. $tt = $this->UnixTimeStamp($v);
  2341. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2342. if (($tt === false || $tt == -1) && $v != false) return $v;
  2343. if ($tt === 0) return $this->emptyTimeStamp;
  2344. return adodb_date($fmt,$tt);
  2345. }
  2346. /**
  2347. * @param v is the character date in YYYY-MM-DD format, returned by database
  2348. * @param fmt is the format to apply to it, using date()
  2349. *
  2350. * @return a date formated as user desires
  2351. */
  2352. function UserDate($v,$fmt='Y-m-d')
  2353. {
  2354. $tt = $this->UnixDate($v);
  2355. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2356. if (($tt === false || $tt == -1) && $v != false) return $v;
  2357. else if ($tt == 0) return $this->emptyDate;
  2358. else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  2359. }
  2360. return adodb_date($fmt,$tt);
  2361. }
  2362. /**
  2363. * @param $v is a date string in YYYY-MM-DD format
  2364. *
  2365. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2366. */
  2367. function UnixDate($v)
  2368. {
  2369. return ADOConnection::UnixDate($v);
  2370. }
  2371. /**
  2372. * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  2373. *
  2374. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2375. */
  2376. function UnixTimeStamp($v)
  2377. {
  2378. return ADOConnection::UnixTimeStamp($v);
  2379. }
  2380. /**
  2381. * PEAR DB Compat - do not use internally
  2382. */
  2383. function Free()
  2384. {
  2385. return $this->Close();
  2386. }
  2387. /**
  2388. * PEAR DB compat, number of rows
  2389. */
  2390. function NumRows()
  2391. {
  2392. return $this->_numOfRows;
  2393. }
  2394. /**
  2395. * PEAR DB compat, number of cols
  2396. */
  2397. function NumCols()
  2398. {
  2399. return $this->_numOfFields;
  2400. }
  2401. /**
  2402. * Fetch a row, returning false if no more rows.
  2403. * This is PEAR DB compat mode.
  2404. *
  2405. * @return false or array containing the current record
  2406. */
  2407. function &FetchRow()
  2408. {
  2409. if ($this->EOF) {
  2410. $false = false;
  2411. return $false;
  2412. }
  2413. $arr = $this->fields;
  2414. $this->_currentRow++;
  2415. if (!$this->_fetch()) $this->EOF = true;
  2416. return $arr;
  2417. }
  2418. /**
  2419. * Fetch a row, returning PEAR_Error if no more rows.
  2420. * This is PEAR DB compat mode.
  2421. *
  2422. * @return DB_OK or error object
  2423. */
  2424. function FetchInto(&$arr)
  2425. {
  2426. if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
  2427. $arr = $this->fields;
  2428. $this->MoveNext();
  2429. return 1; // DB_OK
  2430. }
  2431. /**
  2432. * Move to the first row in the recordset. Many databases do NOT support this.
  2433. *
  2434. * @return true or false
  2435. */
  2436. function MoveFirst()
  2437. {
  2438. if ($this->_currentRow == 0) return true;
  2439. return $this->Move(0);
  2440. }
  2441. /**
  2442. * Move to the last row in the recordset.
  2443. *
  2444. * @return true or false
  2445. */
  2446. function MoveLast()
  2447. {
  2448. if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
  2449. if ($this->EOF) return false;
  2450. while (!$this->EOF) {
  2451. $f = $this->fields;
  2452. $this->MoveNext();
  2453. }
  2454. $this->fields = $f;
  2455. $this->EOF = false;
  2456. return true;
  2457. }
  2458. /**
  2459. * Move to next record in the recordset.
  2460. *
  2461. * @return true if there still rows available, or false if there are no more rows (EOF).
  2462. */
  2463. function MoveNext()
  2464. {
  2465. if (!$this->EOF) {
  2466. $this->_currentRow++;
  2467. if ($this->_fetch()) return true;
  2468. }
  2469. $this->EOF = true;
  2470. /* -- tested error handling when scrolling cursor -- seems useless.
  2471. $conn = $this->connection;
  2472. if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
  2473. $fn = $conn->raiseErrorFn;
  2474. $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
  2475. }
  2476. */
  2477. return false;
  2478. }
  2479. /**
  2480. * Random access to a specific row in the recordset. Some databases do not support
  2481. * access to previous rows in the databases (no scrolling backwards).
  2482. *
  2483. * @param rowNumber is the row to move to (0-based)
  2484. *
  2485. * @return true if there still rows available, or false if there are no more rows (EOF).
  2486. */
  2487. function Move($rowNumber = 0)
  2488. {
  2489. $this->EOF = false;
  2490. if ($rowNumber == $this->_currentRow) return true;
  2491. if ($rowNumber >= $this->_numOfRows)
  2492. if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
  2493. if ($this->canSeek) {
  2494. if ($this->_seek($rowNumber)) {
  2495. $this->_currentRow = $rowNumber;
  2496. if ($this->_fetch()) {
  2497. return true;
  2498. }
  2499. } else {
  2500. $this->EOF = true;
  2501. return false;
  2502. }
  2503. } else {
  2504. if ($rowNumber < $this->_currentRow) return false;
  2505. global $ADODB_EXTENSION;
  2506. if ($ADODB_EXTENSION) {
  2507. while (!$this->EOF && $this->_currentRow < $rowNumber) {
  2508. adodb_movenext($this);
  2509. }
  2510. } else {
  2511. while (! $this->EOF && $this->_currentRow < $rowNumber) {
  2512. $this->_currentRow++;
  2513. if (!$this->_fetch()) $this->EOF = true;
  2514. }
  2515. }
  2516. return !($this->EOF);
  2517. }
  2518. $this->fields = false;
  2519. $this->EOF = true;
  2520. return false;
  2521. }
  2522. /**
  2523. * Get the value of a field in the current row by column name.
  2524. * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
  2525. *
  2526. * @param colname is the field to access
  2527. *
  2528. * @return the value of $colname column
  2529. */
  2530. function Fields($colname)
  2531. {
  2532. return $this->fields[$colname];
  2533. }
  2534. function GetAssocKeys($upper=true)
  2535. {
  2536. $this->bind = array();
  2537. for ($i=0; $i < $this->_numOfFields; $i++) {
  2538. $o =& $this->FetchField($i);
  2539. if ($upper === 2) $this->bind[$o->name] = $i;
  2540. else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
  2541. }
  2542. }
  2543. /**
  2544. * Use associative array to get fields array for databases that do not support
  2545. * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it
  2546. *
  2547. * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
  2548. * before you execute your SQL statement, and access $rs->fields['col'] directly.
  2549. *
  2550. * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
  2551. */
  2552. function &GetRowAssoc($upper=1)
  2553. {
  2554. $record = array();
  2555. // if (!$this->fields) return $record;
  2556. if (!$this->bind) {
  2557. $this->GetAssocKeys($upper);
  2558. }
  2559. foreach($this->bind as $k => $v) {
  2560. $record[$k] = $this->fields[$v];
  2561. }
  2562. return $record;
  2563. }
  2564. /**
  2565. * Clean up recordset
  2566. *
  2567. * @return true or false
  2568. */
  2569. function Close()
  2570. {
  2571. // free connection object - this seems to globally free the object
  2572. // and not merely the reference, so don't do this...
  2573. // $this->connection = false;
  2574. if (!$this->_closed) {
  2575. $this->_closed = true;
  2576. return $this->_close();
  2577. } else
  2578. return true;
  2579. }
  2580. /**
  2581. * synonyms RecordCount and RowCount
  2582. *
  2583. * @return the number of rows or -1 if this is not supported
  2584. */
  2585. function RecordCount() {return $this->_numOfRows;}
  2586. /*
  2587. * If we are using PageExecute(), this will return the maximum possible rows
  2588. * that can be returned when paging a recordset.
  2589. */
  2590. function MaxRecordCount()
  2591. {
  2592. return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
  2593. }
  2594. /**
  2595. * synonyms RecordCount and RowCount
  2596. *
  2597. * @return the number of rows or -1 if this is not supported
  2598. */
  2599. function RowCount() {return $this->_numOfRows;}
  2600. /**
  2601. * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
  2602. *
  2603. * @return the number of records from a previous SELECT. All databases support this.
  2604. *
  2605. * But aware possible problems in multiuser environments. For better speed the table
  2606. * must be indexed by the condition. Heavy test this before deploying.
  2607. */
  2608. function PO_RecordCount($table="", $condition="") {
  2609. $lnumrows = $this->_numOfRows;
  2610. // the database doesn't support native recordcount, so we do a workaround
  2611. if ($lnumrows == -1 && $this->connection) {
  2612. IF ($table) {
  2613. if ($condition) $condition = " WHERE " . $condition;
  2614. $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
  2615. if ($resultrows) $lnumrows = reset($resultrows->fields);
  2616. }
  2617. }
  2618. return $lnumrows;
  2619. }
  2620. /**
  2621. * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  2622. */
  2623. function CurrentRow() {return $this->_currentRow;}
  2624. /**
  2625. * synonym for CurrentRow -- for ADO compat
  2626. *
  2627. * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  2628. */
  2629. function AbsolutePosition() {return $this->_currentRow;}
  2630. /**
  2631. * @return the number of columns in the recordset. Some databases will set this to 0
  2632. * if no records are returned, others will return the number of columns in the query.
  2633. */
  2634. function FieldCount() {return $this->_numOfFields;}
  2635. /**
  2636. * Get the ADOFieldObject of a specific column.
  2637. *
  2638. * @param fieldoffset is the column position to access(0-based).
  2639. *
  2640. * @return the ADOFieldObject for that column, or false.
  2641. */
  2642. function &FetchField($fieldoffset)
  2643. {
  2644. // must be defined by child class
  2645. }
  2646. /**
  2647. * Get the ADOFieldObjects of all columns in an array.
  2648. *
  2649. */
  2650. function& FieldTypesArray()
  2651. {
  2652. $arr = array();
  2653. for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
  2654. $arr[] = $this->FetchField($i);
  2655. return $arr;
  2656. }
  2657. /**
  2658. * Return the fields array of the current row as an object for convenience.
  2659. * The default case is lowercase field names.
  2660. *
  2661. * @return the object with the properties set to the fields of the current row
  2662. */
  2663. function &FetchObj()
  2664. {
  2665. $o =& $this->FetchObject(false);
  2666. return $o;
  2667. }
  2668. /**
  2669. * Return the fields array of the current row as an object for convenience.
  2670. * The default case is uppercase.
  2671. *
  2672. * @param $isupper to set the object property names to uppercase
  2673. *
  2674. * @return the object with the properties set to the fields of the current row
  2675. */
  2676. function &FetchObject($isupper=true)
  2677. {
  2678. if (empty($this->_obj)) {
  2679. $this->_obj =& new ADOFetchObj();
  2680. $this->_names = array();
  2681. for ($i=0; $i <$this->_numOfFields; $i++) {
  2682. $f = $this->FetchField($i);
  2683. $this->_names[] = $f->name;
  2684. }
  2685. }
  2686. $i = 0;
  2687. if (PHP_VERSION >= 5) $o = clone($this->_obj);
  2688. else $o = $this->_obj;
  2689. for ($i=0; $i <$this->_numOfFields; $i++) {
  2690. $name = $this->_names[$i];
  2691. if ($isupper) $n = strtoupper($name);
  2692. else $n = $name;
  2693. $o->$n = $this->Fields($name);
  2694. }
  2695. return $o;
  2696. }
  2697. /**
  2698. * Return the fields array of the current row as an object for convenience.
  2699. * The default is lower-case field names.
  2700. *
  2701. * @return the object with the properties set to the fields of the current row,
  2702. * or false if EOF
  2703. *
  2704. * Fixed bug reported by tim@orotech.net
  2705. */
  2706. function &FetchNextObj()
  2707. {
  2708. $o =& $this->FetchNextObject(false);
  2709. return $o;
  2710. }
  2711. /**
  2712. * Return the fields array of the current row as an object for convenience.
  2713. * The default is upper case field names.
  2714. *
  2715. * @param $isupper to set the object property names to uppercase
  2716. *
  2717. * @return the object with the properties set to the fields of the current row,
  2718. * or false if EOF
  2719. *
  2720. * Fixed bug reported by tim@orotech.net
  2721. */
  2722. function &FetchNextObject($isupper=true)
  2723. {
  2724. $o = false;
  2725. if ($this->_numOfRows != 0 && !$this->EOF) {
  2726. $o = $this->FetchObject($isupper);
  2727. $this->_currentRow++;
  2728. if ($this->_fetch()) return $o;
  2729. }
  2730. $this->EOF = true;
  2731. return $o;
  2732. }
  2733. /**
  2734. * Get the metatype of the column. This is used for formatting. This is because
  2735. * many databases use different names for the same type, so we transform the original
  2736. * type to our standardised version which uses 1 character codes:
  2737. *
  2738. * @param t is the type passed in. Normally is ADOFieldObject->type.
  2739. * @param len is the maximum length of that field. This is because we treat character
  2740. * fields bigger than a certain size as a 'B' (blob).
  2741. * @param fieldobj is the field object returned by the database driver. Can hold
  2742. * additional info (eg. primary_key for mysql).
  2743. *
  2744. * @return the general type of the data:
  2745. * C for character < 250 chars
  2746. * X for teXt (>= 250 chars)
  2747. * B for Binary
  2748. * N for numeric or floating point
  2749. * D for date
  2750. * T for timestamp
  2751. * L for logical/Boolean
  2752. * I for integer
  2753. * R for autoincrement counter/integer
  2754. *
  2755. *
  2756. */
  2757. function MetaType($t,$len=-1,$fieldobj=false)
  2758. {
  2759. if (is_object($t)) {
  2760. $fieldobj = $t;
  2761. $t = $fieldobj->type;
  2762. $len = $fieldobj->max_length;
  2763. }
  2764. // changed in 2.32 to hashing instead of switch stmt for speed...
  2765. static $typeMap = array(
  2766. 'VARCHAR' => 'C',
  2767. 'VARCHAR2' => 'C',
  2768. 'CHAR' => 'C',
  2769. 'C' => 'C',
  2770. 'STRING' => 'C',
  2771. 'NCHAR' => 'C',
  2772. 'NVARCHAR' => 'C',
  2773. 'VARYING' => 'C',
  2774. 'BPCHAR' => 'C',
  2775. 'CHARACTER' => 'C',
  2776. 'INTERVAL' => 'C', # Postgres
  2777. ##
  2778. 'LONGCHAR' => 'X',
  2779. 'TEXT' => 'X',
  2780. 'NTEXT' => 'X',
  2781. 'M' => 'X',
  2782. 'X' => 'X',
  2783. 'CLOB' => 'X',
  2784. 'NCLOB' => 'X',
  2785. 'LVARCHAR' => 'X',
  2786. ##
  2787. 'BLOB' => 'B',
  2788. 'IMAGE' => 'B',
  2789. 'BINARY' => 'B',
  2790. 'VARBINARY' => 'B',
  2791. 'LONGBINARY' => 'B',
  2792. 'B' => 'B',
  2793. ##
  2794. 'YEAR' => 'D', // mysql
  2795. 'DATE' => 'D',
  2796. 'D' => 'D',
  2797. ##
  2798. 'TIME' => 'T',
  2799. 'TIMESTAMP' => 'T',
  2800. 'DATETIME' => 'T',
  2801. 'TIMESTAMPTZ' => 'T',
  2802. 'T' => 'T',
  2803. ##
  2804. 'BOOL' => 'L',
  2805. 'BOOLEAN' => 'L',
  2806. 'BIT' => 'L',
  2807. 'L' => 'L',
  2808. ##
  2809. 'COUNTER' => 'R',
  2810. 'R' => 'R',
  2811. 'SERIAL' => 'R', // ifx
  2812. 'INT IDENTITY' => 'R',
  2813. ##
  2814. 'INT' => 'I',
  2815. 'INT2' => 'I',
  2816. 'INT4' => 'I',
  2817. 'INT8' => 'I',
  2818. 'INTEGER' => 'I',
  2819. 'INTEGER UNSIGNED' => 'I',
  2820. 'SHORT' => 'I',
  2821. 'TINYINT' => 'I',
  2822. 'SMALLINT' => 'I',
  2823. 'I' => 'I',
  2824. ##
  2825. 'LONG' => 'N', // interbase is numeric, oci8 is blob
  2826. 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
  2827. 'DECIMAL' => 'N',
  2828. 'DEC' => 'N',
  2829. 'REAL' => 'N',
  2830. 'DOUBLE' => 'N',
  2831. 'DOUBLE PRECISION' => 'N',
  2832. 'SMALLFLOAT' => 'N',
  2833. 'FLOAT' => 'N',
  2834. 'NUMBER' => 'N',
  2835. 'NUM' => 'N',
  2836. 'NUMERIC' => 'N',
  2837. 'MONEY' => 'N',
  2838. ## informix 9.2
  2839. 'SQLINT' => 'I',
  2840. 'SQLSERIAL' => 'I',
  2841. 'SQLSMINT' => 'I',
  2842. 'SQLSMFLOAT' => 'N',
  2843. 'SQLFLOAT' => 'N',
  2844. 'SQLMONEY' => 'N',
  2845. 'SQLDECIMAL' => 'N',
  2846. 'SQLDATE' => 'D',
  2847. 'SQLVCHAR' => 'C',
  2848. 'SQLCHAR' => 'C',
  2849. 'SQLDTIME' => 'T',
  2850. 'SQLINTERVAL' => 'N',
  2851. 'SQLBYTES' => 'B',
  2852. 'SQLTEXT' => 'X'
  2853. );
  2854. $tmap = false;
  2855. $t = strtoupper($t);
  2856. $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
  2857. switch ($tmap) {
  2858. case 'C':
  2859. // is the char field is too long, return as text field...
  2860. if ($this->blobSize >= 0) {
  2861. if ($len > $this->blobSize) return 'X';
  2862. } else if ($len > 250) {
  2863. return 'X';
  2864. }
  2865. return 'C';
  2866. case 'I':
  2867. if (!empty($fieldobj->primary_key)) return 'R';
  2868. return 'I';
  2869. case false:
  2870. return 'N';
  2871. case 'B':
  2872. if (isset($fieldobj->binary))
  2873. return ($fieldobj->binary) ? 'B' : 'X';
  2874. return 'B';
  2875. case 'D':
  2876. if (!empty($this->datetime)) return 'T';
  2877. return 'D';
  2878. default:
  2879. if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
  2880. return $tmap;
  2881. }
  2882. }
  2883. function _close() {}
  2884. /**
  2885. * set/returns the current recordset page when paginating
  2886. */
  2887. function AbsolutePage($page=-1)
  2888. {
  2889. if ($page != -1) $this->_currentPage = $page;
  2890. return $this->_currentPage;
  2891. }
  2892. /**
  2893. * set/returns the status of the atFirstPage flag when paginating
  2894. */
  2895. function AtFirstPage($status=false)
  2896. {
  2897. if ($status != false) $this->_atFirstPage = $status;
  2898. return $this->_atFirstPage;
  2899. }
  2900. function LastPageNo($page = false)
  2901. {
  2902. if ($page != false) $this->_lastPageNo = $page;
  2903. return $this->_lastPageNo;
  2904. }
  2905. /**
  2906. * set/returns the status of the atLastPage flag when paginating
  2907. */
  2908. function AtLastPage($status=false)
  2909. {
  2910. if ($status != false) $this->_atLastPage = $status;
  2911. return $this->_atLastPage;
  2912. }
  2913. } // end class ADORecordSet
  2914. //==============================================================================================
  2915. // CLASS ADORecordSet_array
  2916. //==============================================================================================
  2917. /**
  2918. * This class encapsulates the concept of a recordset created in memory
  2919. * as an array. This is useful for the creation of cached recordsets.
  2920. *
  2921. * Note that the constructor is different from the standard ADORecordSet
  2922. */
  2923. class ADORecordSet_array extends ADORecordSet
  2924. {
  2925. var $databaseType = 'array';
  2926. var $_array; // holds the 2-dimensional data array
  2927. var $_types; // the array of types of each column (C B I L M)
  2928. var $_colnames; // names of each column in array
  2929. var $_skiprow1; // skip 1st row because it holds column names
  2930. var $_fieldarr; // holds array of field objects
  2931. var $canSeek = true;
  2932. var $affectedrows = false;
  2933. var $insertid = false;
  2934. var $sql = '';
  2935. var $compat = false;
  2936. /**
  2937. * Constructor
  2938. *
  2939. */
  2940. function ADORecordSet_array($fakeid=1)
  2941. {
  2942. global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
  2943. // fetch() on EOF does not delete $this->fields
  2944. $this->compat = !empty($ADODB_COMPAT_FETCH);
  2945. $this->ADORecordSet($fakeid); // fake queryID
  2946. $this->fetchMode = $ADODB_FETCH_MODE;
  2947. }
  2948. /**
  2949. * Setup the array.
  2950. *
  2951. * @param array is a 2-dimensional array holding the data.
  2952. * The first row should hold the column names
  2953. * unless paramter $colnames is used.
  2954. * @param typearr holds an array of types. These are the same types
  2955. * used in MetaTypes (C,B,L,I,N).
  2956. * @param [colnames] array of column names. If set, then the first row of
  2957. * $array should not hold the column names.
  2958. */
  2959. function InitArray($array,$typearr,$colnames=false)
  2960. {
  2961. $this->_array = $array;
  2962. $this->_types = $typearr;
  2963. if ($colnames) {
  2964. $this->_skiprow1 = false;
  2965. $this->_colnames = $colnames;
  2966. } else {
  2967. $this->_skiprow1 = true;
  2968. $this->_colnames = $array[0];
  2969. }
  2970. $this->Init();
  2971. }
  2972. /**
  2973. * Setup the Array and datatype file objects
  2974. *
  2975. * @param array is a 2-dimensional array holding the data.
  2976. * The first row should hold the column names
  2977. * unless paramter $colnames is used.
  2978. * @param fieldarr holds an array of ADOFieldObject's.
  2979. */
  2980. function InitArrayFields(&$array,&$fieldarr)
  2981. {
  2982. $this->_array =& $array;
  2983. $this->_skiprow1= false;
  2984. if ($fieldarr) {
  2985. $this->_fieldobjects =& $fieldarr;
  2986. }
  2987. $this->Init();
  2988. }
  2989. function &GetArray($nRows=-1)
  2990. {
  2991. if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
  2992. return $this->_array;
  2993. } else {
  2994. $arr =& ADORecordSet::GetArray($nRows);
  2995. return $arr;
  2996. }
  2997. }
  2998. function _initrs()
  2999. {
  3000. $this->_numOfRows = sizeof($this->_array);
  3001. if ($this->_skiprow1) $this->_numOfRows -= 1;
  3002. $this->_numOfFields =(isset($this->_fieldobjects)) ?
  3003. sizeof($this->_fieldobjects):sizeof($this->_types);
  3004. }
  3005. /* Use associative array to get fields array */
  3006. function Fields($colname)
  3007. {
  3008. $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode;
  3009. if ($mode & ADODB_FETCH_ASSOC) {
  3010. if (!isset($this->fields[$colname])) $colname = strtolower($colname);
  3011. return $this->fields[$colname];
  3012. }
  3013. if (!$this->bind) {
  3014. $this->bind = array();
  3015. for ($i=0; $i < $this->_numOfFields; $i++) {
  3016. $o = $this->FetchField($i);
  3017. $this->bind[strtoupper($o->name)] = $i;
  3018. }
  3019. }
  3020. return $this->fields[$this->bind[strtoupper($colname)]];
  3021. }
  3022. function &FetchField($fieldOffset = -1)
  3023. {
  3024. if (isset($this->_fieldobjects)) {
  3025. return $this->_fieldobjects[$fieldOffset];
  3026. }
  3027. $o = new ADOFieldObject();
  3028. $o->name = $this->_colnames[$fieldOffset];
  3029. $o->type = $this->_types[$fieldOffset];
  3030. $o->max_length = -1; // length not known
  3031. return $o;
  3032. }
  3033. function _seek($row)
  3034. {
  3035. if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
  3036. $this->_currentRow = $row;
  3037. if ($this->_skiprow1) $row += 1;
  3038. $this->fields = $this->_array[$row];
  3039. return true;
  3040. }
  3041. return false;
  3042. }
  3043. function MoveNext()
  3044. {
  3045. if (!$this->EOF) {
  3046. $this->_currentRow++;
  3047. $pos = $this->_currentRow;
  3048. if ($this->_numOfRows <= $pos) {
  3049. if (!$this->compat) $this->fields = false;
  3050. } else {
  3051. if ($this->_skiprow1) $pos += 1;
  3052. $this->fields = $this->_array[$pos];
  3053. return true;
  3054. }
  3055. $this->EOF = true;
  3056. }
  3057. return false;
  3058. }
  3059. function _fetch()
  3060. {
  3061. $pos = $this->_currentRow;
  3062. if ($this->_numOfRows <= $pos) {
  3063. if (!$this->compat) $this->fields = false;
  3064. return false;
  3065. }
  3066. if ($this->_skiprow1) $pos += 1;
  3067. $this->fields = $this->_array[$pos];
  3068. return true;
  3069. }
  3070. function _close()
  3071. {
  3072. return true;
  3073. }
  3074. } // ADORecordSet_array
  3075. //==============================================================================================
  3076. // HELPER FUNCTIONS
  3077. //==============================================================================================
  3078. /**
  3079. * Synonym for ADOLoadCode. Private function. Do not use.
  3080. *
  3081. * @deprecated
  3082. */
  3083. function ADOLoadDB($dbType)
  3084. {
  3085. return ADOLoadCode($dbType);
  3086. }
  3087. /**
  3088. * Load the code for a specific database driver. Private function. Do not use.
  3089. */
  3090. function ADOLoadCode($dbType)
  3091. {
  3092. global $ADODB_LASTDB;
  3093. if (!$dbType) return false;
  3094. $db = strtolower($dbType);
  3095. switch ($db) {
  3096. case 'ado':
  3097. if (PHP_VERSION >= 5) $db = 'ado5';
  3098. $class = 'ado';
  3099. break;
  3100. case 'ifx':
  3101. case 'maxsql': $class = $db = 'mysqlt'; break;
  3102. case 'postgres':
  3103. case 'postgres8':
  3104. case 'pgsql': $class = $db = 'postgres7'; break;
  3105. default:
  3106. $class = $db; break;
  3107. }
  3108. $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
  3109. @include_once($file);
  3110. $ADODB_LASTDB = $class;
  3111. if (class_exists("ADODB_" . $db)) return $class;
  3112. //ADOConnection::outp(adodb_pr(get_declared_classes(),true));
  3113. if (!file_exists($file)) ADOConnection::outp("Missing file: $file");
  3114. else ADOConnection::outp("Syntax error in file: $file");
  3115. return false;
  3116. }
  3117. /**
  3118. * synonym for ADONewConnection for people like me who cannot remember the correct name
  3119. */
  3120. function &NewADOConnection($db='')
  3121. {
  3122. $tmp =& ADONewConnection($db);
  3123. return $tmp;
  3124. }
  3125. /**
  3126. * Instantiate a new Connection class for a specific database driver.
  3127. *
  3128. * @param [db] is the database Connection object to create. If undefined,
  3129. * use the last database driver that was loaded by ADOLoadCode().
  3130. *
  3131. * @return the freshly created instance of the Connection class.
  3132. */
  3133. function &ADONewConnection($db='')
  3134. {
  3135. GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
  3136. if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  3137. $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
  3138. $false = false;
  3139. if (strpos($db,'://')) {
  3140. $origdsn = $db;
  3141. $dsna = @parse_url($db);
  3142. if (!$dsna) {
  3143. // special handling of oracle, which might not have host
  3144. $db = str_replace('@/','@adodb-fakehost/',$db);
  3145. $dsna = parse_url($db);
  3146. if (!$dsna) return $false;
  3147. $dsna['host'] = '';
  3148. }
  3149. $db = @$dsna['scheme'];
  3150. if (!$db) return $false;
  3151. $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
  3152. $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : '';
  3153. $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : '';
  3154. $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : '';
  3155. if (isset($dsna['query'])) {
  3156. $opt1 = explode('&',$dsna['query']);
  3157. foreach($opt1 as $k => $v) {
  3158. $arr = explode('=',$v);
  3159. $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1;
  3160. }
  3161. } else $opt = array();
  3162. }
  3163. /*
  3164. * phptype: Database backend used in PHP (mysql, odbc etc.)
  3165. * dbsyntax: Database used with regards to SQL syntax etc.
  3166. * protocol: Communication protocol to use (tcp, unix etc.)
  3167. * hostspec: Host specification (hostname[:port])
  3168. * database: Database to use on the DBMS server
  3169. * username: User name for login
  3170. * password: Password for login
  3171. */
  3172. if (!empty($ADODB_NEWCONNECTION)) {
  3173. $obj = $ADODB_NEWCONNECTION($db);
  3174. } else {
  3175. if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
  3176. if (empty($db)) $db = $ADODB_LASTDB;
  3177. if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
  3178. if (!$db) {
  3179. if (isset($origdsn)) $db = $origdsn;
  3180. if ($errorfn) {
  3181. // raise an error
  3182. $ignore = false;
  3183. $errorfn('ADONewConnection', 'ADONewConnection', -998,
  3184. "could not load the database driver for '$db'",
  3185. $db,false,$ignore);
  3186. } else
  3187. ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
  3188. return $false;
  3189. }
  3190. $cls = 'ADODB_'.$db;
  3191. if (!class_exists($cls)) {
  3192. adodb_backtrace();
  3193. return $false;
  3194. }
  3195. $obj =& new $cls();
  3196. }
  3197. # constructor should not fail
  3198. if ($obj) {
  3199. if ($errorfn) $obj->raiseErrorFn = $errorfn;
  3200. if (isset($dsna)) {
  3201. foreach($opt as $k => $v) {
  3202. switch(strtolower($k)) {
  3203. case 'persist':
  3204. case 'persistent': $persist = $v; break;
  3205. case 'debug': $obj->debug = (integer) $v; break;
  3206. #ibase
  3207. case 'dialect': $obj->dialect = (integer) $v; break;
  3208. case 'charset': $obj->charset = $v; break;
  3209. case 'buffers': $obj->buffers = $v; break;
  3210. case 'fetchmode': $obj->SetFetchMode($v); break;
  3211. #ado
  3212. case 'charpage': $obj->charPage = $v; break;
  3213. #mysql, mysqli
  3214. case 'clientflags': $obj->clientFlags = $v; break;
  3215. #mysqli
  3216. case 'port': $obj->port = $v; break;
  3217. case 'socket': $obj->socket = $v; break;
  3218. #oci8
  3219. case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break;
  3220. }
  3221. }
  3222. if (empty($persist))
  3223. $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3224. else
  3225. $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3226. if (!$ok) return $false;
  3227. }
  3228. }
  3229. return $obj;
  3230. }
  3231. // $perf == true means called by NewPerfMonitor()
  3232. function _adodb_getdriver($provider,$drivername,$perf=false)
  3233. {
  3234. switch ($provider) {
  3235. case 'odbtp': if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6);
  3236. case 'odbc' : if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5);
  3237. case 'ado' : if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4);
  3238. case 'native': break;
  3239. default:
  3240. return $provider;
  3241. }
  3242. switch($drivername) {
  3243. case 'oracle': $drivername = 'oci8'; break;
  3244. case 'access': if ($perf) $drivername = ''; break;
  3245. case 'db2' : break;
  3246. case 'sapdb' : break;
  3247. default:
  3248. $drivername = 'generic';
  3249. break;
  3250. }
  3251. return $drivername;
  3252. }
  3253. function &NewPerfMonitor(&$conn)
  3254. {
  3255. $false = false;
  3256. $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
  3257. if (!$drivername || $drivername == 'generic') return $false;
  3258. include_once(ADODB_DIR.'/adodb-perf.inc.php');
  3259. @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
  3260. $class = "Perf_$drivername";
  3261. if (!class_exists($class)) return $false;
  3262. $perf =& new $class($conn);
  3263. return $perf;
  3264. }
  3265. function &NewDataDictionary(&$conn,$drivername=false)
  3266. {
  3267. $false = false;
  3268. if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
  3269. include_once(ADODB_DIR.'/adodb-lib.inc.php');
  3270. include_once(ADODB_DIR.'/adodb-datadict.inc.php');
  3271. $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
  3272. if (!file_exists($path)) {
  3273. ADOConnection::outp("Database driver '$path' not available");
  3274. return $false;
  3275. }
  3276. include_once($path);
  3277. $class = "ADODB2_$drivername";
  3278. $dict =& new $class();
  3279. $dict->dataProvider = $conn->dataProvider;
  3280. $dict->connection = &$conn;
  3281. $dict->upperName = strtoupper($drivername);
  3282. $dict->quote = $conn->nameQuote;
  3283. if (!empty($conn->_connectionID))
  3284. $dict->serverInfo = $conn->ServerInfo();
  3285. return $dict;
  3286. }
  3287. /*
  3288. Perform a print_r, with pre tags for better formatting.
  3289. */
  3290. function adodb_pr($var,$as_string=false)
  3291. {
  3292. if ($as_string) ob_start();
  3293. if (isset($_SERVER['HTTP_USER_AGENT'])) {
  3294. echo " <pre>\n";print_r($var);echo "</pre>\n";
  3295. } else
  3296. print_r($var);
  3297. if ($as_string) {
  3298. $s = ob_get_contents();
  3299. ob_end_clean();
  3300. return $s;
  3301. }
  3302. }
  3303. /*
  3304. Perform a stack-crawl and pretty print it.
  3305. @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
  3306. @param levels Number of levels to display
  3307. */
  3308. function adodb_backtrace($printOrArr=true,$levels=9999)
  3309. {
  3310. global $ADODB_INCLUDED_LIB;
  3311. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  3312. return _adodb_backtrace($printOrArr,$levels);
  3313. }
  3314. } // defined
  3315. ?>