PageRenderTime 68ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

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

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