PageRenderTime 50ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/adodb/adodb.inc.php

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