PageRenderTime 77ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/adodb/adodb.inc.php

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