PageRenderTime 49ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/libs/adodb/adodb.inc.php

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