PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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. * …

Large files files are truncated, but you can click here to view the full file