PageRenderTime 55ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/rdfapi-php/api/util/adodb/adodb.inc.php

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

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