PageRenderTime 31ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 1ms

/upload/libraries/adodb/adodb.inc.php

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

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