PageRenderTime 84ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/include/phpgacl/adodb/adodb.inc.php

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