PageRenderTime 81ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

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

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