PageRenderTime 48ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/adodb.493a/adodb.inc.php

https://github.com/guzzisto/retrospect-gds
PHP | 4221 lines | 2628 code | 491 blank | 1102 comment | 569 complexity | 9d00fe007af998feff23910768e94d61 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1

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

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