PageRenderTime 38ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/05_Desarrollo/lib/adodb/adodb.inc.php

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