PageRenderTime 47ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/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

Large files files are truncated, but you can click here to view the full file

  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_COU

Large files files are truncated, but you can click here to view the full file