PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/include/adodb/adodb.inc.php

https://github.com/radicaldesigns/amp
PHP | 4217 lines | 2625 code | 489 blank | 1103 comment | 569 complexity | 9270fa74e208d2467a683f2215e738dd MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, BSD-3-Clause, LGPL-2.0, CC-BY-SA-3.0, AGPL-1.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.92a 29 Aug 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 $cacheSecs = 0; /// cache off by default
  227. // memcache
  228. var $memCache = false; /// should we use memCache instead of caching in files
  229. var $memCacheHost; /// memCache host
  230. var $memCachePort = 11211; /// memCache port
  231. var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
  232. var $sysDate = false; /// name of function that returns the current date
  233. var $sysTimeStamp = false; /// name of function that returns the current timestamp
  234. var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
  235. var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
  236. var $numCacheHits = 0;
  237. var $numCacheMisses = 0;
  238. var $pageExecuteCountRows = true;
  239. var $uniqueSort = false; /// indicates that all fields in order by must be unique
  240. var $leftOuter = false; /// operator to use for left outer join in WHERE clause
  241. var $rightOuter = false; /// operator to use for right outer join in WHERE clause
  242. var $ansiOuter = false; /// whether ansi outer join syntax supported
  243. var $autoRollback = false; // autoRollback on PConnect().
  244. var $poorAffectedRows = false; // affectedRows not working or unreliable
  245. var $fnExecute = false;
  246. var $fnCacheExecute = false;
  247. var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
  248. var $rsPrefix = "ADORecordSet_";
  249. var $autoCommit = true; /// do not modify this yourself - actually private
  250. var $transOff = 0; /// temporarily disable transactions
  251. var $transCnt = 0; /// count of nested transactions
  252. var $fetchMode=false;
  253. //
  254. // PRIVATE VARS
  255. //
  256. var $_oldRaiseFn = false;
  257. var $_transOK = null;
  258. var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
  259. var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
  260. /// then returned by the errorMsg() function
  261. var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
  262. var $_queryID = false; /// This variable keeps the last created result link identifier
  263. var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
  264. var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
  265. var $_evalAll = false;
  266. var $_affected = false;
  267. var $_logsql = false;
  268. var $_transmode = ''; // transaction mode
  269. /**
  270. * Constructor
  271. */
  272. function ADOConnection()
  273. {
  274. die('Virtual Class -- cannot instantiate');
  275. }
  276. function Version()
  277. {
  278. global $ADODB_vers;
  279. return (float) substr($ADODB_vers,1);
  280. }
  281. /**
  282. Get server version info...
  283. @returns An array with 2 elements: $arr['string'] is the description string,
  284. and $arr[version] is the version (also a string).
  285. */
  286. function ServerInfo()
  287. {
  288. return array('description' => '', 'version' => '');
  289. }
  290. function IsConnected()
  291. {
  292. return !empty($this->_connectionID);
  293. }
  294. function _findvers($str)
  295. {
  296. if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
  297. else return '';
  298. }
  299. /**
  300. * All error messages go through this bottleneck function.
  301. * You can define your own handler by defining the function name in ADODB_OUTP.
  302. */
  303. function outp($msg,$newline=true)
  304. {
  305. global $ADODB_FLUSH,$ADODB_OUTP;
  306. if (defined('ADODB_OUTP')) {
  307. $fn = ADODB_OUTP;
  308. $fn($msg,$newline);
  309. return;
  310. } else if (isset($ADODB_OUTP)) {
  311. $fn = $ADODB_OUTP;
  312. $fn($msg,$newline);
  313. return;
  314. }
  315. if ($newline) $msg .= "<br>\n";
  316. if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
  317. else echo strip_tags($msg);
  318. if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
  319. }
  320. function Time()
  321. {
  322. $rs = $this->_Execute("select $this->sysTimeStamp");
  323. if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
  324. return false;
  325. }
  326. /**
  327. * Connect to database
  328. *
  329. * @param [argHostname] Host to connect to
  330. * @param [argUsername] Userid to login
  331. * @param [argPassword] Associated password
  332. * @param [argDatabaseName] database
  333. * @param [forceNew] force new connection
  334. *
  335. * @return true or false
  336. */
  337. function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
  338. {
  339. if ($argHostname != "") $this->host = $argHostname;
  340. if ($argUsername != "") $this->user = $argUsername;
  341. if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
  342. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  343. $this->_isPersistentConnection = false;
  344. if ($forceNew) {
  345. if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
  346. } else {
  347. if ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
  348. }
  349. if (isset($rez)) {
  350. $err = $this->ErrorMsg();
  351. if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  352. $ret = false;
  353. } else {
  354. $err = "Missing extension for ".$this->dataProvider;
  355. $ret = 0;
  356. }
  357. if ($fn = $this->raiseErrorFn)
  358. $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  359. $this->_connectionID = false;
  360. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  361. return $ret;
  362. }
  363. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  364. {
  365. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
  366. }
  367. /**
  368. * Always force a new connection to database - currently only works with oracle
  369. *
  370. * @param [argHostname] Host to connect to
  371. * @param [argUsername] Userid to login
  372. * @param [argPassword] Associated password
  373. * @param [argDatabaseName] database
  374. *
  375. * @return true or false
  376. */
  377. function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  378. {
  379. return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
  380. }
  381. /**
  382. * Establish persistent connect to database
  383. *
  384. * @param [argHostname] Host to connect to
  385. * @param [argUsername] Userid to login
  386. * @param [argPassword] Associated password
  387. * @param [argDatabaseName] database
  388. *
  389. * @return return true or false
  390. */
  391. function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  392. {
  393. if (defined('ADODB_NEVER_PERSIST'))
  394. return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
  395. if ($argHostname != "") $this->host = $argHostname;
  396. if ($argUsername != "") $this->user = $argUsername;
  397. if ($argPassword != "") $this->password = $argPassword;
  398. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  399. $this->_isPersistentConnection = true;
  400. if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
  401. if (isset($rez)) {
  402. $err = $this->ErrorMsg();
  403. if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  404. $ret = false;
  405. } else {
  406. $err = "Missing extension for ".$this->dataProvider;
  407. $ret = 0;
  408. }
  409. if ($fn = $this->raiseErrorFn) {
  410. $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  411. }
  412. $this->_connectionID = false;
  413. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  414. return $ret;
  415. }
  416. // Format date column in sql string given an input format that understands Y M D
  417. function SQLDate($fmt, $col=false)
  418. {
  419. if (!$col) $col = $this->sysDate;
  420. return $col; // child class implement
  421. }
  422. /**
  423. * Should prepare the sql statement and return the stmt resource.
  424. * For databases that do not support this, we return the $sql. To ensure
  425. * compatibility with databases that do not support prepare:
  426. *
  427. * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
  428. * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
  429. * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
  430. *
  431. * @param sql SQL to send to database
  432. *
  433. * @return return FALSE, or the prepared statement, or the original sql if
  434. * if the database does not support prepare.
  435. *
  436. */
  437. function Prepare($sql)
  438. {
  439. return $sql;
  440. }
  441. /**
  442. * Some databases, eg. mssql require a different function for preparing
  443. * stored procedures. So we cannot use Prepare().
  444. *
  445. * Should prepare the stored procedure and return the stmt resource.
  446. * For databases that do not support this, we return the $sql. To ensure
  447. * compatibility with databases that do not support prepare:
  448. *
  449. * @param sql SQL to send to database
  450. *
  451. * @return return FALSE, or the prepared statement, or the original sql if
  452. * if the database does not support prepare.
  453. *
  454. */
  455. function PrepareSP($sql,$param=true)
  456. {
  457. return $this->Prepare($sql,$param);
  458. }
  459. /**
  460. * PEAR DB Compat
  461. */
  462. function Quote($s)
  463. {
  464. return $this->qstr($s,false);
  465. }
  466. /**
  467. Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
  468. */
  469. function QMagic($s)
  470. {
  471. return $this->qstr($s,get_magic_quotes_gpc());
  472. }
  473. function q(&$s)
  474. {
  475. #if (!empty($this->qNull)) if ($s == 'null') return $s;
  476. $s = $this->qstr($s,false);
  477. }
  478. /**
  479. * PEAR DB Compat - do not use internally.
  480. */
  481. function ErrorNative()
  482. {
  483. return $this->ErrorNo();
  484. }
  485. /**
  486. * PEAR DB Compat - do not use internally.
  487. */
  488. function nextId($seq_name)
  489. {
  490. return $this->GenID($seq_name);
  491. }
  492. /**
  493. * Lock a row, will escalate and lock the table if row locking not supported
  494. * will normally free the lock at the end of the transaction
  495. *
  496. * @param $table name of table to lock
  497. * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
  498. */
  499. function RowLock($table,$where)
  500. {
  501. return false;
  502. }
  503. function CommitLock($table)
  504. {
  505. return $this->CommitTrans();
  506. }
  507. function RollbackLock($table)
  508. {
  509. return $this->RollbackTrans();
  510. }
  511. /**
  512. * PEAR DB Compat - do not use internally.
  513. *
  514. * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
  515. * for easy porting :-)
  516. *
  517. * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
  518. * @returns The previous fetch mode
  519. */
  520. function SetFetchMode($mode)
  521. {
  522. $old = $this->fetchMode;
  523. $this->fetchMode = $mode;
  524. if ($old === false) {
  525. global $ADODB_FETCH_MODE;
  526. return $ADODB_FETCH_MODE;
  527. }
  528. return $old;
  529. }
  530. /**
  531. * PEAR DB Compat - do not use internally.
  532. */
  533. function &Query($sql, $inputarr=false)
  534. {
  535. $rs = &$this->Execute($sql, $inputarr);
  536. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  537. return $rs;
  538. }
  539. /**
  540. * PEAR DB Compat - do not use internally
  541. */
  542. function &LimitQuery($sql, $offset, $count, $params=false)
  543. {
  544. $rs = &$this->SelectLimit($sql, $count, $offset, $params);
  545. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  546. return $rs;
  547. }
  548. /**
  549. * PEAR DB Compat - do not use internally
  550. */
  551. function Disconnect()
  552. {
  553. return $this->Close();
  554. }
  555. /*
  556. Returns placeholder for parameter, eg.
  557. $DB->Param('a')
  558. will return ':a' for Oracle, and '?' for most other databases...
  559. For databases that require positioned params, eg $1, $2, $3 for postgresql,
  560. pass in Param(false) before setting the first parameter.
  561. */
  562. function Param($name,$type='C')
  563. {
  564. return '?';
  565. }
  566. /*
  567. InParameter and OutParameter are self-documenting versions of Parameter().
  568. */
  569. function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  570. {
  571. return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
  572. }
  573. /*
  574. */
  575. function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  576. {
  577. return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
  578. }
  579. /*
  580. Usage in oracle
  581. $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
  582. $db->Parameter($stmt,$id,'myid');
  583. $db->Parameter($stmt,$group,'group',64);
  584. $db->Execute();
  585. @param $stmt Statement returned by Prepare() or PrepareSP().
  586. @param $var PHP variable to bind to
  587. @param $name Name of stored procedure variable name to bind to.
  588. @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
  589. @param [$maxLen] Holds an maximum length of the variable.
  590. @param [$type] The data type of $var. Legal values depend on driver.
  591. */
  592. function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
  593. {
  594. return false;
  595. }
  596. function IgnoreErrors($saveErrs=false)
  597. {
  598. if (!$saveErrs) {
  599. $saveErrs = array($this->raiseErrorFn,$this->_transOK);
  600. $this->raiseErrorFn = false;
  601. return $saveErrs;
  602. } else {
  603. $this->raiseErrorFn = $saveErrs[0];
  604. $this->_transOK = $saveErrs[1];
  605. }
  606. }
  607. /**
  608. Improved method of initiating a transaction. Used together with CompleteTrans().
  609. Advantages include:
  610. a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
  611. Only the outermost block is treated as a transaction.<br>
  612. b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
  613. c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
  614. are disabled, making it backward compatible.
  615. */
  616. function StartTrans($errfn = 'ADODB_TransMonitor')
  617. {
  618. if ($this->transOff > 0) {
  619. $this->transOff += 1;
  620. return;
  621. }
  622. $this->_oldRaiseFn = $this->raiseErrorFn;
  623. $this->raiseErrorFn = $errfn;
  624. $this->_transOK = true;
  625. if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
  626. $this->BeginTrans();
  627. $this->transOff = 1;
  628. }
  629. /**
  630. Used together with StartTrans() to end a transaction. Monitors connection
  631. for sql errors, and will commit or rollback as appropriate.
  632. @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
  633. and if set to false force rollback even if no SQL error detected.
  634. @returns true on commit, false on rollback.
  635. */
  636. function CompleteTrans($autoComplete = true)
  637. {
  638. if ($this->transOff > 1) {
  639. $this->transOff -= 1;
  640. return true;
  641. }
  642. $this->raiseErrorFn = $this->_oldRaiseFn;
  643. $this->transOff = 0;
  644. if ($this->_transOK && $autoComplete) {
  645. if (!$this->CommitTrans()) {
  646. $this->_transOK = false;
  647. if ($this->debug) ADOConnection::outp("Smart Commit failed");
  648. } else
  649. if ($this->debug) ADOConnection::outp("Smart Commit occurred");
  650. } else {
  651. $this->_transOK = false;
  652. $this->RollbackTrans();
  653. if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
  654. }
  655. return $this->_transOK;
  656. }
  657. /*
  658. At the end of a StartTrans/CompleteTrans block, perform a rollback.
  659. */
  660. function FailTrans()
  661. {
  662. if ($this->debug)
  663. if ($this->transOff == 0) {
  664. ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
  665. } else {
  666. ADOConnection::outp("FailTrans was called");
  667. adodb_backtrace();
  668. }
  669. $this->_transOK = false;
  670. }
  671. /**
  672. Check if transaction has failed, only for Smart Transactions.
  673. */
  674. function HasFailedTrans()
  675. {
  676. if ($this->transOff > 0) return $this->_transOK == false;
  677. return false;
  678. }
  679. /**
  680. * Execute SQL
  681. *
  682. * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
  683. * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
  684. * @return RecordSet or false
  685. */
  686. function &Execute($sql,$inputarr=false)
  687. {
  688. if ($this->fnExecute) {
  689. $fn = $this->fnExecute;
  690. $ret = $fn($this,$sql,$inputarr);
  691. if (isset($ret)) return $ret;
  692. }
  693. if ($inputarr) {
  694. if (!is_array($inputarr)) $inputarr = array($inputarr);
  695. $element0 = reset($inputarr);
  696. # is_object check because oci8 descriptors can be passed in
  697. $array_2d = is_array($element0) && !is_object(reset($element0));
  698. //remove extra memory copy of input -mikefedyk
  699. unset($element0);
  700. if (!is_array($sql) && !$this->_bindInputArray) {
  701. $sqlarr = explode('?',$sql);
  702. if (!$array_2d) $inputarr = array($inputarr);
  703. foreach($inputarr as $arr) {
  704. $sql = ''; $i = 0;
  705. //Use each() instead of foreach to reduce memory usage -mikefedyk
  706. while(list(, $v) = each($arr)) {
  707. $sql .= $sqlarr[$i];
  708. // from Ron Baldwin <ron.baldwin#sourceprose.com>
  709. // Only quote string types
  710. $typ = gettype($v);
  711. if ($typ == 'string')
  712. //New memory copy of input created here -mikefedyk
  713. $sql .= $this->qstr($v);
  714. else if ($typ == 'double')
  715. $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
  716. else if ($typ == 'boolean')
  717. $sql .= $v ? $this->true : $this->false;
  718. else if ($typ == 'object') {
  719. if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString());
  720. else $sql .= $this->qstr((string) $v);
  721. } else if ($v === null)
  722. $sql .= 'NULL';
  723. else
  724. $sql .= $v;
  725. $i += 1;
  726. }
  727. if (isset($sqlarr[$i])) {
  728. $sql .= $sqlarr[$i];
  729. if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
  730. } else if ($i != sizeof($sqlarr))
  731. ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql));
  732. $ret = $this->_Execute($sql);
  733. if (!$ret) return $ret;
  734. }
  735. } else {
  736. if ($array_2d) {
  737. if (is_string($sql))
  738. $stmt = $this->Prepare($sql);
  739. else
  740. $stmt = $sql;
  741. foreach($inputarr as $arr) {
  742. $ret = $this->_Execute($stmt,$arr);
  743. if (!$ret) return $ret;
  744. }
  745. } else {
  746. $ret = $this->_Execute($sql,$inputarr);
  747. }
  748. }
  749. } else {
  750. $ret = $this->_Execute($sql,false);
  751. }
  752. return $ret;
  753. }
  754. function &_Execute($sql,$inputarr=false)
  755. {
  756. if ($this->debug) {
  757. global $ADODB_INCLUDED_LIB;
  758. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  759. $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
  760. } else {
  761. $this->_queryID = @$this->_query($sql,$inputarr);
  762. }
  763. /************************
  764. // OK, query executed
  765. *************************/
  766. if ($this->_queryID === false) { // error handling if query fails
  767. if ($this->debug == 99) adodb_backtrace(true,5);
  768. $fn = $this->raiseErrorFn;
  769. if ($fn) {
  770. $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
  771. }
  772. $false = false;
  773. return $false;
  774. }
  775. if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
  776. $rs = new ADORecordSet_empty();
  777. return $rs;
  778. }
  779. // return real recordset from select statement
  780. $rsclass = $this->rsPrefix.$this->databaseType;
  781. $rs = new $rsclass($this->_queryID,$this->fetchMode);
  782. $rs->connection = &$this; // Pablo suggestion
  783. $rs->Init();
  784. if (is_array($sql)) $rs->sql = $sql[0];
  785. else $rs->sql = $sql;
  786. if ($rs->_numOfRows <= 0) {
  787. global $ADODB_COUNTRECS;
  788. if ($ADODB_COUNTRECS) {
  789. if (!$rs->EOF) {
  790. $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
  791. $rs->_queryID = $this->_queryID;
  792. } else
  793. $rs->_numOfRows = 0;
  794. }
  795. }
  796. return $rs;
  797. }
  798. function CreateSequence($seqname='adodbseq',$startID=1)
  799. {
  800. if (empty($this->_genSeqSQL)) return false;
  801. return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  802. }
  803. function DropSequence($seqname='adodbseq')
  804. {
  805. if (empty($this->_dropSeqSQL)) return false;
  806. return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
  807. }
  808. /**
  809. * Generates a sequence id and stores it in $this->genID;
  810. * GenID is only available if $this->hasGenID = true;
  811. *
  812. * @param seqname name of sequence to use
  813. * @param startID if sequence does not exist, start at this ID
  814. * @return 0 if not supported, otherwise a sequence id
  815. */
  816. function GenID($seqname='adodbseq',$startID=1)
  817. {
  818. if (!$this->hasGenID) {
  819. return 0; // formerly returns false pre 1.60
  820. }
  821. $getnext = sprintf($this->_genIDSQL,$seqname);
  822. $holdtransOK = $this->_transOK;
  823. $save_handler = $this->raiseErrorFn;
  824. $this->raiseErrorFn = '';
  825. @($rs = $this->Execute($getnext));
  826. $this->raiseErrorFn = $save_handler;
  827. if (!$rs) {
  828. $this->_transOK = $holdtransOK; //if the status was ok before reset
  829. $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  830. $rs = $this->Execute($getnext);
  831. }
  832. if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
  833. else $this->genID = 0; // false
  834. if ($rs) $rs->Close();
  835. return $this->genID;
  836. }
  837. /**
  838. * @param $table string name of the table, not needed by all databases (eg. mysql), default ''
  839. * @param $column string name of the column, not needed by all databases (eg. mysql), default ''
  840. * @return the last inserted ID. Not all databases support this.
  841. */
  842. function Insert_ID($table='',$column='')
  843. {
  844. if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
  845. if ($this->hasInsertID) return $this->_insertid($table,$column);
  846. if ($this->debug) {
  847. ADOConnection::outp( '<p>Insert_ID error</p>');
  848. adodb_backtrace();
  849. }
  850. return false;
  851. }
  852. /**
  853. * Portable Insert ID. Pablo Roca <pabloroca#mvps.org>
  854. *
  855. * @return the last inserted ID. All databases support this. But aware possible
  856. * problems in multiuser environments. Heavy test this before deploying.
  857. */
  858. function PO_Insert_ID($table="", $id="")
  859. {
  860. if ($this->hasInsertID){
  861. return $this->Insert_ID($table,$id);
  862. } else {
  863. return $this->GetOne("SELECT MAX($id) FROM $table");
  864. }
  865. }
  866. /**
  867. * @return # rows affected by UPDATE/DELETE
  868. */
  869. function Affected_Rows()
  870. {
  871. if ($this->hasAffectedRows) {
  872. if ($this->fnExecute === 'adodb_log_sql') {
  873. if ($this->_logsql && $this->_affected !== false) return $this->_affected;
  874. }
  875. $val = $this->_affectedrows();
  876. return ($val < 0) ? false : $val;
  877. }
  878. if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
  879. return false;
  880. }
  881. /**
  882. * @return the last error message
  883. */
  884. function ErrorMsg()
  885. {
  886. if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
  887. else return '';
  888. }
  889. /**
  890. * @return the last error number. Normally 0 means no error.
  891. */
  892. function ErrorNo()
  893. {
  894. return ($this->_errorMsg) ? -1 : 0;
  895. }
  896. function MetaError($err=false)
  897. {
  898. include_once(ADODB_DIR."/adodb-error.inc.php");
  899. if ($err === false) $err = $this->ErrorNo();
  900. return adodb_error($this->dataProvider,$this->databaseType,$err);
  901. }
  902. function MetaErrorMsg($errno)
  903. {
  904. include_once(ADODB_DIR."/adodb-error.inc.php");
  905. return adodb_errormsg($errno);
  906. }
  907. /**
  908. * @returns an array with the primary key columns in it.
  909. */
  910. function MetaPrimaryKeys($table, $owner=false)
  911. {
  912. // owner not used in base class - see oci8
  913. $p = array();
  914. $objs = $this->MetaColumns($table);
  915. if ($objs) {
  916. foreach($objs as $v) {
  917. if (!empty($v->primary_key))
  918. $p[] = $v->name;
  919. }
  920. }
  921. if (sizeof($p)) return $p;
  922. if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
  923. return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
  924. return false;
  925. }
  926. /**
  927. * @returns assoc array where keys are tables, and values are foreign keys
  928. */
  929. function MetaForeignKeys($table, $owner=false, $upper=false)
  930. {
  931. return false;
  932. }
  933. /**
  934. * Choose a database to connect to. Many databases do not support this.
  935. *
  936. * @param dbName is the name of the database to select
  937. * @return true or false
  938. */
  939. function SelectDB($dbName)
  940. {return false;}
  941. /**
  942. * Will select, getting rows from $offset (1-based), for $nrows.
  943. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  944. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  945. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  946. * eg.
  947. * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
  948. * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
  949. *
  950. * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
  951. * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
  952. *
  953. * @param sql
  954. * @param [offset] is the row to start calculations from (1-based)
  955. * @param [nrows] is the number of rows to get
  956. * @param [inputarr] array of bind variables
  957. * @param [secs2cache] is a private parameter only used by jlim
  958. * @return the recordset ($rs->databaseType == 'array')
  959. */
  960. function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
  961. {
  962. if ($this->hasTop && $nrows > 0) {
  963. // suggested by Reinhard Balling. Access requires top after distinct
  964. // Informix requires first before distinct - F Riosa
  965. $ismssql = (strpos($this->databaseType,'mssql') !== false);
  966. if ($ismssql) $isaccess = false;
  967. else $isaccess = (strpos($this->databaseType,'access') !== false);
  968. if ($offset <= 0) {
  969. // access includes ties in result
  970. if ($isaccess) {
  971. $sql = preg_replace(
  972. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  973. if ($secs2cache != 0) {
  974. $ret = $this->CacheExecute($secs2cache, $sql,$inputarr);
  975. } else {
  976. $ret = $this->Execute($sql,$inputarr);
  977. }
  978. return $ret; // PHP5 fix
  979. } else if ($ismssql){
  980. $sql = preg_replace(
  981. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  982. } else {
  983. $sql = preg_replace(
  984. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  985. }
  986. } else {
  987. $nn = $nrows + $offset;
  988. if ($isaccess || $ismssql) {
  989. $sql = preg_replace(
  990. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  991. } else {
  992. $sql = preg_replace(
  993. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  994. }
  995. }
  996. }
  997. // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
  998. // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
  999. global $ADODB_COUNTRECS;
  1000. $savec = $ADODB_COUNTRECS;
  1001. $ADODB_COUNTRECS = false;
  1002. if ($offset>0){
  1003. if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1004. else $rs = &$this->Execute($sql,$inputarr);
  1005. } else {
  1006. if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1007. else $rs = &$this->Execute($sql,$inputarr);
  1008. }
  1009. $ADODB_COUNTRECS = $savec;
  1010. if ($rs && !$rs->EOF) {
  1011. $rs = $this->_rs2rs($rs,$nrows,$offset);
  1012. }
  1013. //print_r($rs);
  1014. return $rs;
  1015. }
  1016. /**
  1017. * Create serializable recordset. Breaks rs link to connection.
  1018. *
  1019. * @param rs the recordset to serialize
  1020. */
  1021. function &SerializableRS(&$rs)
  1022. {
  1023. $rs2 = $this->_rs2rs($rs);
  1024. $ignore = false;
  1025. $rs2->connection = $ignore;
  1026. return $rs2;
  1027. }
  1028. /**
  1029. * Convert database recordset to an array recordset
  1030. * input recordset's cursor should be at beginning, and
  1031. * old $rs will be closed.
  1032. *
  1033. * @param rs the recordset to copy
  1034. * @param [nrows] number of rows to retrieve (optional)
  1035. * @param [offset] offset by number of rows (optional)
  1036. * @return the new recordset
  1037. */
  1038. function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
  1039. {
  1040. if (! $rs) {
  1041. $false = false;
  1042. return $false;
  1043. }
  1044. $dbtype = $rs->databaseType;
  1045. if (!$dbtype) {
  1046. $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
  1047. return $rs;
  1048. }
  1049. if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
  1050. $rs->MoveFirst();
  1051. $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
  1052. return $rs;
  1053. }
  1054. $flds = array();
  1055. for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
  1056. $flds[] = $rs->FetchField($i);
  1057. }
  1058. $arr = $rs->GetArrayLimit($nrows,$offset);
  1059. //print_r($arr);
  1060. if ($close) $rs->Close();
  1061. $arrayClass = $this->arrayClass;
  1062. $rs2 = new $arrayClass();
  1063. $rs2->connection = &$this;
  1064. $rs2->sql = $rs->sql;
  1065. $rs2->dataProvider = $this->dataProvider;
  1066. $rs2->InitArrayFields($arr,$flds);
  1067. $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
  1068. return $rs2;
  1069. }
  1070. /*
  1071. * Return all rows. Compat with PEAR DB
  1072. */
  1073. function &GetAll($sql, $inputarr=false)
  1074. {
  1075. $arr = $this->GetArray($sql,$inputarr);
  1076. return $arr;
  1077. }
  1078. function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
  1079. {
  1080. $rs = $this->Execute($sql, $inputarr);
  1081. if (!$rs) {
  1082. $false = false;
  1083. return $false;
  1084. }
  1085. $arr = $rs->GetAssoc($force_array,$first2cols);
  1086. return $arr;
  1087. }
  1088. function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
  1089. {
  1090. if (!is_numeric($secs2cache)) {
  1091. $first2cols = $force_array;
  1092. $force_array = $inputarr;
  1093. }
  1094. $rs = $this->CacheExecute($secs2cache, $sql, $inputarr);
  1095. if (!$rs) {
  1096. $false = false;
  1097. return $false;
  1098. }
  1099. $arr = $rs->GetAssoc($force_array,$first2cols);
  1100. return $arr;
  1101. }
  1102. /**
  1103. * Return first element of first row of sql statement. Recordset is disposed
  1104. * for you.
  1105. *
  1106. * @param sql SQL statement
  1107. * @param [inputarr] input bind array
  1108. */
  1109. function GetOne($sql,$inputarr=false)
  1110. {
  1111. global $ADODB_COUNTRECS;
  1112. $crecs = $ADODB_COUNTRECS;
  1113. $ADODB_COUNTRECS = false;
  1114. $ret = false;
  1115. $rs = &$this->Execute($sql,$inputarr);
  1116. if ($rs) {
  1117. if (!$rs->EOF) $ret = reset($rs->fields);
  1118. $rs->Close();
  1119. }
  1120. $ADODB_COUNTRECS = $crecs;
  1121. return $ret;
  1122. }
  1123. function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
  1124. {
  1125. $ret = false;
  1126. $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1127. if ($rs) {
  1128. if (!$rs->EOF) $ret = reset($rs->fields);
  1129. $rs->Close();
  1130. }
  1131. return $ret;
  1132. }
  1133. function GetCol($sql, $inputarr = false, $trim = false)
  1134. {
  1135. $rv = false;
  1136. $rs = &$this->Execute($sql, $inputarr);
  1137. if ($rs) {
  1138. $rv = array();
  1139. if ($trim) {
  1140. while (!$rs->EOF) {
  1141. $rv[] = trim(reset($rs->fields));
  1142. $rs->MoveNext();
  1143. }
  1144. } else {
  1145. while (!$rs->EOF) {
  1146. $rv[] = reset($rs->fields);
  1147. $rs->MoveNext();
  1148. }
  1149. }
  1150. $rs->Close();
  1151. }
  1152. return $rv;
  1153. }
  1154. function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
  1155. {
  1156. $rv = false;
  1157. $rs = &$this->CacheExecute($secs, $sql, $inputarr);
  1158. if ($rs) {
  1159. if ($trim) {
  1160. while (!$rs->EOF) {
  1161. $rv[] = trim(reset($rs->fields));
  1162. $rs->MoveNext();
  1163. }
  1164. } else {
  1165. while (!$rs->EOF) {
  1166. $rv[] = reset($rs->fields);
  1167. $rs->MoveNext();
  1168. }
  1169. }
  1170. $rs->Close();
  1171. }
  1172. return $rv;
  1173. }
  1174. function &Transpose(&$rs)
  1175. {
  1176. $rs2 = $this->_rs2rs($rs);
  1177. $false = false;
  1178. if (!$rs2) return $false;
  1179. $rs2->_transpose();
  1180. return $rs2;
  1181. }
  1182. /*
  1183. Calculate the offset of a date for a particular database and generate
  1184. appropriate SQL. Useful for calculating future/past dates and storing
  1185. in a database.
  1186. If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
  1187. */
  1188. function OffsetDate($dayFraction,$date=false)
  1189. {
  1190. if (!$date) $date = $this->sysDate;
  1191. return '('.$date.'+'.$dayFraction.')';
  1192. }
  1193. /**
  1194. *
  1195. * @param sql SQL statement
  1196. * @param [inputarr] input bind array
  1197. */
  1198. function &GetArray($sql,$inputarr=false)
  1199. {
  1200. global $ADODB_COUNTRECS;
  1201. $savec = $ADODB_COUNTRECS;
  1202. $ADODB_COUNTRECS = false;
  1203. $rs = $this->Execute($sql,$inputarr);
  1204. $ADODB_COUNTRECS = $savec;
  1205. if (!$rs)
  1206. if (defined('ADODB_PEAR')) {
  1207. $cls = ADODB_PEAR_Error();
  1208. return $cls;
  1209. } else {
  1210. $false = false;
  1211. return $false;
  1212. }
  1213. $arr = $rs->GetArray();
  1214. $rs->Close();
  1215. return $arr;
  1216. }
  1217. function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
  1218. {
  1219. return $this->CacheGetArray($secs2cache,$sql,$inputarr);
  1220. }
  1221. function &CacheGetArray($secs2cache,$sql=false,$inputarr=false)
  1222. {
  1223. global $ADODB_COUNTRECS;
  1224. $savec = $ADODB_COUNTRECS;
  1225. $ADODB_COUNTRECS = false;
  1226. $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
  1227. $ADODB_COUNTRECS = $savec;
  1228. if (!$rs)
  1229. if (defined('ADODB_PEAR')) {
  1230. $cls = ADODB_PEAR_Error();
  1231. return $cls;
  1232. } else {
  1233. $false = false;
  1234. return $false;
  1235. }
  1236. $arr = $rs->GetArray();
  1237. $rs->Close();
  1238. return $arr;
  1239. }
  1240. /**
  1241. * Return one row of sql statement. Recordset is disposed for you.
  1242. *
  1243. * @param sql SQL statement
  1244. * @param [inputarr] input bind array
  1245. */
  1246. function &GetRow($sql,$inputarr=false)
  1247. {
  1248. global $ADODB_COUNTRECS;
  1249. $crecs = $ADODB_COUNTRECS;
  1250. $ADODB_COUNTRECS = false;
  1251. $rs = $this->Execute($sql,$inputarr);
  1252. $ADODB_COUNTRECS = $crecs;
  1253. if ($rs) {
  1254. if (!$rs->EOF) $arr = $rs->fields;
  1255. else $arr = array();
  1256. $rs->Close();
  1257. return $arr;
  1258. }
  1259. $false = false;
  1260. return $false;
  1261. }
  1262. function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
  1263. {
  1264. $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
  1265. if ($rs) {
  1266. $arr = false;
  1267. if (!$rs->EOF) $arr = $rs->fields;
  1268. $rs->Close();
  1269. return $arr;
  1270. }
  1271. $false = false;
  1272. return $false;
  1273. }
  1274. /**
  1275. * Insert or replace a single record. Note: this is not the same as MySQL's replace.
  1276. * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
  1277. * Also note that no table locking is done currently, so it is possible that the
  1278. * record be inserted twice by two programs...
  1279. *
  1280. * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
  1281. *
  1282. * $table table name
  1283. * $fieldArray associative array of data (you must quote strings yourself).
  1284. * $keyCol the primary key field name or if compound key, array of field names
  1285. * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
  1286. * but does not work with dates nor SQL functions.
  1287. * has_autoinc the primary key is an auto-inc field, so skip in insert.
  1288. *
  1289. * Currently blob replace not supported
  1290. *
  1291. * returns 0 = fail, 1 = update, 2 = insert
  1292. */
  1293. function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
  1294. {
  1295. global $ADODB_INCLUDED_LIB;
  1296. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1297. return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
  1298. }
  1299. /**
  1300. * Will select, getting rows from $offset (1-based), for $nrows.
  1301. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  1302. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  1303. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  1304. * eg.
  1305. * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
  1306. * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
  1307. *
  1308. * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
  1309. *
  1310. * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
  1311. * @param sql
  1312. * @param [offset] is the row to start calculations from (1-based)
  1313. * @param [nrows] is the number of rows to get
  1314. * @param [inputarr] array of bind variables
  1315. * @return the recordset ($rs->databaseType == 'array')
  1316. */
  1317. function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
  1318. {
  1319. if (!is_numeric($secs2cache)) {
  1320. if ($sql === false) $sql = -1;
  1321. if ($offset == -1) $offset = false;
  1322. // sql, nrows, offset,inputarr
  1323. $rs = $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
  1324. } else {
  1325. if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
  1326. $rs = $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
  1327. }
  1328. return $rs;
  1329. }
  1330. /**
  1331. * Flush cached recordsets that match a particular $sql statement.
  1332. * If $sql == false, then we purge all files in the cache.
  1333. */
  1334. /**
  1335. * Flush cached recordsets that match a particular $sql statement.
  1336. * If $sql == false, then we purge all files in the cache.
  1337. */
  1338. function CacheFlush($sql=false,$inputarr=false)
  1339. {
  1340. global $ADODB_CACHE_DIR;
  1341. if ( !$this->cacheSecs ) return ;
  1342. if ($this->memCache) {
  1343. global $ADODB_INCLUDED_MEMCACHE;
  1344. $key = false;
  1345. if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
  1346. if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
  1347. FlushMemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
  1348. return;
  1349. }
  1350. if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
  1351. /*if (strncmp(PHP_OS,'WIN',3) === 0)
  1352. $dir = str_replace('/', '\\', $ADODB_CACHE_DIR);
  1353. else */
  1354. $dir = $ADODB_CACHE_DIR;
  1355. if ($this->debug) {
  1356. ADOConnection::outp( "CacheFlush: $dir<br><pre>\n", $this->_dirFlush($dir),"</pre>");
  1357. } else {
  1358. $this->_dirFlush($dir);
  1359. }
  1360. return;
  1361. }
  1362. global $ADODB_INCLUDED_CSV;
  1363. if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  1364. $f = $this->_gencachename($sql.serialize($inputarr),false);
  1365. adodb_write_file($f,''); // is adodb_write_file needed?
  1366. if (!@unlink($f)) {
  1367. if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
  1368. }
  1369. }
  1370. /**
  1371. * Private function to erase all of the files and subdirectories in a directory.
  1372. *
  1373. * Just specify the directory, and tell it if you want to delete the directory or just clear it out.
  1374. * Note: $kill_top_level is used internally in the function to flush subdirectories.
  1375. */
  1376. function _dirFlush($dir, $kill_top_level = false) {
  1377. if(!$dh = @opendir($dir)) return;
  1378. while (($obj = readdir($dh))) {
  1379. if($obj=='.' || $obj=='..')
  1380. continue;
  1381. if (!@unlink($dir.'/'.$obj))
  1382. $this->_dirFlush($dir.'/'.$obj, true);
  1383. }
  1384. if ($kill_top_level === true)
  1385. @rmdir($dir);
  1386. return true;
  1387. }
  1388. function xCacheFlush($sql=false,$inputarr=false)
  1389. {
  1390. global $ADODB_CACHE_DIR;
  1391. if ( !$this->cacheSecs ) return ;
  1392. if ($this->memCache) {
  1393. global $ADODB_INCLUDED_MEMCACHE;
  1394. $key = false;
  1395. if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
  1396. if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
  1397. FlushMemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
  1398. return;
  1399. }
  1400. if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
  1401. if (strncmp(PHP_OS,'WIN',3) === 0) {
  1402. $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
  1403. } else {
  1404. //$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f';
  1405. $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/';
  1406. // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
  1407. }
  1408. if ($this->debug) {
  1409. ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
  1410. } else {
  1411. exec($cmd);
  1412. }
  1413. return;
  1414. }
  1415. global $ADODB_INCLUDED_CSV;
  1416. if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  1417. $f = $this->_gencachename($sql.serialize($inputarr),false);
  1418. adodb_write_file($f,''); // is adodb_write_file needed?
  1419. if (!@unlink($f)) {
  1420. if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
  1421. }
  1422. }
  1423. /**
  1424. * Private function to generate filename for caching.
  1425. * Filename is generated based on:
  1426. *…

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