PageRenderTime 39ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/include/adodb/adodb.inc.php

https://github.com/radicaldesigns/amp
PHP | 4217 lines | 2625 code | 489 blank | 1103 comment | 569 complexity | 9270fa74e208d2467a683f2215e738dd MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, BSD-3-Clause, LGPL-2.0, CC-BY-SA-3.0, AGPL-1.0
  1. <?php
  2. /*
  3. * Set tabs to 4 for best viewing.
  4. *
  5. * Latest version is available at http://adodb.sourceforge.net
  6. *
  7. * This is the main include file for ADOdb.
  8. * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
  9. *
  10. * The ADOdb files are formatted so that doxygen can be used to generate documentation.
  11. * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
  12. */
  13. /**
  14. \mainpage
  15. @version V4.92a 29 Aug 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
  16. Released under both BSD license and Lesser GPL library license. You can choose which license
  17. you prefer.
  18. PHP's database access functions are not standardised. This creates a need for a database
  19. class library to hide the differences between the different database API's (encapsulate
  20. the differences) so we can easily switch databases.
  21. We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
  22. Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
  23. ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
  24. other databases via ODBC.
  25. Latest Download at http://adodb.sourceforge.net/
  26. */
  27. if (!defined('_ADODB_LAYER')) {
  28. define('_ADODB_LAYER',1);
  29. //==============================================================================================
  30. // CONSTANT DEFINITIONS
  31. //==============================================================================================
  32. /**
  33. * Set ADODB_DIR to the directory where this file resides...
  34. * This constant was formerly called $ADODB_RootPath
  35. */
  36. if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
  37. //==============================================================================================
  38. // GLOBAL VARIABLES
  39. //==============================================================================================
  40. GLOBAL
  41. $ADODB_vers, // database version
  42. $ADODB_COUNTRECS, // count number of records returned - slows down query
  43. $ADODB_CACHE_DIR, // directory to cache recordsets
  44. $ADODB_EXTENSION, // ADODB extension installed
  45. $ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
  46. $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
  47. //==============================================================================================
  48. // GLOBAL SETUP
  49. //==============================================================================================
  50. $ADODB_EXTENSION = defined('ADODB_EXTENSION');
  51. //********************************************************//
  52. /*
  53. Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
  54. Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
  55. 0 = ignore empty fields. All empty fields in array are ignored.
  56. 1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
  57. 2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
  58. 3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values.
  59. */
  60. define('ADODB_FORCE_IGNORE',0);
  61. define('ADODB_FORCE_NULL',1);
  62. define('ADODB_FORCE_EMPTY',2);
  63. define('ADODB_FORCE_VALUE',3);
  64. //********************************************************//
  65. if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
  66. define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
  67. // allow [ ] @ ` " and . in table names
  68. define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
  69. // prefetching used by oracle
  70. if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
  71. /*
  72. Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
  73. This currently works only with mssql, odbc, oci8po and ibase derived drivers.
  74. 0 = assoc lowercase field names. $rs->fields['orderid']
  75. 1 = assoc uppercase field names. $rs->fields['ORDERID']
  76. 2 = use native-case field names. $rs->fields['OrderID']
  77. */
  78. define('ADODB_FETCH_DEFAULT',0);
  79. define('ADODB_FETCH_NUM',1);
  80. define('ADODB_FETCH_ASSOC',2);
  81. define('ADODB_FETCH_BOTH',3);
  82. if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
  83. // PHP's version scheme makes converting to numbers difficult - workaround
  84. $_adodb_ver = (float) PHP_VERSION;
  85. if ($_adodb_ver >= 5.0) {
  86. define('ADODB_PHPVER',0x5000);
  87. } else if ($_adodb_ver > 4.299999) { # 4.3
  88. define('ADODB_PHPVER',0x4300);
  89. } else if ($_adodb_ver > 4.199999) { # 4.2
  90. define('ADODB_PHPVER',0x4200);
  91. } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
  92. define('ADODB_PHPVER',0x4050);
  93. } else {
  94. define('ADODB_PHPVER',0x4000);
  95. }
  96. }
  97. //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  98. /**
  99. Accepts $src and $dest arrays, replacing string $data
  100. */
  101. function ADODB_str_replace($src, $dest, $data)
  102. {
  103. if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
  104. $s = reset($src);
  105. $d = reset($dest);
  106. while ($s !== false) {
  107. $data = str_replace($s,$d,$data);
  108. $s = next($src);
  109. $d = next($dest);
  110. }
  111. return $data;
  112. }
  113. function ADODB_Setup()
  114. {
  115. GLOBAL
  116. $ADODB_vers, // database version
  117. $ADODB_COUNTRECS, // count number of records returned - slows down query
  118. $ADODB_CACHE_DIR, // directory to cache recordsets
  119. $ADODB_FETCH_MODE,
  120. $ADODB_FORCE_TYPE;
  121. $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
  122. $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
  123. if (!isset($ADODB_CACHE_DIR)) {
  124. $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
  125. } else {
  126. // do not accept url based paths, eg. http:/ or ftp:/
  127. if (strpos($ADODB_CACHE_DIR,'://') !== false)
  128. die("Illegal path http:// or ftp://");
  129. }
  130. // Initialize random number generator for randomizing cache flushes
  131. srand(((double)microtime())*1000000);
  132. /**
  133. * ADODB version as a string.
  134. */
  135. $ADODB_vers = 'V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
  136. /**
  137. * Determines whether recordset->RecordCount() is used.
  138. * Set to false for highest performance -- RecordCount() will always return -1 then
  139. * for databases that provide "virtual" recordcounts...
  140. */
  141. if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
  142. }
  143. //==============================================================================================
  144. // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
  145. //==============================================================================================
  146. ADODB_Setup();
  147. //==============================================================================================
  148. // CLASS ADOFieldObject
  149. //==============================================================================================
  150. /**
  151. * Helper class for FetchFields -- holds info on a column
  152. */
  153. class ADOFieldObject {
  154. var $name = '';
  155. var $max_length=0;
  156. var $type="";
  157. /*
  158. // additional fields by dannym... (danny_milo@yahoo.com)
  159. var $not_null = false;
  160. // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
  161. // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
  162. var $has_default = false; // this one I have done only in mysql and postgres for now ...
  163. // others to come (dannym)
  164. var $default_value; // default, if any, and supported. Check has_default first.
  165. */
  166. }
  167. function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
  168. {
  169. //print "Errorno ($fn errno=$errno m=$errmsg) ";
  170. $thisConnection->_transOK = false;
  171. if ($thisConnection->_oldRaiseFn) {
  172. $fn = $thisConnection->_oldRaiseFn;
  173. $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
  174. }
  175. }
  176. //==============================================================================================
  177. // CLASS ADOConnection
  178. //==============================================================================================
  179. /**
  180. * Connection object. For connecting to databases, and executing queries.
  181. */
  182. class ADOConnection {
  183. //
  184. // PUBLIC VARS
  185. //
  186. var $dataProvider = 'native';
  187. var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
  188. var $database = ''; /// Name of database to be used.
  189. var $host = ''; /// The hostname of the database server
  190. var $user = ''; /// The username which is used to connect to the database server.
  191. var $password = ''; /// Password for the username. For security, we no longer store it.
  192. var $debug = false; /// if set to true will output sql statements
  193. var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
  194. var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
  195. var $substr = 'substr'; /// substring operator
  196. var $length = 'length'; /// string length ofperator
  197. var $random = 'rand()'; /// random function
  198. var $upperCase = 'upper'; /// uppercase function
  199. var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
  200. var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
  201. var $true = '1'; /// string that represents TRUE for a database
  202. var $false = '0'; /// string that represents FALSE for a database
  203. var $replaceQuote = "\\'"; /// string to use to replace quotes
  204. var $nameQuote = '"'; /// string to use to quote identifiers and names
  205. var $charSet=false; /// character set to use - only for interbase, postgres and oci8
  206. var $metaDatabasesSQL = '';
  207. var $metaTablesSQL = '';
  208. var $uniqueOrderBy = false; /// All order by columns have to be unique
  209. var $emptyDate = '&nbsp;';
  210. var $emptyTimeStamp = '&nbsp;';
  211. var $lastInsID = false;
  212. //--
  213. var $hasInsertID = false; /// supports autoincrement ID?
  214. var $hasAffectedRows = false; /// supports affected rows for update/delete?
  215. var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
  216. var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
  217. var $readOnly = false; /// this is a readonly database - used by phpLens
  218. var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
  219. var $hasGenID = false; /// can generate sequences using GenID();
  220. var $hasTransactions = true; /// has transactions
  221. //--
  222. var $genID = 0; /// sequence id used by GenID();
  223. var $raiseErrorFn = false; /// error function to call
  224. var $isoDates = false; /// accepts dates in ISO format
  225. //var $cacheSecs = 3600; /// cache for 1 hour
  226. var $cacheSecs = 0; /// cache off by default
  227. // memcache
  228. var $memCache = false; /// should we use memCache instead of caching in files
  229. var $memCacheHost; /// memCache host
  230. var $memCachePort = 11211; /// memCache port
  231. var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
  232. var $sysDate = false; /// name of function that returns the current date
  233. var $sysTimeStamp = false; /// name of function that returns the current timestamp
  234. var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
  235. var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
  236. var $numCacheHits = 0;
  237. var $numCacheMisses = 0;
  238. var $pageExecuteCountRows = true;
  239. var $uniqueSort = false; /// indicates that all fields in order by must be unique
  240. var $leftOuter = false; /// operator to use for left outer join in WHERE clause
  241. var $rightOuter = false; /// operator to use for right outer join in WHERE clause
  242. var $ansiOuter = false; /// whether ansi outer join syntax supported
  243. var $autoRollback = false; // autoRollback on PConnect().
  244. var $poorAffectedRows = false; // affectedRows not working or unreliable
  245. var $fnExecute = false;
  246. var $fnCacheExecute = false;
  247. var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
  248. var $rsPrefix = "ADORecordSet_";
  249. var $autoCommit = true; /// do not modify this yourself - actually private
  250. var $transOff = 0; /// temporarily disable transactions
  251. var $transCnt = 0; /// count of nested transactions
  252. var $fetchMode=false;
  253. //
  254. // PRIVATE VARS
  255. //
  256. var $_oldRaiseFn = false;
  257. var $_transOK = null;
  258. var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
  259. var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
  260. /// then returned by the errorMsg() function
  261. var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
  262. var $_queryID = false; /// This variable keeps the last created result link identifier
  263. var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
  264. var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
  265. var $_evalAll = false;
  266. var $_affected = false;
  267. var $_logsql = false;
  268. var $_transmode = ''; // transaction mode
  269. /**
  270. * Constructor
  271. */
  272. function ADOConnection()
  273. {
  274. die('Virtual Class -- cannot instantiate');
  275. }
  276. function Version()
  277. {
  278. global $ADODB_vers;
  279. return (float) substr($ADODB_vers,1);
  280. }
  281. /**
  282. Get server version info...
  283. @returns An array with 2 elements: $arr['string'] is the description string,
  284. and $arr[version] is the version (also a string).
  285. */
  286. function ServerInfo()
  287. {
  288. return array('description' => '', 'version' => '');
  289. }
  290. function IsConnected()
  291. {
  292. return !empty($this->_connectionID);
  293. }
  294. function _findvers($str)
  295. {
  296. if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
  297. else return '';
  298. }
  299. /**
  300. * All error messages go through this bottleneck function.
  301. * You can define your own handler by defining the function name in ADODB_OUTP.
  302. */
  303. function outp($msg,$newline=true)
  304. {
  305. global $ADODB_FLUSH,$ADODB_OUTP;
  306. if (defined('ADODB_OUTP')) {
  307. $fn = ADODB_OUTP;
  308. $fn($msg,$newline);
  309. return;
  310. } else if (isset($ADODB_OUTP)) {
  311. $fn = $ADODB_OUTP;
  312. $fn($msg,$newline);
  313. return;
  314. }
  315. if ($newline) $msg .= "<br>\n";
  316. if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
  317. else echo strip_tags($msg);
  318. if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
  319. }
  320. function Time()
  321. {
  322. $rs = $this->_Execute("select $this->sysTimeStamp");
  323. if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
  324. return false;
  325. }
  326. /**
  327. * Connect to database
  328. *
  329. * @param [argHostname] Host to connect to
  330. * @param [argUsername] Userid to login
  331. * @param [argPassword] Associated password
  332. * @param [argDatabaseName] database
  333. * @param [forceNew] force new connection
  334. *
  335. * @return true or false
  336. */
  337. function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
  338. {
  339. if ($argHostname != "") $this->host = $argHostname;
  340. if ($argUsername != "") $this->user = $argUsername;
  341. if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
  342. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  343. $this->_isPersistentConnection = false;
  344. if ($forceNew) {
  345. if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
  346. } else {
  347. if ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
  348. }
  349. if (isset($rez)) {
  350. $err = $this->ErrorMsg();
  351. if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  352. $ret = false;
  353. } else {
  354. $err = "Missing extension for ".$this->dataProvider;
  355. $ret = 0;
  356. }
  357. if ($fn = $this->raiseErrorFn)
  358. $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  359. $this->_connectionID = false;
  360. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  361. return $ret;
  362. }
  363. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  364. {
  365. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
  366. }
  367. /**
  368. * Always force a new connection to database - currently only works with oracle
  369. *
  370. * @param [argHostname] Host to connect to
  371. * @param [argUsername] Userid to login
  372. * @param [argPassword] Associated password
  373. * @param [argDatabaseName] database
  374. *
  375. * @return true or false
  376. */
  377. function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  378. {
  379. return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
  380. }
  381. /**
  382. * Establish persistent connect to database
  383. *
  384. * @param [argHostname] Host to connect to
  385. * @param [argUsername] Userid to login
  386. * @param [argPassword] Associated password
  387. * @param [argDatabaseName] database
  388. *
  389. * @return return true or false
  390. */
  391. function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  392. {
  393. if (defined('ADODB_NEVER_PERSIST'))
  394. return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
  395. if ($argHostname != "") $this->host = $argHostname;
  396. if ($argUsername != "") $this->user = $argUsername;
  397. if ($argPassword != "") $this->password = $argPassword;
  398. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  399. $this->_isPersistentConnection = true;
  400. if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
  401. if (isset($rez)) {
  402. $err = $this->ErrorMsg();
  403. if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  404. $ret = false;
  405. } else {
  406. $err = "Missing extension for ".$this->dataProvider;
  407. $ret = 0;
  408. }
  409. if ($fn = $this->raiseErrorFn) {
  410. $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  411. }
  412. $this->_connectionID = false;
  413. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  414. return $ret;
  415. }
  416. // Format date column in sql string given an input format that understands Y M D
  417. function SQLDate($fmt, $col=false)
  418. {
  419. if (!$col) $col = $this->sysDate;
  420. return $col; // child class implement
  421. }
  422. /**
  423. * Should prepare the sql statement and return the stmt resource.
  424. * For databases that do not support this, we return the $sql. To ensure
  425. * compatibility with databases that do not support prepare:
  426. *
  427. * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
  428. * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
  429. * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
  430. *
  431. * @param sql SQL to send to database
  432. *
  433. * @return return FALSE, or the prepared statement, or the original sql if
  434. * if the database does not support prepare.
  435. *
  436. */
  437. function Prepare($sql)
  438. {
  439. return $sql;
  440. }
  441. /**
  442. * Some databases, eg. mssql require a different function for preparing
  443. * stored procedures. So we cannot use Prepare().
  444. *
  445. * Should prepare the stored procedure and return the stmt resource.
  446. * For databases that do not support this, we return the $sql. To ensure
  447. * compatibility with databases that do not support prepare:
  448. *
  449. * @param sql SQL to send to database
  450. *
  451. * @return return FALSE, or the prepared statement, or the original sql if
  452. * if the database does not support prepare.
  453. *
  454. */
  455. function PrepareSP($sql,$param=true)
  456. {
  457. return $this->Prepare($sql,$param);
  458. }
  459. /**
  460. * PEAR DB Compat
  461. */
  462. function Quote($s)
  463. {
  464. return $this->qstr($s,false);
  465. }
  466. /**
  467. Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
  468. */
  469. function QMagic($s)
  470. {
  471. return $this->qstr($s,get_magic_quotes_gpc());
  472. }
  473. function q(&$s)
  474. {
  475. #if (!empty($this->qNull)) if ($s == 'null') return $s;
  476. $s = $this->qstr($s,false);
  477. }
  478. /**
  479. * PEAR DB Compat - do not use internally.
  480. */
  481. function ErrorNative()
  482. {
  483. return $this->ErrorNo();
  484. }
  485. /**
  486. * PEAR DB Compat - do not use internally.
  487. */
  488. function nextId($seq_name)
  489. {
  490. return $this->GenID($seq_name);
  491. }
  492. /**
  493. * Lock a row, will escalate and lock the table if row locking not supported
  494. * will normally free the lock at the end of the transaction
  495. *
  496. * @param $table name of table to lock
  497. * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
  498. */
  499. function RowLock($table,$where)
  500. {
  501. return false;
  502. }
  503. function CommitLock($table)
  504. {
  505. return $this->CommitTrans();
  506. }
  507. function RollbackLock($table)
  508. {
  509. return $this->RollbackTrans();
  510. }
  511. /**
  512. * PEAR DB Compat - do not use internally.
  513. *
  514. * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
  515. * for easy porting :-)
  516. *
  517. * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
  518. * @returns The previous fetch mode
  519. */
  520. function SetFetchMode($mode)
  521. {
  522. $old = $this->fetchMode;
  523. $this->fetchMode = $mode;
  524. if ($old === false) {
  525. global $ADODB_FETCH_MODE;
  526. return $ADODB_FETCH_MODE;
  527. }
  528. return $old;
  529. }
  530. /**
  531. * PEAR DB Compat - do not use internally.
  532. */
  533. function &Query($sql, $inputarr=false)
  534. {
  535. $rs = &$this->Execute($sql, $inputarr);
  536. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  537. return $rs;
  538. }
  539. /**
  540. * PEAR DB Compat - do not use internally
  541. */
  542. function &LimitQuery($sql, $offset, $count, $params=false)
  543. {
  544. $rs = &$this->SelectLimit($sql, $count, $offset, $params);
  545. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  546. return $rs;
  547. }
  548. /**
  549. * PEAR DB Compat - do not use internally
  550. */
  551. function Disconnect()
  552. {
  553. return $this->Close();
  554. }
  555. /*
  556. Returns placeholder for parameter, eg.
  557. $DB->Param('a')
  558. will return ':a' for Oracle, and '?' for most other databases...
  559. For databases that require positioned params, eg $1, $2, $3 for postgresql,
  560. pass in Param(false) before setting the first parameter.
  561. */
  562. function Param($name,$type='C')
  563. {
  564. return '?';
  565. }
  566. /*
  567. InParameter and OutParameter are self-documenting versions of Parameter().
  568. */
  569. function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  570. {
  571. return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
  572. }
  573. /*
  574. */
  575. function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  576. {
  577. return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
  578. }
  579. /*
  580. Usage in oracle
  581. $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
  582. $db->Parameter($stmt,$id,'myid');
  583. $db->Parameter($stmt,$group,'group',64);
  584. $db->Execute();
  585. @param $stmt Statement returned by Prepare() or PrepareSP().
  586. @param $var PHP variable to bind to
  587. @param $name Name of stored procedure variable name to bind to.
  588. @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
  589. @param [$maxLen] Holds an maximum length of the variable.
  590. @param [$type] The data type of $var. Legal values depend on driver.
  591. */
  592. function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
  593. {
  594. return false;
  595. }
  596. function IgnoreErrors($saveErrs=false)
  597. {
  598. if (!$saveErrs) {
  599. $saveErrs = array($this->raiseErrorFn,$this->_transOK);
  600. $this->raiseErrorFn = false;
  601. return $saveErrs;
  602. } else {
  603. $this->raiseErrorFn = $saveErrs[0];
  604. $this->_transOK = $saveErrs[1];
  605. }
  606. }
  607. /**
  608. Improved method of initiating a transaction. Used together with CompleteTrans().
  609. Advantages include:
  610. a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
  611. Only the outermost block is treated as a transaction.<br>
  612. b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
  613. c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
  614. are disabled, making it backward compatible.
  615. */
  616. function StartTrans($errfn = 'ADODB_TransMonitor')
  617. {
  618. if ($this->transOff > 0) {
  619. $this->transOff += 1;
  620. return;
  621. }
  622. $this->_oldRaiseFn = $this->raiseErrorFn;
  623. $this->raiseErrorFn = $errfn;
  624. $this->_transOK = true;
  625. if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
  626. $this->BeginTrans();
  627. $this->transOff = 1;
  628. }
  629. /**
  630. Used together with StartTrans() to end a transaction. Monitors connection
  631. for sql errors, and will commit or rollback as appropriate.
  632. @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
  633. and if set to false force rollback even if no SQL error detected.
  634. @returns true on commit, false on rollback.
  635. */
  636. function CompleteTrans($autoComplete = true)
  637. {
  638. if ($this->transOff > 1) {
  639. $this->transOff -= 1;
  640. return true;
  641. }
  642. $this->raiseErrorFn = $this->_oldRaiseFn;
  643. $this->transOff = 0;
  644. if ($this->_transOK && $autoComplete) {
  645. if (!$this->CommitTrans()) {
  646. $this->_transOK = false;
  647. if ($this->debug) ADOConnection::outp("Smart Commit failed");
  648. } else
  649. if ($this->debug) ADOConnection::outp("Smart Commit occurred");
  650. } else {
  651. $this->_transOK = false;
  652. $this->RollbackTrans();
  653. if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
  654. }
  655. return $this->_transOK;
  656. }
  657. /*
  658. At the end of a StartTrans/CompleteTrans block, perform a rollback.
  659. */
  660. function FailTrans()
  661. {
  662. if ($this->debug)
  663. if ($this->transOff == 0) {
  664. ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
  665. } else {
  666. ADOConnection::outp("FailTrans was called");
  667. adodb_backtrace();
  668. }
  669. $this->_transOK = false;
  670. }
  671. /**
  672. Check if transaction has failed, only for Smart Transactions.
  673. */
  674. function HasFailedTrans()
  675. {
  676. if ($this->transOff > 0) return $this->_transOK == false;
  677. return false;
  678. }
  679. /**
  680. * Execute SQL
  681. *
  682. * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
  683. * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
  684. * @return RecordSet or false
  685. */
  686. function &Execute($sql,$inputarr=false)
  687. {
  688. if ($this->fnExecute) {
  689. $fn = $this->fnExecute;
  690. $ret = $fn($this,$sql,$inputarr);
  691. if (isset($ret)) return $ret;
  692. }
  693. if ($inputarr) {
  694. if (!is_array($inputarr)) $inputarr = array($inputarr);
  695. $element0 = reset($inputarr);
  696. # is_object check because oci8 descriptors can be passed in
  697. $array_2d = is_array($element0) && !is_object(reset($element0));
  698. //remove extra memory copy of input -mikefedyk
  699. unset($element0);
  700. if (!is_array($sql) && !$this->_bindInputArray) {
  701. $sqlarr = explode('?',$sql);
  702. if (!$array_2d) $inputarr = array($inputarr);
  703. foreach($inputarr as $arr) {
  704. $sql = ''; $i = 0;
  705. //Use each() instead of foreach to reduce memory usage -mikefedyk
  706. while(list(, $v) = each($arr)) {
  707. $sql .= $sqlarr[$i];
  708. // from Ron Baldwin <ron.baldwin#sourceprose.com>
  709. // Only quote string types
  710. $typ = gettype($v);
  711. if ($typ == 'string')
  712. //New memory copy of input created here -mikefedyk
  713. $sql .= $this->qstr($v);
  714. else if ($typ == 'double')
  715. $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
  716. else if ($typ == 'boolean')
  717. $sql .= $v ? $this->true : $this->false;
  718. else if ($typ == 'object') {
  719. if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString());
  720. else $sql .= $this->qstr((string) $v);
  721. } else if ($v === null)
  722. $sql .= 'NULL';
  723. else
  724. $sql .= $v;
  725. $i += 1;
  726. }
  727. if (isset($sqlarr[$i])) {
  728. $sql .= $sqlarr[$i];
  729. if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
  730. } else if ($i != sizeof($sqlarr))
  731. ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql));
  732. $ret = $this->_Execute($sql);
  733. if (!$ret) return $ret;
  734. }
  735. } else {
  736. if ($array_2d) {
  737. if (is_string($sql))
  738. $stmt = $this->Prepare($sql);
  739. else
  740. $stmt = $sql;
  741. foreach($inputarr as $arr) {
  742. $ret = $this->_Execute($stmt,$arr);
  743. if (!$ret) return $ret;
  744. }
  745. } else {
  746. $ret = $this->_Execute($sql,$inputarr);
  747. }
  748. }
  749. } else {
  750. $ret = $this->_Execute($sql,false);
  751. }
  752. return $ret;
  753. }
  754. function &_Execute($sql,$inputarr=false)
  755. {
  756. if ($this->debug) {
  757. global $ADODB_INCLUDED_LIB;
  758. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  759. $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
  760. } else {
  761. $this->_queryID = @$this->_query($sql,$inputarr);
  762. }
  763. /************************
  764. // OK, query executed
  765. *************************/
  766. if ($this->_queryID === false) { // error handling if query fails
  767. if ($this->debug == 99) adodb_backtrace(true,5);
  768. $fn = $this->raiseErrorFn;
  769. if ($fn) {
  770. $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
  771. }
  772. $false = false;
  773. return $false;
  774. }
  775. if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
  776. $rs = new ADORecordSet_empty();
  777. return $rs;
  778. }
  779. // return real recordset from select statement
  780. $rsclass = $this->rsPrefix.$this->databaseType;
  781. $rs = new $rsclass($this->_queryID,$this->fetchMode);
  782. $rs->connection = &$this; // Pablo suggestion
  783. $rs->Init();
  784. if (is_array($sql)) $rs->sql = $sql[0];
  785. else $rs->sql = $sql;
  786. if ($rs->_numOfRows <= 0) {
  787. global $ADODB_COUNTRECS;
  788. if ($ADODB_COUNTRECS) {
  789. if (!$rs->EOF) {
  790. $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
  791. $rs->_queryID = $this->_queryID;
  792. } else
  793. $rs->_numOfRows = 0;
  794. }
  795. }
  796. return $rs;
  797. }
  798. function CreateSequence($seqname='adodbseq',$startID=1)
  799. {
  800. if (empty($this->_genSeqSQL)) return false;
  801. return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  802. }
  803. function DropSequence($seqname='adodbseq')
  804. {
  805. if (empty($this->_dropSeqSQL)) return false;
  806. return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
  807. }
  808. /**
  809. * Generates a sequence id and stores it in $this->genID;
  810. * GenID is only available if $this->hasGenID = true;
  811. *
  812. * @param seqname name of sequence to use
  813. * @param startID if sequence does not exist, start at this ID
  814. * @return 0 if not supported, otherwise a sequence id
  815. */
  816. function GenID($seqname='adodbseq',$startID=1)
  817. {
  818. if (!$this->hasGenID) {
  819. return 0; // formerly returns false pre 1.60
  820. }
  821. $getnext = sprintf($this->_genIDSQL,$seqname);
  822. $holdtransOK = $this->_transOK;
  823. $save_handler = $this->raiseErrorFn;
  824. $this->raiseErrorFn = '';
  825. @($rs = $this->Execute($getnext));
  826. $this->raiseErrorFn = $save_handler;
  827. if (!$rs) {
  828. $this->_transOK = $holdtransOK; //if the status was ok before reset
  829. $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  830. $rs = $this->Execute($getnext);
  831. }
  832. if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
  833. else $this->genID = 0; // false
  834. if ($rs) $rs->Close();
  835. return $this->genID;
  836. }
  837. /**
  838. * @param $table string name of the table, not needed by all databases (eg. mysql), default ''
  839. * @param $column string name of the column, not needed by all databases (eg. mysql), default ''
  840. * @return the last inserted ID. Not all databases support this.
  841. */
  842. function Insert_ID($table='',$column='')
  843. {
  844. if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
  845. if ($this->hasInsertID) return $this->_insertid($table,$column);
  846. if ($this->debug) {
  847. ADOConnection::outp( '<p>Insert_ID error</p>');
  848. adodb_backtrace();
  849. }
  850. return false;
  851. }
  852. /**
  853. * Portable Insert ID. Pablo Roca <pabloroca#mvps.org>
  854. *
  855. * @return the last inserted ID. All databases support this. But aware possible
  856. * problems in multiuser environments. Heavy test this before deploying.
  857. */
  858. function PO_Insert_ID($table="", $id="")
  859. {
  860. if ($this->hasInsertID){
  861. return $this->Insert_ID($table,$id);
  862. } else {
  863. return $this->GetOne("SELECT MAX($id) FROM $table");
  864. }
  865. }
  866. /**
  867. * @return # rows affected by UPDATE/DELETE
  868. */
  869. function Affected_Rows()
  870. {
  871. if ($this->hasAffectedRows) {
  872. if ($this->fnExecute === 'adodb_log_sql') {
  873. if ($this->_logsql && $this->_affected !== false) return $this->_affected;
  874. }
  875. $val = $this->_affectedrows();
  876. return ($val < 0) ? false : $val;
  877. }
  878. if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
  879. return false;
  880. }
  881. /**
  882. * @return the last error message
  883. */
  884. function ErrorMsg()
  885. {
  886. if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
  887. else return '';
  888. }
  889. /**
  890. * @return the last error number. Normally 0 means no error.
  891. */
  892. function ErrorNo()
  893. {
  894. return ($this->_errorMsg) ? -1 : 0;
  895. }
  896. function MetaError($err=false)
  897. {
  898. include_once(ADODB_DIR."/adodb-error.inc.php");
  899. if ($err === false) $err = $this->ErrorNo();
  900. return adodb_error($this->dataProvider,$this->databaseType,$err);
  901. }
  902. function MetaErrorMsg($errno)
  903. {
  904. include_once(ADODB_DIR."/adodb-error.inc.php");
  905. return adodb_errormsg($errno);
  906. }
  907. /**
  908. * @returns an array with the primary key columns in it.
  909. */
  910. function MetaPrimaryKeys($table, $owner=false)
  911. {
  912. // owner not used in base class - see oci8
  913. $p = array();
  914. $objs = $this->MetaColumns($table);
  915. if ($objs) {
  916. foreach($objs as $v) {
  917. if (!empty($v->primary_key))
  918. $p[] = $v->name;
  919. }
  920. }
  921. if (sizeof($p)) return $p;
  922. if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
  923. return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
  924. return false;
  925. }
  926. /**
  927. * @returns assoc array where keys are tables, and values are foreign keys
  928. */
  929. function MetaForeignKeys($table, $owner=false, $upper=false)
  930. {
  931. return false;
  932. }
  933. /**
  934. * Choose a database to connect to. Many databases do not support this.
  935. *
  936. * @param dbName is the name of the database to select
  937. * @return true or false
  938. */
  939. function SelectDB($dbName)
  940. {return false;}
  941. /**
  942. * Will select, getting rows from $offset (1-based), for $nrows.
  943. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  944. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  945. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  946. * eg.
  947. * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
  948. * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
  949. *
  950. * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
  951. * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
  952. *
  953. * @param sql
  954. * @param [offset] is the row to start calculations from (1-based)
  955. * @param [nrows] is the number of rows to get
  956. * @param [inputarr] array of bind variables
  957. * @param [secs2cache] is a private parameter only used by jlim
  958. * @return the recordset ($rs->databaseType == 'array')
  959. */
  960. function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
  961. {
  962. if ($this->hasTop && $nrows > 0) {
  963. // suggested by Reinhard Balling. Access requires top after distinct
  964. // Informix requires first before distinct - F Riosa
  965. $ismssql = (strpos($this->databaseType,'mssql') !== false);
  966. if ($ismssql) $isaccess = false;
  967. else $isaccess = (strpos($this->databaseType,'access') !== false);
  968. if ($offset <= 0) {
  969. // access includes ties in result
  970. if ($isaccess) {
  971. $sql = preg_replace(
  972. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  973. if ($secs2cache != 0) {
  974. $ret = $this->CacheExecute($secs2cache, $sql,$inputarr);
  975. } else {
  976. $ret = $this->Execute($sql,$inputarr);
  977. }
  978. return $ret; // PHP5 fix
  979. } else if ($ismssql){
  980. $sql = preg_replace(
  981. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  982. } else {
  983. $sql = preg_replace(
  984. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  985. }
  986. } else {
  987. $nn = $nrows + $offset;
  988. if ($isaccess || $ismssql) {
  989. $sql = preg_replace(
  990. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  991. } else {
  992. $sql = preg_replace(
  993. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  994. }
  995. }
  996. }
  997. // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
  998. // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
  999. global $ADODB_COUNTRECS;
  1000. $savec = $ADODB_COUNTRECS;
  1001. $ADODB_COUNTRECS = false;
  1002. if ($offset>0){
  1003. if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1004. else $rs = &$this->Execute($sql,$inputarr);
  1005. } else {
  1006. if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1007. else $rs = &$this->Execute($sql,$inputarr);
  1008. }
  1009. $ADODB_COUNTRECS = $savec;
  1010. if ($rs && !$rs->EOF) {
  1011. $rs = $this->_rs2rs($rs,$nrows,$offset);
  1012. }
  1013. //print_r($rs);
  1014. return $rs;
  1015. }
  1016. /**
  1017. * Create serializable recordset. Breaks rs link to connection.
  1018. *
  1019. * @param rs the recordset to serialize
  1020. */
  1021. function &SerializableRS(&$rs)
  1022. {
  1023. $rs2 = $this->_rs2rs($rs);
  1024. $ignore = false;
  1025. $rs2->connection = $ignore;
  1026. return $rs2;
  1027. }
  1028. /**
  1029. * Convert database recordset to an array recordset
  1030. * input recordset's cursor should be at beginning, and
  1031. * old $rs will be closed.
  1032. *
  1033. * @param rs the recordset to copy
  1034. * @param [nrows] number of rows to retrieve (optional)
  1035. * @param [offset] offset by number of rows (optional)
  1036. * @return the new recordset
  1037. */
  1038. function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
  1039. {
  1040. if (! $rs) {
  1041. $false = false;
  1042. return $false;
  1043. }
  1044. $dbtype = $rs->databaseType;
  1045. if (!$dbtype) {
  1046. $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
  1047. return $rs;
  1048. }
  1049. if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
  1050. $rs->MoveFirst();
  1051. $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
  1052. return $rs;
  1053. }
  1054. $flds = array();
  1055. for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
  1056. $flds[] = $rs->FetchField($i);
  1057. }
  1058. $arr = $rs->GetArrayLimit($nrows,$offset);
  1059. //print_r($arr);
  1060. if ($close) $rs->Close();
  1061. $arrayClass = $this->arrayClass;
  1062. $rs2 = new $arrayClass();
  1063. $rs2->connection = &$this;
  1064. $rs2->sql = $rs->sql;
  1065. $rs2->dataProvider = $this->dataProvider;
  1066. $rs2->InitArrayFields($arr,$flds);
  1067. $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
  1068. return $rs2;
  1069. }
  1070. /*
  1071. * Return all rows. Compat with PEAR DB
  1072. */
  1073. function &GetAll($sql, $inputarr=false)
  1074. {
  1075. $arr = $this->GetArray($sql,$inputarr);
  1076. return $arr;
  1077. }
  1078. function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
  1079. {
  1080. $rs = $this->Execute($sql, $inputarr);
  1081. if (!$rs) {
  1082. $false = false;
  1083. return $false;
  1084. }
  1085. $arr = $rs->GetAssoc($force_array,$first2cols);
  1086. return $arr;
  1087. }
  1088. function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
  1089. {
  1090. if (!is_numeric($secs2cache)) {
  1091. $first2cols = $force_array;
  1092. $force_array = $inputarr;
  1093. }
  1094. $rs = $this->CacheExecute($secs2cache, $sql, $inputarr);
  1095. if (!$rs) {
  1096. $false = false;
  1097. return $false;
  1098. }
  1099. $arr = $rs->GetAssoc($force_array,$first2cols);
  1100. return $arr;
  1101. }
  1102. /**
  1103. * Return first element of first row of sql statement. Recordset is disposed
  1104. * for you.
  1105. *
  1106. * @param sql SQL statement
  1107. * @param [inputarr] input bind array
  1108. */
  1109. function GetOne($sql,$inputarr=false)
  1110. {
  1111. global $ADODB_COUNTRECS;
  1112. $crecs = $ADODB_COUNTRECS;
  1113. $ADODB_COUNTRECS = false;
  1114. $ret = false;
  1115. $rs = &$this->Execute($sql,$inputarr);
  1116. if ($rs) {
  1117. if (!$rs->EOF) $ret = reset($rs->fields);
  1118. $rs->Close();
  1119. }
  1120. $ADODB_COUNTRECS = $crecs;
  1121. return $ret;
  1122. }
  1123. function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
  1124. {
  1125. $ret = false;
  1126. $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1127. if ($rs) {
  1128. if (!$rs->EOF) $ret = reset($rs->fields);
  1129. $rs->Close();
  1130. }
  1131. return $ret;
  1132. }
  1133. function GetCol($sql, $inputarr = false, $trim = false)
  1134. {
  1135. $rv = false;
  1136. $rs = &$this->Execute($sql, $inputarr);
  1137. if ($rs) {
  1138. $rv = array();
  1139. if ($trim) {
  1140. while (!$rs->EOF) {
  1141. $rv[] = trim(reset($rs->fields));
  1142. $rs->MoveNext();
  1143. }
  1144. } else {
  1145. while (!$rs->EOF) {
  1146. $rv[] = reset($rs->fields);
  1147. $rs->MoveNext();
  1148. }
  1149. }
  1150. $rs->Close();
  1151. }
  1152. return $rv;
  1153. }
  1154. function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
  1155. {
  1156. $rv = false;
  1157. $rs = &$this->CacheExecute($secs, $sql, $inputarr);
  1158. if ($rs) {
  1159. if ($trim) {
  1160. while (!$rs->EOF) {
  1161. $rv[] = trim(reset($rs->fields));
  1162. $rs->MoveNext();
  1163. }
  1164. } else {
  1165. while (!$rs->EOF) {
  1166. $rv[] = reset($rs->fields);
  1167. $rs->MoveNext();
  1168. }
  1169. }
  1170. $rs->Close();
  1171. }
  1172. return $rv;
  1173. }
  1174. function &Transpose(&$rs)
  1175. {
  1176. $rs2 = $this->_rs2rs($rs);
  1177. $false = false;
  1178. if (!$rs2) return $false;
  1179. $rs2->_transpose();
  1180. return $rs2;
  1181. }
  1182. /*
  1183. Calculate the offset of a date for a particular database and generate
  1184. appropriate SQL. Useful for calculating future/past dates and storing
  1185. in a database.
  1186. If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
  1187. */
  1188. function OffsetDate($dayFraction,$date=false)
  1189. {
  1190. if (!$date) $date = $this->sysDate;
  1191. return '('.$date.'+'.$dayFraction.')';
  1192. }
  1193. /**
  1194. *
  1195. * @param sql SQL statement
  1196. * @param [inputarr] input bind array
  1197. */
  1198. function &GetArray($sql,$inputarr=false)
  1199. {
  1200. global $ADODB_COUNTRECS;
  1201. $savec = $ADODB_COUNTRECS;
  1202. $ADODB_COUNTRECS = false;
  1203. $rs = $this->Execute($sql,$inputarr);
  1204. $ADODB_COUNTRECS = $savec;
  1205. if (!$rs)
  1206. if (defined('ADODB_PEAR')) {
  1207. $cls = ADODB_PEAR_Error();
  1208. return $cls;
  1209. } else {
  1210. $false = false;
  1211. return $false;
  1212. }
  1213. $arr = $rs->GetArray();
  1214. $rs->Close();
  1215. return $arr;
  1216. }
  1217. function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
  1218. {
  1219. return $this->CacheGetArray($secs2cache,$sql,$inputarr);
  1220. }
  1221. function &CacheGetArray($secs2cache,$sql=false,$inputarr=false)
  1222. {
  1223. global $ADODB_COUNTRECS;
  1224. $savec = $ADODB_COUNTRECS;
  1225. $ADODB_COUNTRECS = false;
  1226. $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
  1227. $ADODB_COUNTRECS = $savec;
  1228. if (!$rs)
  1229. if (defined('ADODB_PEAR')) {
  1230. $cls = ADODB_PEAR_Error();
  1231. return $cls;
  1232. } else {
  1233. $false = false;
  1234. return $false;
  1235. }
  1236. $arr = $rs->GetArray();
  1237. $rs->Close();
  1238. return $arr;
  1239. }
  1240. /**
  1241. * Return one row of sql statement. Recordset is disposed for you.
  1242. *
  1243. * @param sql SQL statement
  1244. * @param [inputarr] input bind array
  1245. */
  1246. function &GetRow($sql,$inputarr=false)
  1247. {
  1248. global $ADODB_COUNTRECS;
  1249. $crecs = $ADODB_COUNTRECS;
  1250. $ADODB_COUNTRECS = false;
  1251. $rs = $this->Execute($sql,$inputarr);
  1252. $ADODB_COUNTRECS = $crecs;
  1253. if ($rs) {
  1254. if (!$rs->EOF) $arr = $rs->fields;
  1255. else $arr = array();
  1256. $rs->Close();
  1257. return $arr;
  1258. }
  1259. $false = false;
  1260. return $false;
  1261. }
  1262. function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
  1263. {
  1264. $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
  1265. if ($rs) {
  1266. $arr = false;
  1267. if (!$rs->EOF) $arr = $rs->fields;
  1268. $rs->Close();
  1269. return $arr;
  1270. }
  1271. $false = false;
  1272. return $false;
  1273. }
  1274. /**
  1275. * Insert or replace a single record. Note: this is not the same as MySQL's replace.
  1276. * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
  1277. * Also note that no table locking is done currently, so it is possible that the
  1278. * record be inserted twice by two programs...
  1279. *
  1280. * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
  1281. *
  1282. * $table table name
  1283. * $fieldArray associative array of data (you must quote strings yourself).
  1284. * $keyCol the primary key field name or if compound key, array of field names
  1285. * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
  1286. * but does not work with dates nor SQL functions.
  1287. * has_autoinc the primary key is an auto-inc field, so skip in insert.
  1288. *
  1289. * Currently blob replace not supported
  1290. *
  1291. * returns 0 = fail, 1 = update, 2 = insert
  1292. */
  1293. function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
  1294. {
  1295. global $ADODB_INCLUDED_LIB;
  1296. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1297. return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
  1298. }
  1299. /**
  1300. * Will select, getting rows from $offset (1-based), for $nrows.
  1301. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  1302. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  1303. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  1304. * eg.
  1305. * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
  1306. * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
  1307. *
  1308. * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
  1309. *
  1310. * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
  1311. * @param sql
  1312. * @param [offset] is the row to start calculations from (1-based)
  1313. * @param [nrows] is the number of rows to get
  1314. * @param [inputarr] array of bind variables
  1315. * @return the recordset ($rs->databaseType == 'array')
  1316. */
  1317. function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
  1318. {
  1319. if (!is_numeric($secs2cache)) {
  1320. if ($sql === false) $sql = -1;
  1321. if ($offset == -1) $offset = false;
  1322. // sql, nrows, offset,inputarr
  1323. $rs = $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
  1324. } else {
  1325. if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
  1326. $rs = $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
  1327. }
  1328. return $rs;
  1329. }
  1330. /**
  1331. * Flush cached recordsets that match a particular $sql statement.
  1332. * If $sql == false, then we purge all files in the cache.
  1333. */
  1334. /**
  1335. * Flush cached recordsets that match a particular $sql statement.
  1336. * If $sql == false, then we purge all files in the cache.
  1337. */
  1338. function CacheFlush($sql=false,$inputarr=false)
  1339. {
  1340. global $ADODB_CACHE_DIR;
  1341. if ( !$this->cacheSecs ) return ;
  1342. if ($this->memCache) {
  1343. global $ADODB_INCLUDED_MEMCACHE;
  1344. $key = false;
  1345. if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
  1346. if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
  1347. FlushMemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
  1348. return;
  1349. }
  1350. if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
  1351. /*if (strncmp(PHP_OS,'WIN',3) === 0)
  1352. $dir = str_replace('/', '\\', $ADODB_CACHE_DIR);
  1353. else */
  1354. $dir = $ADODB_CACHE_DIR;
  1355. if ($this->debug) {
  1356. ADOConnection::outp( "CacheFlush: $dir<br><pre>\n", $this->_dirFlush($dir),"</pre>");
  1357. } else {
  1358. $this->_dirFlush($dir);
  1359. }
  1360. return;
  1361. }
  1362. global $ADODB_INCLUDED_CSV;
  1363. if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  1364. $f = $this->_gencachename($sql.serialize($inputarr),false);
  1365. adodb_write_file($f,''); // is adodb_write_file needed?
  1366. if (!@unlink($f)) {
  1367. if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
  1368. }
  1369. }
  1370. /**
  1371. * Private function to erase all of the files and subdirectories in a directory.
  1372. *
  1373. * Just specify the directory, and tell it if you want to delete the directory or just clear it out.
  1374. * Note: $kill_top_level is used internally in the function to flush subdirectories.
  1375. */
  1376. function _dirFlush($dir, $kill_top_level = false) {
  1377. if(!$dh = @opendir($dir)) return;
  1378. while (($obj = readdir($dh))) {
  1379. if($obj=='.' || $obj=='..')
  1380. continue;
  1381. if (!@unlink($dir.'/'.$obj))
  1382. $this->_dirFlush($dir.'/'.$obj, true);
  1383. }
  1384. if ($kill_top_level === true)
  1385. @rmdir($dir);
  1386. return true;
  1387. }
  1388. function xCacheFlush($sql=false,$inputarr=false)
  1389. {
  1390. global $ADODB_CACHE_DIR;
  1391. if ( !$this->cacheSecs ) return ;
  1392. if ($this->memCache) {
  1393. global $ADODB_INCLUDED_MEMCACHE;
  1394. $key = false;
  1395. if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
  1396. if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
  1397. FlushMemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
  1398. return;
  1399. }
  1400. if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
  1401. if (strncmp(PHP_OS,'WIN',3) === 0) {
  1402. $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
  1403. } else {
  1404. //$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f';
  1405. $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/';
  1406. // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
  1407. }
  1408. if ($this->debug) {
  1409. ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
  1410. } else {
  1411. exec($cmd);
  1412. }
  1413. return;
  1414. }
  1415. global $ADODB_INCLUDED_CSV;
  1416. if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  1417. $f = $this->_gencachename($sql.serialize($inputarr),false);
  1418. adodb_write_file($f,''); // is adodb_write_file needed?
  1419. if (!@unlink($f)) {
  1420. if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
  1421. }
  1422. }
  1423. /**
  1424. * Private function to generate filename for caching.
  1425. * Filename is generated based on:
  1426. *
  1427. * - sql statement
  1428. * - database type (oci8, ibase, ifx, etc)
  1429. * - database name
  1430. * - userid
  1431. * - setFetchMode (adodb 4.23)
  1432. *
  1433. * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
  1434. * Assuming that we can have 50,000 files per directory with good performance,
  1435. * then we can scale to 12.8 million unique cached recordsets. Wow!
  1436. */
  1437. function _gencachename($sql,$createdir,$memcache=false)
  1438. {
  1439. global $ADODB_CACHE_DIR;
  1440. static $notSafeMode;
  1441. if ($this->fetchMode === false) {
  1442. global $ADODB_FETCH_MODE;
  1443. $mode = $ADODB_FETCH_MODE;
  1444. } else {
  1445. $mode = $this->fetchMode;
  1446. }
  1447. $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
  1448. if ($memcache) return $m;
  1449. if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode');
  1450. $dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR;
  1451. if ($createdir && $notSafeMode && !file_exists($dir)) {
  1452. $oldu = umask(0);
  1453. if (!mkdir($dir,0771))
  1454. if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
  1455. umask($oldu);
  1456. }
  1457. return $dir.'/adodb_'.$m.'.cache';
  1458. }
  1459. /**
  1460. * Execute SQL, caching recordsets.
  1461. *
  1462. * @param [secs2cache] seconds to cache data, set to 0 to force query.
  1463. * This is an optional parameter.
  1464. * @param sql SQL statement to execute
  1465. * @param [inputarr] holds the input data to bind to
  1466. * @return RecordSet or false
  1467. */
  1468. function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
  1469. {
  1470. if (!is_numeric($secs2cache)) {
  1471. $inputarr = $sql;
  1472. $sql = $secs2cache;
  1473. $secs2cache = $this->cacheSecs;
  1474. }
  1475. if (is_array($sql)) {
  1476. $sqlparam = $sql;
  1477. $sql = $sql[0];
  1478. } else
  1479. $sqlparam = $sql;
  1480. if ($this->memCache) {
  1481. global $ADODB_INCLUDED_MEMCACHE;
  1482. if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
  1483. $md5file = $this->_gencachename($sql.serialize($inputarr),false,true);
  1484. } else {
  1485. global $ADODB_INCLUDED_CSV;
  1486. if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  1487. $md5file = $this->_gencachename($sql.serialize($inputarr),true);
  1488. }
  1489. $err = '';
  1490. if ($secs2cache > 0){
  1491. if ($this->memCache)
  1492. $rs = &getmemCache($md5file,$err,$secs2cache, $this->memCacheHost, $this->memCachePort);
  1493. else
  1494. $rs = &csv2rs($md5file,$err,$secs2cache,$this->arrayClass);
  1495. $this->numCacheHits += 1;
  1496. } else {
  1497. $err='Timeout 1';
  1498. $rs = false;
  1499. $this->numCacheMisses += 1;
  1500. }
  1501. if (!$rs) {
  1502. // no cached rs found
  1503. if ($this->debug) {
  1504. if (get_magic_quotes_runtime() && !$this->memCache) {
  1505. ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
  1506. }
  1507. if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
  1508. }
  1509. $rs = &$this->Execute($sqlparam,$inputarr);
  1510. if ($rs && $this->memCache) {
  1511. $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
  1512. if(!putmemCache($md5file, $rs, $this->memCacheHost, $this->memCachePort, $this->memCacheCompress, $this->debug)) {
  1513. if ($fn = $this->raiseErrorFn)
  1514. $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
  1515. if ($this->debug) ADOConnection::outp( " Cache write error");
  1516. }
  1517. } else
  1518. if ($rs && $secs2cache ) {
  1519. $eof = $rs->EOF;
  1520. $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
  1521. $txt = _rs2serialize($rs,false,$sql); // serialize
  1522. if (!adodb_write_file($md5file,$txt,$this->debug)) {
  1523. if ($fn = $this->raiseErrorFn) {
  1524. $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
  1525. }
  1526. if ($this->debug) ADOConnection::outp( " Cache write error");
  1527. }
  1528. if ($rs->EOF && !$eof) {
  1529. $rs->MoveFirst();
  1530. //$rs = &csv2rs($md5file,$err);
  1531. $rs->connection = &$this; // Pablo suggestion
  1532. }
  1533. } else
  1534. if (!$this->memCache)
  1535. @unlink($md5file);
  1536. } else {
  1537. $this->_errorMsg = '';
  1538. $this->_errorCode = 0;
  1539. if ($this->fnCacheExecute) {
  1540. $fn = $this->fnCacheExecute;
  1541. $fn($this, $secs2cache, $sql, $inputarr);
  1542. }
  1543. // ok, set cached object found
  1544. $rs->connection = &$this; // Pablo suggestion
  1545. if ($this->debug){
  1546. $inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
  1547. $ttl = $rs->timeCreated + $secs2cache - time();
  1548. $s = is_array($sql) ? $sql[0] : $sql;
  1549. if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
  1550. ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
  1551. }
  1552. }
  1553. return $rs;
  1554. }
  1555. /*
  1556. Similar to PEAR DB's autoExecute(), except that
  1557. $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
  1558. If $mode == 'UPDATE', then $where is compulsory as a safety measure.
  1559. $forceUpdate means that even if the data has not changed, perform update.
  1560. */
  1561. function& AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false)
  1562. {
  1563. $false = false;
  1564. $sql = 'SELECT * FROM '.$table;
  1565. if ($where!==FALSE) $sql .= ' WHERE '.$where;
  1566. else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
  1567. ADOConnection::outp('AutoExecute: Illegal mode=UPDATE with empty WHERE clause');
  1568. return $false;
  1569. }
  1570. $rs = $this->SelectLimit($sql,1);
  1571. if (!$rs) return $false; // table does not exist
  1572. $rs->tableName = $table;
  1573. switch((string) $mode) {
  1574. case 'UPDATE':
  1575. case '2':
  1576. $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
  1577. break;
  1578. case 'INSERT':
  1579. case '1':
  1580. $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
  1581. break;
  1582. default:
  1583. ADOConnection::outp("AutoExecute: Unknown mode=$mode");
  1584. return $false;
  1585. }
  1586. $ret = false;
  1587. if ($sql) $ret = $this->Execute($sql);
  1588. if ($ret) $ret = true;
  1589. return $ret;
  1590. }
  1591. /**
  1592. * Generates an Update Query based on an existing recordset.
  1593. * $arrFields is an associative array of fields with the value
  1594. * that should be assigned.
  1595. *
  1596. * Note: This function should only be used on a recordset
  1597. * that is run against a single table and sql should only
  1598. * be a simple select stmt with no groupby/orderby/limit
  1599. *
  1600. * "Jonathan Younger" <jyounger@unilab.com>
  1601. */
  1602. function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
  1603. {
  1604. global $ADODB_INCLUDED_LIB;
  1605. //********************************************************//
  1606. //This is here to maintain compatibility
  1607. //with older adodb versions. Sets force type to force nulls if $forcenulls is set.
  1608. if (!isset($force)) {
  1609. global $ADODB_FORCE_TYPE;
  1610. $force = $ADODB_FORCE_TYPE;
  1611. }
  1612. //********************************************************//
  1613. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1614. return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
  1615. }
  1616. /**
  1617. * Generates an Insert Query based on an existing recordset.
  1618. * $arrFields is an associative array of fields with the value
  1619. * that should be assigned.
  1620. *
  1621. * Note: This function should only be used on a recordset
  1622. * that is run against a single table.
  1623. */
  1624. function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
  1625. {
  1626. global $ADODB_INCLUDED_LIB;
  1627. if (!isset($force)) {
  1628. global $ADODB_FORCE_TYPE;
  1629. $force = $ADODB_FORCE_TYPE;
  1630. }
  1631. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1632. return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
  1633. }
  1634. /**
  1635. * Update a blob column, given a where clause. There are more sophisticated
  1636. * blob handling functions that we could have implemented, but all require
  1637. * a very complex API. Instead we have chosen something that is extremely
  1638. * simple to understand and use.
  1639. *
  1640. * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
  1641. *
  1642. * Usage to update a $blobvalue which has a primary key blob_id=1 into a
  1643. * field blobtable.blobcolumn:
  1644. *
  1645. * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
  1646. *
  1647. * Insert example:
  1648. *
  1649. * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1650. * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
  1651. */
  1652. function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  1653. {
  1654. return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
  1655. }
  1656. /**
  1657. * Usage:
  1658. * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
  1659. *
  1660. * $blobtype supports 'BLOB' and 'CLOB'
  1661. *
  1662. * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1663. * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
  1664. */
  1665. function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
  1666. {
  1667. $fd = fopen($path,'rb');
  1668. if ($fd === false) return false;
  1669. $val = fread($fd,filesize($path));
  1670. fclose($fd);
  1671. return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
  1672. }
  1673. function BlobDecode($blob)
  1674. {
  1675. return $blob;
  1676. }
  1677. function BlobEncode($blob)
  1678. {
  1679. return $blob;
  1680. }
  1681. function SetCharSet($charset)
  1682. {
  1683. return false;
  1684. }
  1685. function IfNull( $field, $ifNull )
  1686. {
  1687. return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
  1688. }
  1689. function LogSQL($enable=true)
  1690. {
  1691. include_once(ADODB_DIR.'/adodb-perf.inc.php');
  1692. if ($enable) $this->fnExecute = 'adodb_log_sql';
  1693. else $this->fnExecute = false;
  1694. $old = $this->_logsql;
  1695. $this->_logsql = $enable;
  1696. if ($enable && !$old) $this->_affected = false;
  1697. return $old;
  1698. }
  1699. function GetCharSet()
  1700. {
  1701. return false;
  1702. }
  1703. /**
  1704. * Usage:
  1705. * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
  1706. *
  1707. * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
  1708. * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
  1709. */
  1710. function UpdateClob($table,$column,$val,$where)
  1711. {
  1712. return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
  1713. }
  1714. // not the fastest implementation - quick and dirty - jlim
  1715. // for best performance, use the actual $rs->MetaType().
  1716. function MetaType($t,$len=-1,$fieldobj=false)
  1717. {
  1718. if (empty($this->_metars)) {
  1719. $rsclass = $this->rsPrefix.$this->databaseType;
  1720. $this->_metars = new $rsclass(false,$this->fetchMode);
  1721. $this->_metars->connection = $this;
  1722. }
  1723. return $this->_metars->MetaType($t,$len,$fieldobj);
  1724. }
  1725. /**
  1726. * Change the SQL connection locale to a specified locale.
  1727. * This is used to get the date formats written depending on the client locale.
  1728. */
  1729. function SetDateLocale($locale = 'En')
  1730. {
  1731. $this->locale = $locale;
  1732. switch (strtoupper($locale))
  1733. {
  1734. case 'EN':
  1735. $this->fmtDate="'Y-m-d'";
  1736. $this->fmtTimeStamp = "'Y-m-d H:i:s'";
  1737. break;
  1738. case 'US':
  1739. $this->fmtDate = "'m-d-Y'";
  1740. $this->fmtTimeStamp = "'m-d-Y H:i:s'";
  1741. break;
  1742. case 'NL':
  1743. case 'FR':
  1744. case 'RO':
  1745. case 'IT':
  1746. $this->fmtDate="'d-m-Y'";
  1747. $this->fmtTimeStamp = "'d-m-Y H:i:s'";
  1748. break;
  1749. case 'GE':
  1750. $this->fmtDate="'d.m.Y'";
  1751. $this->fmtTimeStamp = "'d.m.Y H:i:s'";
  1752. break;
  1753. default:
  1754. $this->fmtDate="'Y-m-d'";
  1755. $this->fmtTimeStamp = "'Y-m-d H:i:s'";
  1756. break;
  1757. }
  1758. }
  1759. function &GetActiveRecordsClass($class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false)
  1760. {
  1761. global $_ADODB_ACTIVE_DBS;
  1762. $save = $this->SetFetchMode(ADODB_FETCH_NUM);
  1763. if (empty($whereOrderBy)) $whereOrderBy = '1=1';
  1764. $rows = $this->GetAll("select * from ".$table.' WHERE '.$whereOrderBy,$bindarr);
  1765. $this->SetFetchMode($save);
  1766. $false = false;
  1767. if ($rows === false) {
  1768. return $false;
  1769. }
  1770. if (!isset($_ADODB_ACTIVE_DBS)) {
  1771. include(ADODB_DIR.'/adodb-active-record.inc.php');
  1772. }
  1773. if (!class_exists($class)) {
  1774. ADOConnection::outp("Unknown class $class in GetActiveRcordsClass()");
  1775. return $false;
  1776. }
  1777. $arr = array();
  1778. foreach($rows as $row) {
  1779. $obj = new $class($table,$primkeyArr,$this);
  1780. if ($obj->ErrorMsg()){
  1781. $this->_errorMsg = $obj->ErrorMsg();
  1782. return $false;
  1783. }
  1784. $obj->Set($row);
  1785. $arr[] = $obj;
  1786. }
  1787. return $arr;
  1788. }
  1789. function &GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
  1790. {
  1791. $arr = $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
  1792. return $arr;
  1793. }
  1794. /**
  1795. * Close Connection
  1796. */
  1797. function Close()
  1798. {
  1799. $rez = $this->_close();
  1800. $this->_connectionID = false;
  1801. return $rez;
  1802. }
  1803. /**
  1804. * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
  1805. *
  1806. * @return true if succeeded or false if database does not support transactions
  1807. */
  1808. function BeginTrans() {return false;}
  1809. /* set transaction mode */
  1810. function SetTransactionMode( $transaction_mode )
  1811. {
  1812. $transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider);
  1813. $this->_transmode = $transaction_mode;
  1814. }
  1815. /*
  1816. http://msdn2.microsoft.com/en-US/ms173763.aspx
  1817. http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html
  1818. http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html
  1819. http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm
  1820. */
  1821. function MetaTransaction($mode,$db)
  1822. {
  1823. $mode = strtoupper($mode);
  1824. $mode = str_replace('ISOLATION LEVEL ','',$mode);
  1825. switch($mode) {
  1826. case 'READ UNCOMMITTED':
  1827. switch($db) {
  1828. case 'oci8':
  1829. case 'oracle':
  1830. return 'ISOLATION LEVEL READ COMMITTED';
  1831. default:
  1832. return 'ISOLATION LEVEL READ UNCOMMITTED';
  1833. }
  1834. break;
  1835. case 'READ COMMITTED':
  1836. return 'ISOLATION LEVEL READ COMMITTED';
  1837. break;
  1838. case 'REPEATABLE READ':
  1839. switch($db) {
  1840. case 'oci8':
  1841. case 'oracle':
  1842. return 'ISOLATION LEVEL SERIALIZABLE';
  1843. default:
  1844. return 'ISOLATION LEVEL REPEATABLE READ';
  1845. }
  1846. break;
  1847. case 'SERIALIZABLE':
  1848. return 'ISOLATION LEVEL SERIALIZABLE';
  1849. break;
  1850. default:
  1851. return $mode;
  1852. }
  1853. }
  1854. /**
  1855. * If database does not support transactions, always return true as data always commited
  1856. *
  1857. * @param $ok set to false to rollback transaction, true to commit
  1858. *
  1859. * @return true/false.
  1860. */
  1861. function CommitTrans($ok=true)
  1862. { return true;}
  1863. /**
  1864. * If database does not support transactions, rollbacks always fail, so return false
  1865. *
  1866. * @return true/false.
  1867. */
  1868. function RollbackTrans()
  1869. { return false;}
  1870. /**
  1871. * return the databases that the driver can connect to.
  1872. * Some databases will return an empty array.
  1873. *
  1874. * @return an array of database names.
  1875. */
  1876. function MetaDatabases()
  1877. {
  1878. global $ADODB_FETCH_MODE;
  1879. if ($this->metaDatabasesSQL) {
  1880. $save = $ADODB_FETCH_MODE;
  1881. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1882. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1883. $arr = $this->GetCol($this->metaDatabasesSQL);
  1884. if (isset($savem)) $this->SetFetchMode($savem);
  1885. $ADODB_FETCH_MODE = $save;
  1886. return $arr;
  1887. }
  1888. return false;
  1889. }
  1890. /**
  1891. * @param ttype can either be 'VIEW' or 'TABLE' or false.
  1892. * If false, both views and tables are returned.
  1893. * "VIEW" returns only views
  1894. * "TABLE" returns only tables
  1895. * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
  1896. * @param mask is the input mask - only supported by oci8 and postgresql
  1897. *
  1898. * @return array of tables for current database.
  1899. */
  1900. function &MetaTables($ttype=false,$showSchema=false,$mask=false)
  1901. {
  1902. global $ADODB_FETCH_MODE;
  1903. $false = false;
  1904. if ($mask) {
  1905. return $false;
  1906. }
  1907. if ($this->metaTablesSQL) {
  1908. $save = $ADODB_FETCH_MODE;
  1909. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1910. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1911. $rs = $this->Execute($this->metaTablesSQL);
  1912. if (isset($savem)) $this->SetFetchMode($savem);
  1913. $ADODB_FETCH_MODE = $save;
  1914. if ($rs === false) return $false;
  1915. $arr = $rs->GetArray();
  1916. $arr2 = array();
  1917. if ($hast = ($ttype && isset($arr[0][1]))) {
  1918. $showt = strncmp($ttype,'T',1);
  1919. }
  1920. for ($i=0; $i < sizeof($arr); $i++) {
  1921. if ($hast) {
  1922. if ($showt == 0) {
  1923. if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
  1924. } else {
  1925. if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
  1926. }
  1927. } else
  1928. $arr2[] = trim($arr[$i][0]);
  1929. }
  1930. $rs->Close();
  1931. return $arr2;
  1932. }
  1933. return $false;
  1934. }
  1935. function _findschema(&$table,&$schema)
  1936. {
  1937. if (!$schema && ($at = strpos($table,'.')) !== false) {
  1938. $schema = substr($table,0,$at);
  1939. $table = substr($table,$at+1);
  1940. }
  1941. }
  1942. /**
  1943. * List columns in a database as an array of ADOFieldObjects.
  1944. * See top of file for definition of object.
  1945. *
  1946. * @param $table table name to query
  1947. * @param $normalize makes table name case-insensitive (required by some databases)
  1948. * @schema is optional database schema to use - not supported by all databases.
  1949. *
  1950. * @return array of ADOFieldObjects for current table.
  1951. */
  1952. function &MetaColumns($table,$normalize=true)
  1953. {
  1954. global $ADODB_FETCH_MODE;
  1955. $false = false;
  1956. if (!empty($this->metaColumnsSQL)) {
  1957. $schema = false;
  1958. $this->_findschema($table,$schema);
  1959. $save = $ADODB_FETCH_MODE;
  1960. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1961. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1962. $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table));
  1963. if (isset($savem)) $this->SetFetchMode($savem);
  1964. $ADODB_FETCH_MODE = $save;
  1965. if ($rs === false || $rs->EOF) return $false;
  1966. $retarr = array();
  1967. while (!$rs->EOF) { //print_r($rs->fields);
  1968. $fld = new ADOFieldObject();
  1969. $fld->name = $rs->fields[0];
  1970. $fld->type = $rs->fields[1];
  1971. if (isset($rs->fields[3]) && $rs->fields[3]) {
  1972. if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
  1973. $fld->scale = $rs->fields[4];
  1974. if ($fld->scale>0) $fld->max_length += 1;
  1975. } else
  1976. $fld->max_length = $rs->fields[2];
  1977. if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
  1978. else $retarr[strtoupper($fld->name)] = $fld;
  1979. $rs->MoveNext();
  1980. }
  1981. $rs->Close();
  1982. return $retarr;
  1983. }
  1984. return $false;
  1985. }
  1986. /**
  1987. * List indexes on a table as an array.
  1988. * @param table table name to query
  1989. * @param primary true to only show primary keys. Not actually used for most databases
  1990. *
  1991. * @return array of indexes on current table. Each element represents an index, and is itself an associative array.
  1992. Array (
  1993. [name_of_index] => Array
  1994. (
  1995. [unique] => true or false
  1996. [columns] => Array
  1997. (
  1998. [0] => firstname
  1999. [1] => lastname
  2000. )
  2001. )
  2002. */
  2003. function &MetaIndexes($table, $primary = false, $owner = false)
  2004. {
  2005. $false = false;
  2006. return $false;
  2007. }
  2008. /**
  2009. * List columns names in a table as an array.
  2010. * @param table table name to query
  2011. *
  2012. * @return array of column names for current table.
  2013. */
  2014. function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */)
  2015. {
  2016. $objarr = $this->MetaColumns($table);
  2017. if (!is_array($objarr)) {
  2018. $false = false;
  2019. return $false;
  2020. }
  2021. $arr = array();
  2022. if ($numIndexes) {
  2023. $i = 0;
  2024. if ($useattnum) {
  2025. foreach($objarr as $v)
  2026. $arr[$v->attnum] = $v->name;
  2027. } else
  2028. foreach($objarr as $v) $arr[$i++] = $v->name;
  2029. } else
  2030. foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
  2031. return $arr;
  2032. }
  2033. /**
  2034. * Different SQL databases used different methods to combine strings together.
  2035. * This function provides a wrapper.
  2036. *
  2037. * param s variable number of string parameters
  2038. *
  2039. * Usage: $db->Concat($str1,$str2);
  2040. *
  2041. * @return concatenated string
  2042. */
  2043. function Concat()
  2044. {
  2045. $arr = func_get_args();
  2046. return implode($this->concat_operator, $arr);
  2047. }
  2048. /**
  2049. * Converts a date "d" to a string that the database can understand.
  2050. *
  2051. * @param d a date in Unix date time format.
  2052. *
  2053. * @return date string in database date format
  2054. */
  2055. function DBDate($d)
  2056. {
  2057. if (empty($d) && $d !== 0) return 'null';
  2058. if (is_string($d) && !is_numeric($d)) {
  2059. if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
  2060. if ($this->isoDates) return "'$d'";
  2061. $d = ADOConnection::UnixDate($d);
  2062. }
  2063. return adodb_date($this->fmtDate,$d);
  2064. }
  2065. function BindDate($d)
  2066. {
  2067. $d = $this->DBDate($d);
  2068. if (strncmp($d,"'",1)) return $d;
  2069. return substr($d,1,strlen($d)-2);
  2070. }
  2071. function BindTimeStamp($d)
  2072. {
  2073. $d = $this->DBTimeStamp($d);
  2074. if (strncmp($d,"'",1)) return $d;
  2075. return substr($d,1,strlen($d)-2);
  2076. }
  2077. /**
  2078. * Converts a timestamp "ts" to a string that the database can understand.
  2079. *
  2080. * @param ts a timestamp in Unix date time format.
  2081. *
  2082. * @return timestamp string in database timestamp format
  2083. */
  2084. function DBTimeStamp($ts)
  2085. {
  2086. if (empty($ts) && $ts !== 0) return 'null';
  2087. # strlen(14) allows YYYYMMDDHHMMSS format
  2088. if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
  2089. return adodb_date($this->fmtTimeStamp,$ts);
  2090. if ($ts === 'null') return $ts;
  2091. if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
  2092. $ts = ADOConnection::UnixTimeStamp($ts);
  2093. return adodb_date($this->fmtTimeStamp,$ts);
  2094. }
  2095. /**
  2096. * Also in ADORecordSet.
  2097. * @param $v is a date string in YYYY-MM-DD format
  2098. *
  2099. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2100. */
  2101. function UnixDate($v)
  2102. {
  2103. if (is_object($v)) {
  2104. // odbtp support
  2105. //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
  2106. return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
  2107. }
  2108. if (is_numeric($v) && strlen($v) !== 8) return $v;
  2109. if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
  2110. ($v), $rr)) return false;
  2111. if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
  2112. // h-m-s-MM-DD-YY
  2113. return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  2114. }
  2115. /**
  2116. * Also in ADORecordSet.
  2117. * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  2118. *
  2119. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2120. */
  2121. function UnixTimeStamp($v)
  2122. {
  2123. if (is_object($v)) {
  2124. // odbtp support
  2125. //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
  2126. return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
  2127. }
  2128. if (!preg_match(
  2129. "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
  2130. ($v), $rr)) return false;
  2131. if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
  2132. // h-m-s-MM-DD-YY
  2133. if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  2134. return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
  2135. }
  2136. /**
  2137. * Also in ADORecordSet.
  2138. *
  2139. * Format database date based on user defined format.
  2140. *
  2141. * @param v is the character date in YYYY-MM-DD format, returned by database
  2142. * @param fmt is the format to apply to it, using date()
  2143. *
  2144. * @return a date formated as user desires
  2145. */
  2146. function UserDate($v,$fmt='Y-m-d',$gmt=false)
  2147. {
  2148. $tt = $this->UnixDate($v);
  2149. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2150. if (($tt === false || $tt == -1) && $v != false) return $v;
  2151. else if ($tt == 0) return $this->emptyDate;
  2152. else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  2153. }
  2154. return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  2155. }
  2156. /**
  2157. *
  2158. * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
  2159. * @param fmt is the format to apply to it, using date()
  2160. *
  2161. * @return a timestamp formated as user desires
  2162. */
  2163. function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)
  2164. {
  2165. if (!isset($v)) return $this->emptyTimeStamp;
  2166. # strlen(14) allows YYYYMMDDHHMMSS format
  2167. if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
  2168. $tt = $this->UnixTimeStamp($v);
  2169. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2170. if (($tt === false || $tt == -1) && $v != false) return $v;
  2171. if ($tt == 0) return $this->emptyTimeStamp;
  2172. return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  2173. }
  2174. function escape($s,$magic_quotes=false)
  2175. {
  2176. return $this->addq($s,$magic_quotes);
  2177. }
  2178. /**
  2179. * Quotes a string, without prefixing nor appending quotes.
  2180. */
  2181. function addq($s,$magic_quotes=false)
  2182. {
  2183. if (!$magic_quotes) {
  2184. if ($this->replaceQuote[0] == '\\'){
  2185. // only since php 4.0.5
  2186. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  2187. //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  2188. }
  2189. return str_replace("'",$this->replaceQuote,$s);
  2190. }
  2191. // undo magic quotes for "
  2192. $s = str_replace('\\"','"',$s);
  2193. if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
  2194. return $s;
  2195. else {// change \' to '' for sybase/mssql
  2196. $s = str_replace('\\\\','\\',$s);
  2197. return str_replace("\\'",$this->replaceQuote,$s);
  2198. }
  2199. }
  2200. /**
  2201. * Correctly quotes a string so that all strings are escaped. We prefix and append
  2202. * to the string single-quotes.
  2203. * An example is $db->qstr("Don't bother",magic_quotes_runtime());
  2204. *
  2205. * @param s the string to quote
  2206. * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
  2207. * This undoes the stupidity of magic quotes for GPC.
  2208. *
  2209. * @return quoted string to be sent back to database
  2210. */
  2211. function qstr($s,$magic_quotes=false)
  2212. {
  2213. if (!$magic_quotes) {
  2214. if ($this->replaceQuote[0] == '\\'){
  2215. // only since php 4.0.5
  2216. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  2217. //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  2218. }
  2219. return "'".str_replace("'",$this->replaceQuote,$s)."'";
  2220. }
  2221. // undo magic quotes for "
  2222. $s = str_replace('\\"','"',$s);
  2223. if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
  2224. return "'$s'";
  2225. else {// change \' to '' for sybase/mssql
  2226. $s = str_replace('\\\\','\\',$s);
  2227. return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
  2228. }
  2229. }
  2230. /**
  2231. * Will select the supplied $page number from a recordset, given that it is paginated in pages of
  2232. * $nrows rows per page. It also saves two boolean values saying if the given page is the first
  2233. * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
  2234. *
  2235. * See readme.htm#ex8 for an example of usage.
  2236. *
  2237. * @param sql
  2238. * @param nrows is the number of rows per page to get
  2239. * @param page is the page number to get (1-based)
  2240. * @param [inputarr] array of bind variables
  2241. * @param [secs2cache] is a private parameter only used by jlim
  2242. * @return the recordset ($rs->databaseType == 'array')
  2243. *
  2244. * NOTE: phpLens uses a different algorithm and does not use PageExecute().
  2245. *
  2246. */
  2247. function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
  2248. {
  2249. global $ADODB_INCLUDED_LIB;
  2250. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  2251. if ($this->pageExecuteCountRows) $rs = _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  2252. else $rs = _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  2253. return $rs;
  2254. }
  2255. /**
  2256. * Will select the supplied $page number from a recordset, given that it is paginated in pages of
  2257. * $nrows rows per page. It also saves two boolean values saying if the given page is the first
  2258. * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
  2259. *
  2260. * @param secs2cache seconds to cache data, set to 0 to force query
  2261. * @param sql
  2262. * @param nrows is the number of rows per page to get
  2263. * @param page is the page number to get (1-based)
  2264. * @param [inputarr] array of bind variables
  2265. * @return the recordset ($rs->databaseType == 'array')
  2266. */
  2267. function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
  2268. {
  2269. /*switch($this->dataProvider) {
  2270. case 'postgres':
  2271. case 'mysql':
  2272. break;
  2273. default: $secs2cache = 0; break;
  2274. }*/
  2275. $rs = $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
  2276. return $rs;
  2277. }
  2278. } // end class ADOConnection
  2279. //==============================================================================================
  2280. // CLASS ADOFetchObj
  2281. //==============================================================================================
  2282. /**
  2283. * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
  2284. */
  2285. class ADOFetchObj {
  2286. };
  2287. //==============================================================================================
  2288. // CLASS ADORecordSet_empty
  2289. //==============================================================================================
  2290. /**
  2291. * Lightweight recordset when there are no records to be returned
  2292. */
  2293. class ADORecordSet_empty
  2294. {
  2295. var $dataProvider = 'empty';
  2296. var $databaseType = false;
  2297. var $EOF = true;
  2298. var $_numOfRows = 0;
  2299. var $fields = false;
  2300. var $connection = false;
  2301. function RowCount() {return 0;}
  2302. function RecordCount() {return 0;}
  2303. function PO_RecordCount(){return 0;}
  2304. function Close(){return true;}
  2305. function FetchRow() {return false;}
  2306. function FieldCount(){ return 0;}
  2307. function Init() {}
  2308. }
  2309. //==============================================================================================
  2310. // DATE AND TIME FUNCTIONS
  2311. //==============================================================================================
  2312. if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php');
  2313. //==============================================================================================
  2314. // CLASS ADORecordSet
  2315. //==============================================================================================
  2316. if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
  2317. else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
  2318. /**
  2319. * RecordSet class that represents the dataset returned by the database.
  2320. * To keep memory overhead low, this class holds only the current row in memory.
  2321. * No prefetching of data is done, so the RecordCount() can return -1 ( which
  2322. * means recordcount not known).
  2323. */
  2324. class ADORecordSet extends ADODB_BASE_RS {
  2325. /*
  2326. * public variables
  2327. */
  2328. var $dataProvider = "native";
  2329. var $fields = false; /// holds the current row data
  2330. var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
  2331. /// in other words, we use a text area for editing.
  2332. var $canSeek = false; /// indicates that seek is supported
  2333. var $sql; /// sql text
  2334. var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
  2335. var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
  2336. var $emptyDate = '&nbsp;'; /// what to display when $time==0
  2337. var $debug = false;
  2338. var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
  2339. var $bind = false; /// used by Fields() to hold array - should be private?
  2340. var $fetchMode; /// default fetch mode
  2341. var $connection = false; /// the parent connection
  2342. /*
  2343. * private variables
  2344. */
  2345. var $_numOfRows = -1; /** number of rows, or -1 */
  2346. var $_numOfFields = -1; /** number of fields in recordset */
  2347. var $_queryID = -1; /** This variable keeps the result link identifier. */
  2348. var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
  2349. var $_closed = false; /** has recordset been closed */
  2350. var $_inited = false; /** Init() should only be called once */
  2351. var $_obj; /** Used by FetchObj */
  2352. var $_names; /** Used by FetchObj */
  2353. var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */
  2354. var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */
  2355. var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */
  2356. var $_lastPageNo = -1;
  2357. var $_maxRecordCount = 0;
  2358. var $datetime = false;
  2359. /**
  2360. * Constructor
  2361. *
  2362. * @param queryID this is the queryID returned by ADOConnection->_query()
  2363. *
  2364. */
  2365. function ADORecordSet($queryID)
  2366. {
  2367. $this->_queryID = $queryID;
  2368. }
  2369. function Init()
  2370. {
  2371. if ($this->_inited) return;
  2372. $this->_inited = true;
  2373. if ($this->_queryID) @$this->_initrs();
  2374. else {
  2375. $this->_numOfRows = 0;
  2376. $this->_numOfFields = 0;
  2377. }
  2378. if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
  2379. $this->_currentRow = 0;
  2380. if ($this->EOF = ($this->_fetch() === false)) {
  2381. $this->_numOfRows = 0; // _numOfRows could be -1
  2382. }
  2383. } else {
  2384. $this->EOF = true;
  2385. }
  2386. }
  2387. /**
  2388. * Generate a SELECT tag string from a recordset, and return the string.
  2389. * If the recordset has 2 cols, we treat the 1st col as the containing
  2390. * the text to display to the user, and 2nd col as the return value. Default
  2391. * strings are compared with the FIRST column.
  2392. *
  2393. * @param name name of SELECT tag
  2394. * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
  2395. * @param [blank1stItem] true to leave the 1st item in list empty
  2396. * @param [multiple] true for listbox, false for popup
  2397. * @param [size] #rows to show for listbox. not used by popup
  2398. * @param [selectAttr] additional attributes to defined for SELECT tag.
  2399. * useful for holding javascript onChange='...' handlers.
  2400. & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
  2401. * column 0 (1st col) if this is true. This is not documented.
  2402. *
  2403. * @return HTML
  2404. *
  2405. * changes by glen.davies@cce.ac.nz to support multiple hilited items
  2406. */
  2407. function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
  2408. $size=0, $selectAttr='',$compareFields0=true)
  2409. {
  2410. global $ADODB_INCLUDED_LIB;
  2411. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  2412. return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
  2413. $size, $selectAttr,$compareFields0);
  2414. }
  2415. /**
  2416. * Generate a SELECT tag string from a recordset, and return the string.
  2417. * If the recordset has 2 cols, we treat the 1st col as the containing
  2418. * the text to display to the user, and 2nd col as the return value. Default
  2419. * strings are compared with the SECOND column.
  2420. *
  2421. */
  2422. function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
  2423. {
  2424. return $this->GetMenu($name,$defstr,$blank1stItem,$multiple,
  2425. $size, $selectAttr,false);
  2426. }
  2427. /*
  2428. Grouped Menu
  2429. */
  2430. function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false,
  2431. $size=0, $selectAttr='')
  2432. {
  2433. global $ADODB_INCLUDED_LIB;
  2434. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  2435. return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple,
  2436. $size, $selectAttr,false);
  2437. }
  2438. /**
  2439. * return recordset as a 2-dimensional array.
  2440. *
  2441. * @param [nRows] is the number of rows to return. -1 means every row.
  2442. *
  2443. * @return an array indexed by the rows (0-based) from the recordset
  2444. */
  2445. function &GetArray($nRows = -1)
  2446. {
  2447. global $ADODB_EXTENSION; if ($ADODB_EXTENSION) {
  2448. $results = adodb_getall($this,$nRows);
  2449. return $results;
  2450. }
  2451. $results = array();
  2452. $cnt = 0;
  2453. while (!$this->EOF && $nRows != $cnt) {
  2454. $results[] = $this->fields;
  2455. $this->MoveNext();
  2456. $cnt++;
  2457. }
  2458. return $results;
  2459. }
  2460. function &GetAll($nRows = -1)
  2461. {
  2462. $arr = $this->GetArray($nRows);
  2463. return $arr;
  2464. }
  2465. /*
  2466. * Some databases allow multiple recordsets to be returned. This function
  2467. * will return true if there is a next recordset, or false if no more.
  2468. */
  2469. function NextRecordSet()
  2470. {
  2471. return false;
  2472. }
  2473. /**
  2474. * return recordset as a 2-dimensional array.
  2475. * Helper function for ADOConnection->SelectLimit()
  2476. *
  2477. * @param offset is the row to start calculations from (1-based)
  2478. * @param [nrows] is the number of rows to return
  2479. *
  2480. * @return an array indexed by the rows (0-based) from the recordset
  2481. */
  2482. function &GetArrayLimit($nrows,$offset=-1)
  2483. {
  2484. if ($offset <= 0) {
  2485. $arr = $this->GetArray($nrows);
  2486. return $arr;
  2487. }
  2488. $this->Move($offset);
  2489. $results = array();
  2490. $cnt = 0;
  2491. while (!$this->EOF && $nrows != $cnt) {
  2492. $results[$cnt++] = $this->fields;
  2493. $this->MoveNext();
  2494. }
  2495. return $results;
  2496. }
  2497. /**
  2498. * Synonym for GetArray() for compatibility with ADO.
  2499. *
  2500. * @param [nRows] is the number of rows to return. -1 means every row.
  2501. *
  2502. * @return an array indexed by the rows (0-based) from the recordset
  2503. */
  2504. function &GetRows($nRows = -1)
  2505. {
  2506. $arr = $this->GetArray($nRows);
  2507. return $arr;
  2508. }
  2509. /**
  2510. * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
  2511. * The first column is treated as the key and is not included in the array.
  2512. * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
  2513. * $force_array == true.
  2514. *
  2515. * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
  2516. * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
  2517. * read the source.
  2518. *
  2519. * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
  2520. * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
  2521. *
  2522. * @return an associative array indexed by the first column of the array,
  2523. * or false if the data has less than 2 cols.
  2524. */
  2525. function &GetAssoc($force_array = false, $first2cols = false)
  2526. {
  2527. global $ADODB_EXTENSION;
  2528. $cols = $this->_numOfFields;
  2529. if ($cols < 2) {
  2530. $false = false;
  2531. return $false;
  2532. }
  2533. $numIndex = isset($this->fields[0]);
  2534. $results = array();
  2535. if (!$first2cols && ($cols > 2 || $force_array)) {
  2536. if ($ADODB_EXTENSION) {
  2537. if ($numIndex) {
  2538. while (!$this->EOF) {
  2539. // $results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2540. // Fix for array_slice re-numbering numeric associative keys in PHP5
  2541. $keys = array_slice(array_keys($this->fields), 1);
  2542. $sliced_array = array();
  2543. foreach($keys as $key) {
  2544. $sliced_array[$key] = $this->fields[$key];
  2545. }
  2546. $results[trim(reset($this->fields))] = $sliced_array;
  2547. adodb_movenext($this);
  2548. }
  2549. } else {
  2550. while (!$this->EOF) {
  2551. $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
  2552. adodb_movenext($this);
  2553. }
  2554. }
  2555. } else {
  2556. if ($numIndex) {
  2557. while (!$this->EOF) {
  2558. //$results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2559. // Fix for array_slice re-numbering numeric associative keys in PHP5
  2560. $keys = array_slice(array_keys($this->fields), 1);
  2561. $sliced_array = array();
  2562. foreach($keys as $key) {
  2563. $sliced_array[$key] = $this->fields[$key];
  2564. }
  2565. $results[trim(reset($this->fields))] = $sliced_array;
  2566. $this->MoveNext();
  2567. }
  2568. } else {
  2569. while (!$this->EOF) {
  2570. $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
  2571. $this->MoveNext();
  2572. }
  2573. }
  2574. }
  2575. } else {
  2576. if ($ADODB_EXTENSION) {
  2577. // return scalar values
  2578. if ($numIndex) {
  2579. while (!$this->EOF) {
  2580. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2581. $results[trim(($this->fields[0]))] = $this->fields[1];
  2582. adodb_movenext($this);
  2583. }
  2584. } else {
  2585. while (!$this->EOF) {
  2586. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2587. $v1 = trim(reset($this->fields));
  2588. $v2 = ''.next($this->fields);
  2589. $results[$v1] = $v2;
  2590. adodb_movenext($this);
  2591. }
  2592. }
  2593. } else {
  2594. if ($numIndex) {
  2595. while (!$this->EOF) {
  2596. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2597. $results[trim(($this->fields[0]))] = $this->fields[1];
  2598. $this->MoveNext();
  2599. }
  2600. } else {
  2601. while (!$this->EOF) {
  2602. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2603. $v1 = trim(reset($this->fields));
  2604. $v2 = ''.next($this->fields);
  2605. $results[$v1] = $v2;
  2606. $this->MoveNext();
  2607. }
  2608. }
  2609. }
  2610. }
  2611. $ref = $results; # workaround accelerator incompat with PHP 4.4 :(
  2612. return $ref;
  2613. }
  2614. /**
  2615. *
  2616. * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
  2617. * @param fmt is the format to apply to it, using date()
  2618. *
  2619. * @return a timestamp formated as user desires
  2620. */
  2621. function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
  2622. {
  2623. if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
  2624. $tt = $this->UnixTimeStamp($v);
  2625. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2626. if (($tt === false || $tt == -1) && $v != false) return $v;
  2627. if ($tt === 0) return $this->emptyTimeStamp;
  2628. return adodb_date($fmt,$tt);
  2629. }
  2630. /**
  2631. * @param v is the character date in YYYY-MM-DD format, returned by database
  2632. * @param fmt is the format to apply to it, using date()
  2633. *
  2634. * @return a date formated as user desires
  2635. */
  2636. function UserDate($v,$fmt='Y-m-d')
  2637. {
  2638. $tt = $this->UnixDate($v);
  2639. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2640. if (($tt === false || $tt == -1) && $v != false) return $v;
  2641. else if ($tt == 0) return $this->emptyDate;
  2642. else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  2643. }
  2644. return adodb_date($fmt,$tt);
  2645. }
  2646. /**
  2647. * @param $v is a date string in YYYY-MM-DD format
  2648. *
  2649. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2650. */
  2651. function UnixDate($v)
  2652. {
  2653. return ADOConnection::UnixDate($v);
  2654. }
  2655. /**
  2656. * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  2657. *
  2658. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2659. */
  2660. function UnixTimeStamp($v)
  2661. {
  2662. return ADOConnection::UnixTimeStamp($v);
  2663. }
  2664. /**
  2665. * PEAR DB Compat - do not use internally
  2666. */
  2667. function Free()
  2668. {
  2669. return $this->Close();
  2670. }
  2671. /**
  2672. * PEAR DB compat, number of rows
  2673. */
  2674. function NumRows()
  2675. {
  2676. return $this->_numOfRows;
  2677. }
  2678. /**
  2679. * PEAR DB compat, number of cols
  2680. */
  2681. function NumCols()
  2682. {
  2683. return $this->_numOfFields;
  2684. }
  2685. /**
  2686. * Fetch a row, returning false if no more rows.
  2687. * This is PEAR DB compat mode.
  2688. *
  2689. * @return false or array containing the current record
  2690. */
  2691. function FetchRow()
  2692. {
  2693. if ($this->EOF) {
  2694. $false = false;
  2695. return $false;
  2696. }
  2697. $arr = $this->fields;
  2698. $this->_currentRow++;
  2699. if (!$this->_fetch()) $this->EOF = true;
  2700. return $arr;
  2701. }
  2702. /**
  2703. * Fetch a row, returning PEAR_Error if no more rows.
  2704. * This is PEAR DB compat mode.
  2705. *
  2706. * @return DB_OK or error object
  2707. */
  2708. function FetchInto(&$arr)
  2709. {
  2710. if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
  2711. $arr = $this->fields;
  2712. $this->MoveNext();
  2713. return 1; // DB_OK
  2714. }
  2715. /**
  2716. * Move to the first row in the recordset. Many databases do NOT support this.
  2717. *
  2718. * @return true or false
  2719. */
  2720. function MoveFirst()
  2721. {
  2722. if ($this->_currentRow == 0) return true;
  2723. return $this->Move(0);
  2724. }
  2725. /**
  2726. * Move to the last row in the recordset.
  2727. *
  2728. * @return true or false
  2729. */
  2730. function MoveLast()
  2731. {
  2732. if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
  2733. if ($this->EOF) return false;
  2734. while (!$this->EOF) {
  2735. $f = $this->fields;
  2736. $this->MoveNext();
  2737. }
  2738. $this->fields = $f;
  2739. $this->EOF = false;
  2740. return true;
  2741. }
  2742. /**
  2743. * Move to next record in the recordset.
  2744. *
  2745. * @return true if there still rows available, or false if there are no more rows (EOF).
  2746. */
  2747. function MoveNext()
  2748. {
  2749. if (!$this->EOF) {
  2750. $this->_currentRow++;
  2751. if ($this->_fetch()) return true;
  2752. }
  2753. $this->EOF = true;
  2754. /* -- tested error handling when scrolling cursor -- seems useless.
  2755. $conn = $this->connection;
  2756. if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
  2757. $fn = $conn->raiseErrorFn;
  2758. $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
  2759. }
  2760. */
  2761. return false;
  2762. }
  2763. /**
  2764. * Random access to a specific row in the recordset. Some databases do not support
  2765. * access to previous rows in the databases (no scrolling backwards).
  2766. *
  2767. * @param rowNumber is the row to move to (0-based)
  2768. *
  2769. * @return true if there still rows available, or false if there are no more rows (EOF).
  2770. */
  2771. function Move($rowNumber = 0)
  2772. {
  2773. $this->EOF = false;
  2774. if ($rowNumber == $this->_currentRow) return true;
  2775. if ($rowNumber >= $this->_numOfRows)
  2776. if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
  2777. if ($this->canSeek) {
  2778. if ($this->_seek($rowNumber)) {
  2779. $this->_currentRow = $rowNumber;
  2780. if ($this->_fetch()) {
  2781. return true;
  2782. }
  2783. } else {
  2784. $this->EOF = true;
  2785. return false;
  2786. }
  2787. } else {
  2788. if ($rowNumber < $this->_currentRow) return false;
  2789. global $ADODB_EXTENSION;
  2790. if ($ADODB_EXTENSION) {
  2791. while (!$this->EOF && $this->_currentRow < $rowNumber) {
  2792. adodb_movenext($this);
  2793. }
  2794. } else {
  2795. while (! $this->EOF && $this->_currentRow < $rowNumber) {
  2796. $this->_currentRow++;
  2797. if (!$this->_fetch()) $this->EOF = true;
  2798. }
  2799. }
  2800. return !($this->EOF);
  2801. }
  2802. $this->fields = false;
  2803. $this->EOF = true;
  2804. return false;
  2805. }
  2806. /**
  2807. * Get the value of a field in the current row by column name.
  2808. * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
  2809. *
  2810. * @param colname is the field to access
  2811. *
  2812. * @return the value of $colname column
  2813. */
  2814. function Fields($colname)
  2815. {
  2816. return $this->fields[$colname];
  2817. }
  2818. function GetAssocKeys($upper=true)
  2819. {
  2820. $this->bind = array();
  2821. for ($i=0; $i < $this->_numOfFields; $i++) {
  2822. $o = $this->FetchField($i);
  2823. if ($upper === 2) $this->bind[$o->name] = $i;
  2824. else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
  2825. }
  2826. }
  2827. /**
  2828. * Use associative array to get fields array for databases that do not support
  2829. * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it
  2830. *
  2831. * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
  2832. * before you execute your SQL statement, and access $rs->fields['col'] directly.
  2833. *
  2834. * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
  2835. */
  2836. function &GetRowAssoc($upper=1)
  2837. {
  2838. $record = array();
  2839. // if (!$this->fields) return $record;
  2840. if (!$this->bind) {
  2841. $this->GetAssocKeys($upper);
  2842. }
  2843. foreach($this->bind as $k => $v) {
  2844. $record[$k] = $this->fields[$v];
  2845. }
  2846. return $record;
  2847. }
  2848. /**
  2849. * Clean up recordset
  2850. *
  2851. * @return true or false
  2852. */
  2853. function Close()
  2854. {
  2855. // free connection object - this seems to globally free the object
  2856. // and not merely the reference, so don't do this...
  2857. // $this->connection = false;
  2858. if (!$this->_closed) {
  2859. $this->_closed = true;
  2860. return $this->_close();
  2861. } else
  2862. return true;
  2863. }
  2864. /**
  2865. * synonyms RecordCount and RowCount
  2866. *
  2867. * @return the number of rows or -1 if this is not supported
  2868. */
  2869. function RecordCount() {return $this->_numOfRows;}
  2870. /*
  2871. * If we are using PageExecute(), this will return the maximum possible rows
  2872. * that can be returned when paging a recordset.
  2873. */
  2874. function MaxRecordCount()
  2875. {
  2876. return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
  2877. }
  2878. /**
  2879. * synonyms RecordCount and RowCount
  2880. *
  2881. * @return the number of rows or -1 if this is not supported
  2882. */
  2883. function RowCount() {return $this->_numOfRows;}
  2884. /**
  2885. * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
  2886. *
  2887. * @return the number of records from a previous SELECT. All databases support this.
  2888. *
  2889. * But aware possible problems in multiuser environments. For better speed the table
  2890. * must be indexed by the condition. Heavy test this before deploying.
  2891. */
  2892. function PO_RecordCount($table="", $condition="") {
  2893. $lnumrows = $this->_numOfRows;
  2894. // the database doesn't support native recordcount, so we do a workaround
  2895. if ($lnumrows == -1 && $this->connection) {
  2896. IF ($table) {
  2897. if ($condition) $condition = " WHERE " . $condition;
  2898. $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
  2899. if ($resultrows) $lnumrows = reset($resultrows->fields);
  2900. }
  2901. }
  2902. return $lnumrows;
  2903. }
  2904. /**
  2905. * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  2906. */
  2907. function CurrentRow() {return $this->_currentRow;}
  2908. /**
  2909. * synonym for CurrentRow -- for ADO compat
  2910. *
  2911. * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  2912. */
  2913. function AbsolutePosition() {return $this->_currentRow;}
  2914. /**
  2915. * @return the number of columns in the recordset. Some databases will set this to 0
  2916. * if no records are returned, others will return the number of columns in the query.
  2917. */
  2918. function FieldCount() {return $this->_numOfFields;}
  2919. /**
  2920. * Get the ADOFieldObject of a specific column.
  2921. *
  2922. * @param fieldoffset is the column position to access(0-based).
  2923. *
  2924. * @return the ADOFieldObject for that column, or false.
  2925. */
  2926. function &FetchField($fieldoffset)
  2927. {
  2928. // must be defined by child class
  2929. }
  2930. /**
  2931. * Get the ADOFieldObjects of all columns in an array.
  2932. *
  2933. */
  2934. function& FieldTypesArray()
  2935. {
  2936. $arr = array();
  2937. for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
  2938. $arr[] = $this->FetchField($i);
  2939. return $arr;
  2940. }
  2941. /**
  2942. * Return the fields array of the current row as an object for convenience.
  2943. * The default case is lowercase field names.
  2944. *
  2945. * @return the object with the properties set to the fields of the current row
  2946. */
  2947. function &FetchObj()
  2948. {
  2949. $o = $this->FetchObject(false);
  2950. return $o;
  2951. }
  2952. /**
  2953. * Return the fields array of the current row as an object for convenience.
  2954. * The default case is uppercase.
  2955. *
  2956. * @param $isupper to set the object property names to uppercase
  2957. *
  2958. * @return the object with the properties set to the fields of the current row
  2959. */
  2960. function &FetchObject($isupper=true)
  2961. {
  2962. if (empty($this->_obj)) {
  2963. $this->_obj = new ADOFetchObj();
  2964. $this->_names = array();
  2965. for ($i=0; $i <$this->_numOfFields; $i++) {
  2966. $f = $this->FetchField($i);
  2967. $this->_names[] = $f->name;
  2968. }
  2969. }
  2970. $i = 0;
  2971. if (PHP_VERSION >= 5) $o = clone($this->_obj);
  2972. else $o = $this->_obj;
  2973. for ($i=0; $i <$this->_numOfFields; $i++) {
  2974. $name = $this->_names[$i];
  2975. if ($isupper) $n = strtoupper($name);
  2976. else $n = $name;
  2977. $o->$n = $this->Fields($name);
  2978. }
  2979. return $o;
  2980. }
  2981. /**
  2982. * Return the fields array of the current row as an object for convenience.
  2983. * The default is lower-case field names.
  2984. *
  2985. * @return the object with the properties set to the fields of the current row,
  2986. * or false if EOF
  2987. *
  2988. * Fixed bug reported by tim@orotech.net
  2989. */
  2990. function &FetchNextObj()
  2991. {
  2992. $o = $this->FetchNextObject(false);
  2993. return $o;
  2994. }
  2995. /**
  2996. * Return the fields array of the current row as an object for convenience.
  2997. * The default is upper case field names.
  2998. *
  2999. * @param $isupper to set the object property names to uppercase
  3000. *
  3001. * @return the object with the properties set to the fields of the current row,
  3002. * or false if EOF
  3003. *
  3004. * Fixed bug reported by tim@orotech.net
  3005. */
  3006. function &FetchNextObject($isupper=true)
  3007. {
  3008. $o = false;
  3009. if ($this->_numOfRows != 0 && !$this->EOF) {
  3010. $o = $this->FetchObject($isupper);
  3011. $this->_currentRow++;
  3012. if ($this->_fetch()) return $o;
  3013. }
  3014. $this->EOF = true;
  3015. return $o;
  3016. }
  3017. /**
  3018. * Get the metatype of the column. This is used for formatting. This is because
  3019. * many databases use different names for the same type, so we transform the original
  3020. * type to our standardised version which uses 1 character codes:
  3021. *
  3022. * @param t is the type passed in. Normally is ADOFieldObject->type.
  3023. * @param len is the maximum length of that field. This is because we treat character
  3024. * fields bigger than a certain size as a 'B' (blob).
  3025. * @param fieldobj is the field object returned by the database driver. Can hold
  3026. * additional info (eg. primary_key for mysql).
  3027. *
  3028. * @return the general type of the data:
  3029. * C for character < 250 chars
  3030. * X for teXt (>= 250 chars)
  3031. * B for Binary
  3032. * N for numeric or floating point
  3033. * D for date
  3034. * T for timestamp
  3035. * L for logical/Boolean
  3036. * I for integer
  3037. * R for autoincrement counter/integer
  3038. *
  3039. *
  3040. */
  3041. function MetaType($t,$len=-1,$fieldobj=false)
  3042. {
  3043. if (is_object($t)) {
  3044. $fieldobj = $t;
  3045. $t = $fieldobj->type;
  3046. $len = $fieldobj->max_length;
  3047. }
  3048. // changed in 2.32 to hashing instead of switch stmt for speed...
  3049. static $typeMap = array(
  3050. 'VARCHAR' => 'C',
  3051. 'VARCHAR2' => 'C',
  3052. 'CHAR' => 'C',
  3053. 'C' => 'C',
  3054. 'STRING' => 'C',
  3055. 'NCHAR' => 'C',
  3056. 'NVARCHAR' => 'C',
  3057. 'VARYING' => 'C',
  3058. 'BPCHAR' => 'C',
  3059. 'CHARACTER' => 'C',
  3060. 'INTERVAL' => 'C', # Postgres
  3061. 'MACADDR' => 'C', # postgres
  3062. ##
  3063. 'LONGCHAR' => 'X',
  3064. 'TEXT' => 'X',
  3065. 'NTEXT' => 'X',
  3066. 'M' => 'X',
  3067. 'X' => 'X',
  3068. 'CLOB' => 'X',
  3069. 'NCLOB' => 'X',
  3070. 'LVARCHAR' => 'X',
  3071. ##
  3072. 'BLOB' => 'B',
  3073. 'IMAGE' => 'B',
  3074. 'BINARY' => 'B',
  3075. 'VARBINARY' => 'B',
  3076. 'LONGBINARY' => 'B',
  3077. 'B' => 'B',
  3078. ##
  3079. 'YEAR' => 'D', // mysql
  3080. 'DATE' => 'D',
  3081. 'D' => 'D',
  3082. ##
  3083. 'TIME' => 'T',
  3084. 'TIMESTAMP' => 'T',
  3085. 'DATETIME' => 'T',
  3086. 'TIMESTAMPTZ' => 'T',
  3087. 'T' => 'T',
  3088. 'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
  3089. ##
  3090. 'BOOL' => 'L',
  3091. 'BOOLEAN' => 'L',
  3092. 'BIT' => 'L',
  3093. 'L' => 'L',
  3094. ##
  3095. 'COUNTER' => 'R',
  3096. 'R' => 'R',
  3097. 'SERIAL' => 'R', // ifx
  3098. 'INT IDENTITY' => 'R',
  3099. ##
  3100. 'INT' => 'I',
  3101. 'INT2' => 'I',
  3102. 'INT4' => 'I',
  3103. 'INT8' => 'I',
  3104. 'INTEGER' => 'I',
  3105. 'INTEGER UNSIGNED' => 'I',
  3106. 'SHORT' => 'I',
  3107. 'TINYINT' => 'I',
  3108. 'SMALLINT' => 'I',
  3109. 'I' => 'I',
  3110. ##
  3111. 'LONG' => 'N', // interbase is numeric, oci8 is blob
  3112. 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
  3113. 'DECIMAL' => 'N',
  3114. 'DEC' => 'N',
  3115. 'REAL' => 'N',
  3116. 'DOUBLE' => 'N',
  3117. 'DOUBLE PRECISION' => 'N',
  3118. 'SMALLFLOAT' => 'N',
  3119. 'FLOAT' => 'N',
  3120. 'NUMBER' => 'N',
  3121. 'NUM' => 'N',
  3122. 'NUMERIC' => 'N',
  3123. 'MONEY' => 'N',
  3124. ## informix 9.2
  3125. 'SQLINT' => 'I',
  3126. 'SQLSERIAL' => 'I',
  3127. 'SQLSMINT' => 'I',
  3128. 'SQLSMFLOAT' => 'N',
  3129. 'SQLFLOAT' => 'N',
  3130. 'SQLMONEY' => 'N',
  3131. 'SQLDECIMAL' => 'N',
  3132. 'SQLDATE' => 'D',
  3133. 'SQLVCHAR' => 'C',
  3134. 'SQLCHAR' => 'C',
  3135. 'SQLDTIME' => 'T',
  3136. 'SQLINTERVAL' => 'N',
  3137. 'SQLBYTES' => 'B',
  3138. 'SQLTEXT' => 'X',
  3139. ## informix 10
  3140. "SQLINT8" => 'I8',
  3141. "SQLSERIAL8" => 'I8',
  3142. "SQLNCHAR" => 'C',
  3143. "SQLNVCHAR" => 'C',
  3144. "SQLLVARCHAR" => 'X',
  3145. "SQLBOOL" => 'L'
  3146. );
  3147. $tmap = false;
  3148. $t = strtoupper($t);
  3149. $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
  3150. switch ($tmap) {
  3151. case 'C':
  3152. // is the char field is too long, return as text field...
  3153. if ($this->blobSize >= 0) {
  3154. if ($len > $this->blobSize) return 'X';
  3155. } else if ($len > 250) {
  3156. return 'X';
  3157. }
  3158. return 'C';
  3159. case 'I':
  3160. if (!empty($fieldobj->primary_key)) return 'R';
  3161. return 'I';
  3162. case false:
  3163. return 'N';
  3164. case 'B':
  3165. if (isset($fieldobj->binary))
  3166. return ($fieldobj->binary) ? 'B' : 'X';
  3167. return 'B';
  3168. case 'D':
  3169. if (!empty($this->connection) && !empty($this->connection->datetime)) return 'T';
  3170. return 'D';
  3171. default:
  3172. if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
  3173. return $tmap;
  3174. }
  3175. }
  3176. function _close() {}
  3177. /**
  3178. * set/returns the current recordset page when paginating
  3179. */
  3180. function AbsolutePage($page=-1)
  3181. {
  3182. if ($page != -1) $this->_currentPage = $page;
  3183. return $this->_currentPage;
  3184. }
  3185. /**
  3186. * set/returns the status of the atFirstPage flag when paginating
  3187. */
  3188. function AtFirstPage($status=false)
  3189. {
  3190. if ($status != false) $this->_atFirstPage = $status;
  3191. return $this->_atFirstPage;
  3192. }
  3193. function LastPageNo($page = false)
  3194. {
  3195. if ($page != false) $this->_lastPageNo = $page;
  3196. return $this->_lastPageNo;
  3197. }
  3198. /**
  3199. * set/returns the status of the atLastPage flag when paginating
  3200. */
  3201. function AtLastPage($status=false)
  3202. {
  3203. if ($status != false) $this->_atLastPage = $status;
  3204. return $this->_atLastPage;
  3205. }
  3206. } // end class ADORecordSet
  3207. //==============================================================================================
  3208. // CLASS ADORecordSet_array
  3209. //==============================================================================================
  3210. /**
  3211. * This class encapsulates the concept of a recordset created in memory
  3212. * as an array. This is useful for the creation of cached recordsets.
  3213. *
  3214. * Note that the constructor is different from the standard ADORecordSet
  3215. */
  3216. class ADORecordSet_array extends ADORecordSet
  3217. {
  3218. var $databaseType = 'array';
  3219. var $_array; // holds the 2-dimensional data array
  3220. var $_types; // the array of types of each column (C B I L M)
  3221. var $_colnames; // names of each column in array
  3222. var $_skiprow1; // skip 1st row because it holds column names
  3223. var $_fieldobjects; // holds array of field objects
  3224. var $canSeek = true;
  3225. var $affectedrows = false;
  3226. var $insertid = false;
  3227. var $sql = '';
  3228. var $compat = false;
  3229. /**
  3230. * Constructor
  3231. *
  3232. */
  3233. function ADORecordSet_array($fakeid=1)
  3234. {
  3235. global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
  3236. // fetch() on EOF does not delete $this->fields
  3237. $this->compat = !empty($ADODB_COMPAT_FETCH);
  3238. $this->ADORecordSet($fakeid); // fake queryID
  3239. $this->fetchMode = $ADODB_FETCH_MODE;
  3240. }
  3241. function _transpose()
  3242. {
  3243. global $ADODB_INCLUDED_LIB;
  3244. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  3245. $hdr = true;
  3246. adodb_transpose($this->_array, $newarr, $hdr);
  3247. //adodb_pr($newarr);
  3248. $this->_skiprow1 = false;
  3249. $this->_array = $newarr;
  3250. $this->_colnames = $hdr;
  3251. adodb_probetypes($newarr,$this->_types);
  3252. $this->_fieldobjects = array();
  3253. foreach($hdr as $k => $name) {
  3254. $f = new ADOFieldObject();
  3255. $f->name = $name;
  3256. $f->type = $this->_types[$k];
  3257. $f->max_length = -1;
  3258. $this->_fieldobjects[] = $f;
  3259. }
  3260. $this->fields = reset($this->_array);
  3261. $this->_initrs();
  3262. }
  3263. /**
  3264. * Setup the array.
  3265. *
  3266. * @param array is a 2-dimensional array holding the data.
  3267. * The first row should hold the column names
  3268. * unless paramter $colnames is used.
  3269. * @param typearr holds an array of types. These are the same types
  3270. * used in MetaTypes (C,B,L,I,N).
  3271. * @param [colnames] array of column names. If set, then the first row of
  3272. * $array should not hold the column names.
  3273. */
  3274. function InitArray($array,$typearr,$colnames=false)
  3275. {
  3276. $this->_array = $array;
  3277. $this->_types = $typearr;
  3278. if ($colnames) {
  3279. $this->_skiprow1 = false;
  3280. $this->_colnames = $colnames;
  3281. } else {
  3282. $this->_skiprow1 = true;
  3283. $this->_colnames = $array[0];
  3284. }
  3285. $this->Init();
  3286. }
  3287. /**
  3288. * Setup the Array and datatype file objects
  3289. *
  3290. * @param array is a 2-dimensional array holding the data.
  3291. * The first row should hold the column names
  3292. * unless paramter $colnames is used.
  3293. * @param fieldarr holds an array of ADOFieldObject's.
  3294. */
  3295. function InitArrayFields(&$array,&$fieldarr)
  3296. {
  3297. $this->_array = $array;
  3298. $this->_skiprow1= false;
  3299. if ($fieldarr) {
  3300. $this->_fieldobjects = $fieldarr;
  3301. }
  3302. $this->Init();
  3303. }
  3304. function &GetArray($nRows=-1)
  3305. {
  3306. if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
  3307. return $this->_array;
  3308. } else {
  3309. $arr = ADORecordSet::GetArray($nRows);
  3310. return $arr;
  3311. }
  3312. }
  3313. function _initrs()
  3314. {
  3315. $this->_numOfRows = sizeof($this->_array);
  3316. if ($this->_skiprow1) $this->_numOfRows -= 1;
  3317. $this->_numOfFields =(isset($this->_fieldobjects)) ?
  3318. sizeof($this->_fieldobjects):sizeof($this->_types);
  3319. }
  3320. /* Use associative array to get fields array */
  3321. function Fields($colname)
  3322. {
  3323. $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode;
  3324. if ($mode & ADODB_FETCH_ASSOC) {
  3325. if (!isset($this->fields[$colname])) $colname = strtolower($colname);
  3326. return $this->fields[$colname];
  3327. }
  3328. if (!$this->bind) {
  3329. $this->bind = array();
  3330. for ($i=0; $i < $this->_numOfFields; $i++) {
  3331. $o = $this->FetchField($i);
  3332. $this->bind[strtoupper($o->name)] = $i;
  3333. }
  3334. }
  3335. return $this->fields[$this->bind[strtoupper($colname)]];
  3336. }
  3337. function &FetchField($fieldOffset = -1)
  3338. {
  3339. if (isset($this->_fieldobjects)) {
  3340. return $this->_fieldobjects[$fieldOffset];
  3341. }
  3342. $o = new ADOFieldObject();
  3343. $o->name = $this->_colnames[$fieldOffset];
  3344. $o->type = $this->_types[$fieldOffset];
  3345. $o->max_length = -1; // length not known
  3346. return $o;
  3347. }
  3348. function _seek($row)
  3349. {
  3350. if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
  3351. $this->_currentRow = $row;
  3352. if ($this->_skiprow1) $row += 1;
  3353. $this->fields = $this->_array[$row];
  3354. return true;
  3355. }
  3356. return false;
  3357. }
  3358. function MoveNext()
  3359. {
  3360. if (!$this->EOF) {
  3361. $this->_currentRow++;
  3362. $pos = $this->_currentRow;
  3363. if ($this->_numOfRows <= $pos) {
  3364. if (!$this->compat) $this->fields = false;
  3365. } else {
  3366. if ($this->_skiprow1) $pos += 1;
  3367. $this->fields = $this->_array[$pos];
  3368. return true;
  3369. }
  3370. $this->EOF = true;
  3371. }
  3372. return false;
  3373. }
  3374. function _fetch()
  3375. {
  3376. $pos = $this->_currentRow;
  3377. if ($this->_numOfRows <= $pos) {
  3378. if (!$this->compat) $this->fields = false;
  3379. return false;
  3380. }
  3381. if ($this->_skiprow1) $pos += 1;
  3382. $this->fields = $this->_array[$pos];
  3383. return true;
  3384. }
  3385. function _close()
  3386. {
  3387. return true;
  3388. }
  3389. } // ADORecordSet_array
  3390. //==============================================================================================
  3391. // HELPER FUNCTIONS
  3392. //==============================================================================================
  3393. /**
  3394. * Synonym for ADOLoadCode. Private function. Do not use.
  3395. *
  3396. * @deprecated
  3397. */
  3398. function ADOLoadDB($dbType)
  3399. {
  3400. return ADOLoadCode($dbType);
  3401. }
  3402. /**
  3403. * Load the code for a specific database driver. Private function. Do not use.
  3404. */
  3405. function ADOLoadCode($dbType)
  3406. {
  3407. global $ADODB_LASTDB;
  3408. if (!$dbType) return false;
  3409. $db = strtolower($dbType);
  3410. switch ($db) {
  3411. case 'ado':
  3412. if (PHP_VERSION >= 5) $db = 'ado5';
  3413. $class = 'ado';
  3414. break;
  3415. case 'ifx':
  3416. case 'maxsql': $class = $db = 'mysqlt'; break;
  3417. case 'postgres':
  3418. case 'postgres8':
  3419. case 'pgsql': $class = $db = 'postgres7'; break;
  3420. default:
  3421. $class = $db; break;
  3422. }
  3423. $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
  3424. @include_once($file);
  3425. $ADODB_LASTDB = $class;
  3426. if (class_exists("ADODB_" . $class)) return $class;
  3427. //ADOConnection::outp(adodb_pr(get_declared_classes(),true));
  3428. if (!file_exists($file)) ADOConnection::outp("Missing file: $file");
  3429. else ADOConnection::outp("Syntax error in file: $file");
  3430. return false;
  3431. }
  3432. /**
  3433. * synonym for ADONewConnection for people like me who cannot remember the correct name
  3434. */
  3435. function &NewADOConnection($db='')
  3436. {
  3437. $tmp = ADONewConnection($db);
  3438. return $tmp;
  3439. }
  3440. /**
  3441. * Instantiate a new Connection class for a specific database driver.
  3442. *
  3443. * @param [db] is the database Connection object to create. If undefined,
  3444. * use the last database driver that was loaded by ADOLoadCode().
  3445. *
  3446. * @return the freshly created instance of the Connection class.
  3447. */
  3448. function &ADONewConnection($db='')
  3449. {
  3450. GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
  3451. if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  3452. $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
  3453. $false = false;
  3454. if ($at = strpos($db,'://')) {
  3455. $origdsn = $db;
  3456. if (PHP_VERSION < 5) $dsna = @parse_url($db);
  3457. else {
  3458. $fakedsn = 'fake'.substr($db,$at);
  3459. $dsna = @parse_url($fakedsn);
  3460. $dsna['scheme'] = substr($db,0,$at);
  3461. if (strncmp($db,'pdo',3) == 0) {
  3462. $sch = explode('_',$dsna['scheme']);
  3463. if (sizeof($sch)>1) {
  3464. $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
  3465. $dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host']));
  3466. $dsna['scheme'] = 'pdo';
  3467. }
  3468. }
  3469. }
  3470. if (!$dsna) {
  3471. // special handling of oracle, which might not have host
  3472. $db = str_replace('@/','@adodb-fakehost/',$db);
  3473. $dsna = parse_url($db);
  3474. if (!$dsna) return $false;
  3475. $dsna['host'] = '';
  3476. }
  3477. $db = @$dsna['scheme'];
  3478. if (!$db) return $false;
  3479. $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
  3480. $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : '';
  3481. $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : '';
  3482. $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial /
  3483. if (isset($dsna['query'])) {
  3484. $opt1 = explode('&',$dsna['query']);
  3485. foreach($opt1 as $k => $v) {
  3486. $arr = explode('=',$v);
  3487. $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1;
  3488. }
  3489. } else $opt = array();
  3490. }
  3491. /*
  3492. * phptype: Database backend used in PHP (mysql, odbc etc.)
  3493. * dbsyntax: Database used with regards to SQL syntax etc.
  3494. * protocol: Communication protocol to use (tcp, unix etc.)
  3495. * hostspec: Host specification (hostname[:port])
  3496. * database: Database to use on the DBMS server
  3497. * username: User name for login
  3498. * password: Password for login
  3499. */
  3500. if (!empty($ADODB_NEWCONNECTION)) {
  3501. $obj = $ADODB_NEWCONNECTION($db);
  3502. } else {
  3503. if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
  3504. if (empty($db)) $db = $ADODB_LASTDB;
  3505. if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
  3506. if (!$db) {
  3507. if (isset($origdsn)) $db = $origdsn;
  3508. if ($errorfn) {
  3509. // raise an error
  3510. $ignore = false;
  3511. $errorfn('ADONewConnection', 'ADONewConnection', -998,
  3512. "could not load the database driver for '$db'",
  3513. $db,false,$ignore);
  3514. } else
  3515. ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
  3516. return $false;
  3517. }
  3518. $cls = 'ADODB_'.$db;
  3519. if (!class_exists($cls)) {
  3520. adodb_backtrace();
  3521. return $false;
  3522. }
  3523. $obj = new $cls();
  3524. }
  3525. # constructor should not fail
  3526. if ($obj) {
  3527. if ($errorfn) $obj->raiseErrorFn = $errorfn;
  3528. if (isset($dsna)) {
  3529. if (isset($dsna['port'])) $obj->port = $dsna['port'];
  3530. foreach($opt as $k => $v) {
  3531. switch(strtolower($k)) {
  3532. case 'new':
  3533. $nconnect = true; $persist = true; break;
  3534. case 'persist':
  3535. case 'persistent': $persist = $v; break;
  3536. case 'debug': $obj->debug = (integer) $v; break;
  3537. #ibase
  3538. case 'role': $obj->role = $v; break;
  3539. case 'dialect': $obj->dialect = (integer) $v; break;
  3540. case 'charset': $obj->charset = $v; $obj->charSet=$v; break;
  3541. case 'buffers': $obj->buffers = $v; break;
  3542. case 'fetchmode': $obj->SetFetchMode($v); break;
  3543. #ado
  3544. case 'charpage': $obj->charPage = $v; break;
  3545. #mysql, mysqli
  3546. case 'clientflags': $obj->clientFlags = $v; break;
  3547. #mysql, mysqli, postgres
  3548. case 'port': $obj->port = $v; break;
  3549. #mysqli
  3550. case 'socket': $obj->socket = $v; break;
  3551. #oci8
  3552. case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break;
  3553. }
  3554. }
  3555. if (empty($persist))
  3556. $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3557. else if (empty($nconnect))
  3558. $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3559. else
  3560. $ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3561. if (!$ok) return $false;
  3562. }
  3563. }
  3564. return $obj;
  3565. }
  3566. // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary
  3567. function _adodb_getdriver($provider,$drivername,$perf=false)
  3568. {
  3569. switch ($provider) {
  3570. case 'odbtp': if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6);
  3571. case 'odbc' : if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5);
  3572. case 'ado' : if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4);
  3573. case 'native': break;
  3574. default:
  3575. return $provider;
  3576. }
  3577. switch($drivername) {
  3578. case 'mysqlt':
  3579. case 'mysqli':
  3580. $drivername='mysql';
  3581. break;
  3582. case 'postgres7':
  3583. case 'postgres8':
  3584. $drivername = 'postgres';
  3585. break;
  3586. case 'firebird15': $drivername = 'firebird'; break;
  3587. case 'oracle': $drivername = 'oci8'; break;
  3588. case 'access': if ($perf) $drivername = ''; break;
  3589. case 'db2' : break;
  3590. case 'sapdb' : break;
  3591. default:
  3592. $drivername = 'generic';
  3593. break;
  3594. }
  3595. return $drivername;
  3596. }
  3597. function &NewPerfMonitor(&$conn)
  3598. {
  3599. $false = false;
  3600. $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
  3601. if (!$drivername || $drivername == 'generic') return $false;
  3602. include_once(ADODB_DIR.'/adodb-perf.inc.php');
  3603. @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
  3604. $class = "Perf_$drivername";
  3605. if (!class_exists($class)) return $false;
  3606. $perf = new $class($conn);
  3607. return $perf;
  3608. }
  3609. function &NewDataDictionary(&$conn,$drivername=false)
  3610. {
  3611. $false = false;
  3612. if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
  3613. include_once(ADODB_DIR.'/adodb-lib.inc.php');
  3614. include_once(ADODB_DIR.'/adodb-datadict.inc.php');
  3615. $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
  3616. if (!file_exists($path)) {
  3617. ADOConnection::outp("Dictionary driver '$path' not available");
  3618. return $false;
  3619. }
  3620. include_once($path);
  3621. $class = "ADODB2_$drivername";
  3622. $dict = new $class();
  3623. $dict->dataProvider = $conn->dataProvider;
  3624. $dict->connection = &$conn;
  3625. $dict->upperName = strtoupper($drivername);
  3626. $dict->quote = $conn->nameQuote;
  3627. if (!empty($conn->_connectionID))
  3628. $dict->serverInfo = $conn->ServerInfo();
  3629. return $dict;
  3630. }
  3631. /*
  3632. Perform a print_r, with pre tags for better formatting.
  3633. */
  3634. function adodb_pr($var,$as_string=false)
  3635. {
  3636. if ($as_string) ob_start();
  3637. if (isset($_SERVER['HTTP_USER_AGENT'])) {
  3638. echo " <pre>\n";print_r($var);echo "</pre>\n";
  3639. } else
  3640. print_r($var);
  3641. if ($as_string) {
  3642. $s = ob_get_contents();
  3643. ob_end_clean();
  3644. return $s;
  3645. }
  3646. }
  3647. /*
  3648. Perform a stack-crawl and pretty print it.
  3649. @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
  3650. @param levels Number of levels to display
  3651. */
  3652. function adodb_backtrace($printOrArr=true,$levels=9999)
  3653. {
  3654. global $ADODB_INCLUDED_LIB;
  3655. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  3656. return _adodb_backtrace($printOrArr,$levels);
  3657. }
  3658. }
  3659. ?>