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

/concrete/libraries/3rdparty/adodb/adodb.inc.php

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