PageRenderTime 40ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/common/lib/adodb/adodb.inc.php

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