PageRenderTime 76ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/adodb/adodb.inc.php

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