PageRenderTime 58ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/adodb/adodb.inc.php

https://github.com/Fusion/lenses
PHP | 4680 lines | 2917 code | 571 blank | 1192 comment | 648 complexity | 0b196b6d4c7c9e3e4039b32f2f3fdbbf MD5 | raw file
Possible License(s): BSD-3-Clause

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.sourceforge.net
  6. *
  7. * This is the main include file for ADOdb.
  8. * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
  9. *
  10. * The ADOdb files are formatted so that doxygen can be used to generate documentation.
  11. * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
  12. */
  13. /**
  14. \mainpage
  15. @version V5.06 29 Sept 2008 (c) 2000-2008 John Lim (jlim#natsoft.com). All rights reserved.
  16. Released under both BSD license and Lesser GPL library license. You can choose which license
  17. you prefer.
  18. PHP's database access functions are not standardised. This creates a need for a database
  19. class library to hide the differences between the different database API's (encapsulate
  20. the differences) so we can easily switch databases.
  21. We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
  22. Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
  23. ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
  24. other databases via ODBC.
  25. Latest Download at http://adodb.sourceforge.net/
  26. */
  27. if (!defined('_ADODB_LAYER')) {
  28. define('_ADODB_LAYER',1);
  29. //==============================================================================================
  30. // CONSTANT DEFINITIONS
  31. //==============================================================================================
  32. /**
  33. * Set ADODB_DIR to the directory where this file resides...
  34. * This constant was formerly called $ADODB_RootPath
  35. */
  36. if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
  37. //==============================================================================================
  38. // GLOBAL VARIABLES
  39. //==============================================================================================
  40. GLOBAL
  41. $ADODB_vers, // database version
  42. $ADODB_COUNTRECS, // count number of records returned - slows down query
  43. $ADODB_CACHE_DIR, // directory to cache recordsets
  44. $ADODB_CACHE,
  45. $ADODB_CACHE_CLASS,
  46. $ADODB_EXTENSION, // ADODB extension installed
  47. $ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
  48. $ADODB_FETCH_MODE, // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
  49. $ADODB_GETONE_EOF,
  50. $ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.
  51. //==============================================================================================
  52. // GLOBAL SETUP
  53. //==============================================================================================
  54. $ADODB_EXTENSION = defined('ADODB_EXTENSION');
  55. //********************************************************//
  56. /*
  57. Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
  58. Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
  59. 0 = ignore empty fields. All empty fields in array are ignored.
  60. 1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
  61. 2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
  62. 3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values.
  63. */
  64. define('ADODB_FORCE_IGNORE',0);
  65. define('ADODB_FORCE_NULL',1);
  66. define('ADODB_FORCE_EMPTY',2);
  67. define('ADODB_FORCE_VALUE',3);
  68. //********************************************************//
  69. if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
  70. define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
  71. // allow [ ] @ ` " and . in table names
  72. define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
  73. // prefetching used by oracle
  74. if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
  75. /*
  76. Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
  77. This currently works only with mssql, odbc, oci8po and ibase derived drivers.
  78. 0 = assoc lowercase field names. $rs->fields['orderid']
  79. 1 = assoc uppercase field names. $rs->fields['ORDERID']
  80. 2 = use native-case field names. $rs->fields['OrderID']
  81. */
  82. define('ADODB_FETCH_DEFAULT',0);
  83. define('ADODB_FETCH_NUM',1);
  84. define('ADODB_FETCH_ASSOC',2);
  85. define('ADODB_FETCH_BOTH',3);
  86. if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
  87. // PHP's version scheme makes converting to numbers difficult - workaround
  88. $_adodb_ver = (float) PHP_VERSION;
  89. if ($_adodb_ver >= 5.2) {
  90. define('ADODB_PHPVER',0x5200);
  91. } else if ($_adodb_ver >= 5.0) {
  92. define('ADODB_PHPVER',0x5000);
  93. } else
  94. die("PHP5 or later required. You are running ".PHP_VERSION);
  95. }
  96. // CFR: Active Records Definitions
  97. define('ADODB_JOIN_AR', 0x01);
  98. define('ADODB_WORK_AR', 0x02);
  99. define('ADODB_LAZY_AR', 0x03);
  100. //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  101. /**
  102. Accepts $src and $dest arrays, replacing string $data
  103. */
  104. function ADODB_str_replace($src, $dest, $data)
  105. {
  106. if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
  107. $s = reset($src);
  108. $d = reset($dest);
  109. while ($s !== false) {
  110. $data = str_replace($s,$d,$data);
  111. $s = next($src);
  112. $d = next($dest);
  113. }
  114. return $data;
  115. }
  116. function ADODB_Setup()
  117. {
  118. GLOBAL
  119. $ADODB_vers, // database version
  120. $ADODB_COUNTRECS, // count number of records returned - slows down query
  121. $ADODB_CACHE_DIR, // directory to cache recordsets
  122. $ADODB_FETCH_MODE,
  123. $ADODB_CACHE,
  124. $ADODB_CACHE_CLASS,
  125. $ADODB_FORCE_TYPE,
  126. $ADODB_GETONE_EOF,
  127. $ADODB_QUOTE_FIELDNAMES;
  128. $ADODB_CACHE_CLASS = 'ADODB_Cache_File';
  129. $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
  130. $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
  131. $ADODB_GETONE_EOF = null;
  132. if (!isset($ADODB_CACHE_DIR)) {
  133. $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
  134. } else {
  135. // do not accept url based paths, eg. http:/ or ftp:/
  136. if (strpos($ADODB_CACHE_DIR,'://') !== false)
  137. die("Illegal path http:// or ftp://");
  138. }
  139. // Initialize random number generator for randomizing cache flushes
  140. // -- note Since PHP 4.2.0, the seed becomes optional and defaults to a random value if omitted.
  141. srand(((double)microtime())*1000000);
  142. /**
  143. * ADODB version as a string.
  144. */
  145. $ADODB_vers = 'V5.06 29 Sept 2008 (c) 2000-2008 John Lim (jlim#natsoft.com). All rights reserved. Released BSD & LGPL.';
  146. /**
  147. * Determines whether recordset->RecordCount() is used.
  148. * Set to false for highest performance -- RecordCount() will always return -1 then
  149. * for databases that provide "virtual" recordcounts...
  150. */
  151. if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
  152. }
  153. //==============================================================================================
  154. // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
  155. //==============================================================================================
  156. ADODB_Setup();
  157. //==============================================================================================
  158. // CLASS ADOFieldObject
  159. //==============================================================================================
  160. /**
  161. * Helper class for FetchFields -- holds info on a column
  162. */
  163. class ADOFieldObject {
  164. var $name = '';
  165. var $max_length=0;
  166. var $type="";
  167. /*
  168. // additional fields by dannym... (danny_milo@yahoo.com)
  169. var $not_null = false;
  170. // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
  171. // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
  172. var $has_default = false; // this one I have done only in mysql and postgres for now ...
  173. // others to come (dannym)
  174. var $default_value; // default, if any, and supported. Check has_default first.
  175. */
  176. }
  177. // for transaction handling
  178. function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
  179. {
  180. //print "Errorno ($fn errno=$errno m=$errmsg) ";
  181. $thisConnection->_transOK = false;
  182. if ($thisConnection->_oldRaiseFn) {
  183. $fn = $thisConnection->_oldRaiseFn;
  184. $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
  185. }
  186. }
  187. //------------------
  188. // class for caching
  189. class ADODB_Cache_File {
  190. var $createdir = true; // requires creation of temp dirs
  191. function ADODB_Cache_File()
  192. {
  193. global $ADODB_INCLUDED_CSV;
  194. if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  195. }
  196. // write serialised recordset to cache item/file
  197. function writecache($filename, $contents, $debug, $secs2cache)
  198. {
  199. return adodb_write_file($filename, $contents,$debug);
  200. }
  201. // load serialised recordset and unserialise it
  202. function &readcache($filename, &$err, $secs2cache, $rsClass)
  203. {
  204. $rs = csv2rs($filename,$err,$secs2cache,$rsClass);
  205. return $rs;
  206. }
  207. // flush all items in cache
  208. function flushall($debug=false)
  209. {
  210. global $ADODB_CACHE_DIR;
  211. $rez = false;
  212. if (strlen($ADODB_CACHE_DIR) > 1) {
  213. $rez = $this->_dirFlush($ADODB_CACHE_DIR);
  214. if ($debug) DOConnection::outp( "flushall: $dir<br><pre>\n". $rez."</pre>");
  215. }
  216. return $rez;
  217. }
  218. // flush one file in cache
  219. function flushcache($f, $debug=false)
  220. {
  221. if (!@unlink($f)) {
  222. if ($debug) ADOConnection::outp( "flushcache: failed for $f");
  223. }
  224. }
  225. function getdirname($hash)
  226. {
  227. global $ADODB_CACHE_DIR;
  228. if (!isset($this->notSafeMode)) $this->notSafeMode = !ini_get('safe_mode');
  229. return ($this->notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($hash,0,2) : $ADODB_CACHE_DIR;
  230. }
  231. // create temp directories
  232. function createdir($hash, $debug)
  233. {
  234. $dir = $this->getdirname($hash);
  235. if ($this->notSafeMode && !file_exists($dir)) {
  236. $oldu = umask(0);
  237. if (!@mkdir($dir,0771)) if(!is_dir($dir) && $debug) ADOConnection::outp("Cannot create $dir");
  238. umask($oldu);
  239. }
  240. return $dir;
  241. }
  242. /**
  243. * Private function to erase all of the files and subdirectories in a directory.
  244. *
  245. * Just specify the directory, and tell it if you want to delete the directory or just clear it out.
  246. * Note: $kill_top_level is used internally in the function to flush subdirectories.
  247. */
  248. function _dirFlush($dir, $kill_top_level = false)
  249. {
  250. if(!$dh = @opendir($dir)) return;
  251. while (($obj = readdir($dh))) {
  252. if($obj=='.' || $obj=='..') continue;
  253. $f = $dir.'/'.$obj;
  254. if (strpos($obj,'.cache')) @unlink($f);
  255. if (is_dir($f)) $this->_dirFlush($f, true);
  256. }
  257. if ($kill_top_level === true) @rmdir($dir);
  258. return true;
  259. }
  260. }
  261. //==============================================================================================
  262. // CLASS ADOConnection
  263. //==============================================================================================
  264. /**
  265. * Connection object. For connecting to databases, and executing queries.
  266. */
  267. class ADOConnection {
  268. //
  269. // PUBLIC VARS
  270. //
  271. var $dataProvider = 'native';
  272. var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
  273. var $database = ''; /// Name of database to be used.
  274. var $host = ''; /// The hostname of the database server
  275. var $user = ''; /// The username which is used to connect to the database server.
  276. var $password = ''; /// Password for the username. For security, we no longer store it.
  277. var $debug = false; /// if set to true will output sql statements
  278. var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
  279. var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
  280. var $substr = 'substr'; /// substring operator
  281. var $length = 'length'; /// string length ofperator
  282. var $random = 'rand()'; /// random function
  283. var $upperCase = 'upper'; /// uppercase function
  284. var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
  285. var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
  286. var $true = '1'; /// string that represents TRUE for a database
  287. var $false = '0'; /// string that represents FALSE for a database
  288. var $replaceQuote = "\\'"; /// string to use to replace quotes
  289. var $nameQuote = '"'; /// string to use to quote identifiers and names
  290. var $charSet=false; /// character set to use - only for interbase, postgres and oci8
  291. var $metaDatabasesSQL = '';
  292. var $metaTablesSQL = '';
  293. var $uniqueOrderBy = false; /// All order by columns have to be unique
  294. var $emptyDate = '&nbsp;';
  295. var $emptyTimeStamp = '&nbsp;';
  296. var $lastInsID = false;
  297. //--
  298. var $hasInsertID = false; /// supports autoincrement ID?
  299. var $hasAffectedRows = false; /// supports affected rows for update/delete?
  300. var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
  301. var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
  302. var $readOnly = false; /// this is a readonly database - used by phpLens
  303. var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
  304. var $hasGenID = false; /// can generate sequences using GenID();
  305. var $hasTransactions = true; /// has transactions
  306. //--
  307. var $genID = 0; /// sequence id used by GenID();
  308. var $raiseErrorFn = false; /// error function to call
  309. var $isoDates = false; /// accepts dates in ISO format
  310. var $cacheSecs = 3600; /// cache for 1 hour
  311. // memcache
  312. var $memCache = false; /// should we use memCache instead of caching in files
  313. var $memCacheHost; /// memCache host
  314. var $memCachePort = 11211; /// memCache port
  315. var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
  316. var $sysDate = false; /// name of function that returns the current date
  317. var $sysTimeStamp = false; /// name of function that returns the current timestamp
  318. var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
  319. var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
  320. var $numCacheHits = 0;
  321. var $numCacheMisses = 0;
  322. var $pageExecuteCountRows = true;
  323. var $uniqueSort = false; /// indicates that all fields in order by must be unique
  324. var $leftOuter = false; /// operator to use for left outer join in WHERE clause
  325. var $rightOuter = false; /// operator to use for right outer join in WHERE clause
  326. var $ansiOuter = false; /// whether ansi outer join syntax supported
  327. var $autoRollback = false; // autoRollback on PConnect().
  328. var $poorAffectedRows = false; // affectedRows not working or unreliable
  329. var $fnExecute = false;
  330. var $fnCacheExecute = false;
  331. var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
  332. var $rsPrefix = "ADORecordSet_";
  333. var $autoCommit = true; /// do not modify this yourself - actually private
  334. var $transOff = 0; /// temporarily disable transactions
  335. var $transCnt = 0; /// count of nested transactions
  336. var $fetchMode=false;
  337. var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
  338. //
  339. // PRIVATE VARS
  340. //
  341. var $_oldRaiseFn = false;
  342. var $_transOK = null;
  343. var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
  344. var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
  345. /// then returned by the errorMsg() function
  346. var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
  347. var $_queryID = false; /// This variable keeps the last created result link identifier
  348. var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
  349. var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
  350. var $_evalAll = false;
  351. var $_affected = false;
  352. var $_logsql = false;
  353. var $_transmode = ''; // transaction mode
  354. /**
  355. * Constructor
  356. */
  357. function ADOConnection()
  358. {
  359. die('Virtual Class -- cannot instantiate');
  360. }
  361. static function Version()
  362. {
  363. global $ADODB_vers;
  364. return (float) substr($ADODB_vers,1);
  365. }
  366. /**
  367. Get server version info...
  368. @returns An array with 2 elements: $arr['string'] is the description string,
  369. and $arr[version] is the version (also a string).
  370. */
  371. function ServerInfo()
  372. {
  373. return array('description' => '', 'version' => '');
  374. }
  375. function IsConnected()
  376. {
  377. return !empty($this->_connectionID);
  378. }
  379. function _findvers($str)
  380. {
  381. if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
  382. else return '';
  383. }
  384. /**
  385. * All error messages go through this bottleneck function.
  386. * You can define your own handler by defining the function name in ADODB_OUTP.
  387. */
  388. static function outp($msg,$newline=true)
  389. {
  390. global $ADODB_FLUSH,$ADODB_OUTP;
  391. if (defined('ADODB_OUTP')) {
  392. $fn = ADODB_OUTP;
  393. $fn($msg,$newline);
  394. return;
  395. } else if (isset($ADODB_OUTP)) {
  396. $fn = $ADODB_OUTP;
  397. $fn($msg,$newline);
  398. return;
  399. }
  400. if ($newline) $msg .= "<br>\n";
  401. if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
  402. else echo strip_tags($msg);
  403. if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
  404. }
  405. function Time()
  406. {
  407. $rs = $this->_Execute("select $this->sysTimeStamp");
  408. if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
  409. return false;
  410. }
  411. /**
  412. * Connect to database
  413. *
  414. * @param [argHostname] Host to connect to
  415. * @param [argUsername] Userid to login
  416. * @param [argPassword] Associated password
  417. * @param [argDatabaseName] database
  418. * @param [forceNew] force new connection
  419. *
  420. * @return true or false
  421. */
  422. function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
  423. {
  424. if ($argHostname != "") $this->host = $argHostname;
  425. if ($argUsername != "") $this->user = $argUsername;
  426. if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
  427. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  428. $this->_isPersistentConnection = false;
  429. global $ADODB_CACHE;
  430. if (empty($ADODB_CACHE)) $this->_CreateCache();
  431. if ($forceNew) {
  432. if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
  433. } else {
  434. if ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
  435. }
  436. if (isset($rez)) {
  437. $err = $this->ErrorMsg();
  438. if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  439. $ret = false;
  440. } else {
  441. $err = "Missing extension for ".$this->dataProvider;
  442. $ret = 0;
  443. }
  444. if ($fn = $this->raiseErrorFn)
  445. $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  446. $this->_connectionID = false;
  447. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  448. return $ret;
  449. }
  450. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  451. {
  452. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
  453. }
  454. /**
  455. * Always force a new connection to database - currently only works with oracle
  456. *
  457. * @param [argHostname] Host to connect to
  458. * @param [argUsername] Userid to login
  459. * @param [argPassword] Associated password
  460. * @param [argDatabaseName] database
  461. *
  462. * @return true or false
  463. */
  464. function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  465. {
  466. return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
  467. }
  468. /**
  469. * Establish persistent connect to database
  470. *
  471. * @param [argHostname] Host to connect to
  472. * @param [argUsername] Userid to login
  473. * @param [argPassword] Associated password
  474. * @param [argDatabaseName] database
  475. *
  476. * @return return true or false
  477. */
  478. function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  479. {
  480. if (defined('ADODB_NEVER_PERSIST'))
  481. return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
  482. if ($argHostname != "") $this->host = $argHostname;
  483. if ($argUsername != "") $this->user = $argUsername;
  484. if ($argPassword != "") $this->password = $argPassword;
  485. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  486. $this->_isPersistentConnection = true;
  487. global $ADODB_CACHE;
  488. if (empty($ADODB_CACHE)) $this->_CreateCache();
  489. if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
  490. if (isset($rez)) {
  491. $err = $this->ErrorMsg();
  492. if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  493. $ret = false;
  494. } else {
  495. $err = "Missing extension for ".$this->dataProvider;
  496. $ret = 0;
  497. }
  498. if ($fn = $this->raiseErrorFn) {
  499. $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  500. }
  501. $this->_connectionID = false;
  502. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  503. return $ret;
  504. }
  505. function outp_throw($msg,$src='WARN',$sql='')
  506. {
  507. if (defined('ADODB_ERROR_HANDLER') && ADODB_ERROR_HANDLER == 'adodb_throw') {
  508. adodb_throw($this->databaseType,$src,-9999,$msg,$sql,false,$this);
  509. return;
  510. }
  511. ADOConnection::outp($msg);
  512. }
  513. // create cache class. Code is backward compat with old memcache implementation
  514. function _CreateCache()
  515. {
  516. global $ADODB_CACHE, $ADODB_CACHE_CLASS;
  517. if ($this->memCache) {
  518. global $ADODB_INCLUDED_MEMCACHE;
  519. if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
  520. $ADODB_CACHE = new ADODB_Cache_MemCache($this);
  521. } else
  522. $ADODB_CACHE = new $ADODB_CACHE_CLASS($this);
  523. }
  524. // Format date column in sql string given an input format that understands Y M D
  525. function SQLDate($fmt, $col=false)
  526. {
  527. if (!$col) $col = $this->sysDate;
  528. return $col; // child class implement
  529. }
  530. /**
  531. * Should prepare the sql statement and return the stmt resource.
  532. * For databases that do not support this, we return the $sql. To ensure
  533. * compatibility with databases that do not support prepare:
  534. *
  535. * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
  536. * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
  537. * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
  538. *
  539. * @param sql SQL to send to database
  540. *
  541. * @return return FALSE, or the prepared statement, or the original sql if
  542. * if the database does not support prepare.
  543. *
  544. */
  545. function Prepare($sql)
  546. {
  547. return $sql;
  548. }
  549. /**
  550. * Some databases, eg. mssql require a different function for preparing
  551. * stored procedures. So we cannot use Prepare().
  552. *
  553. * Should prepare the stored procedure and return the stmt resource.
  554. * For databases that do not support this, we return the $sql. To ensure
  555. * compatibility with databases that do not support prepare:
  556. *
  557. * @param sql SQL to send to database
  558. *
  559. * @return return FALSE, or the prepared statement, or the original sql if
  560. * if the database does not support prepare.
  561. *
  562. */
  563. function PrepareSP($sql,$param=true)
  564. {
  565. return $this->Prepare($sql,$param);
  566. }
  567. /**
  568. * PEAR DB Compat
  569. */
  570. function Quote($s)
  571. {
  572. return $this->qstr($s,false);
  573. }
  574. /**
  575. Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
  576. */
  577. function QMagic($s)
  578. {
  579. return $this->qstr($s,get_magic_quotes_gpc());
  580. }
  581. function q(&$s)
  582. {
  583. #if (!empty($this->qNull)) if ($s == 'null') return $s;
  584. $s = $this->qstr($s,false);
  585. }
  586. /**
  587. * PEAR DB Compat - do not use internally.
  588. */
  589. function ErrorNative()
  590. {
  591. return $this->ErrorNo();
  592. }
  593. /**
  594. * PEAR DB Compat - do not use internally.
  595. */
  596. function nextId($seq_name)
  597. {
  598. return $this->GenID($seq_name);
  599. }
  600. /**
  601. * Lock a row, will escalate and lock the table if row locking not supported
  602. * will normally free the lock at the end of the transaction
  603. *
  604. * @param $table name of table to lock
  605. * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
  606. */
  607. function RowLock($table,$where)
  608. {
  609. return false;
  610. }
  611. function CommitLock($table)
  612. {
  613. return $this->CommitTrans();
  614. }
  615. function RollbackLock($table)
  616. {
  617. return $this->RollbackTrans();
  618. }
  619. /**
  620. * PEAR DB Compat - do not use internally.
  621. *
  622. * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
  623. * for easy porting :-)
  624. *
  625. * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
  626. * @returns The previous fetch mode
  627. */
  628. function SetFetchMode($mode)
  629. {
  630. $old = $this->fetchMode;
  631. $this->fetchMode = $mode;
  632. if ($old === false) {
  633. global $ADODB_FETCH_MODE;
  634. return $ADODB_FETCH_MODE;
  635. }
  636. return $old;
  637. }
  638. /**
  639. * PEAR DB Compat - do not use internally.
  640. */
  641. function Query($sql, $inputarr=false)
  642. {
  643. $rs = $this->Execute($sql, $inputarr);
  644. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  645. return $rs;
  646. }
  647. /**
  648. * PEAR DB Compat - do not use internally
  649. */
  650. function LimitQuery($sql, $offset, $count, $params=false)
  651. {
  652. $rs = $this->SelectLimit($sql, $count, $offset, $params);
  653. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  654. return $rs;
  655. }
  656. /**
  657. * PEAR DB Compat - do not use internally
  658. */
  659. function Disconnect()
  660. {
  661. return $this->Close();
  662. }
  663. /*
  664. Returns placeholder for parameter, eg.
  665. $DB->Param('a')
  666. will return ':a' for Oracle, and '?' for most other databases...
  667. For databases that require positioned params, eg $1, $2, $3 for postgresql,
  668. pass in Param(false) before setting the first parameter.
  669. */
  670. function Param($name,$type='C')
  671. {
  672. return '?';
  673. }
  674. /*
  675. InParameter and OutParameter are self-documenting versions of Parameter().
  676. */
  677. function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  678. {
  679. return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
  680. }
  681. /*
  682. */
  683. function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  684. {
  685. return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
  686. }
  687. /*
  688. Usage in oracle
  689. $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
  690. $db->Parameter($stmt,$id,'myid');
  691. $db->Parameter($stmt,$group,'group',64);
  692. $db->Execute();
  693. @param $stmt Statement returned by Prepare() or PrepareSP().
  694. @param $var PHP variable to bind to
  695. @param $name Name of stored procedure variable name to bind to.
  696. @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
  697. @param [$maxLen] Holds an maximum length of the variable.
  698. @param [$type] The data type of $var. Legal values depend on driver.
  699. */
  700. function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
  701. {
  702. return false;
  703. }
  704. function IgnoreErrors($saveErrs=false)
  705. {
  706. if (!$saveErrs) {
  707. $saveErrs = array($this->raiseErrorFn,$this->_transOK);
  708. $this->raiseErrorFn = false;
  709. return $saveErrs;
  710. } else {
  711. $this->raiseErrorFn = $saveErrs[0];
  712. $this->_transOK = $saveErrs[1];
  713. }
  714. }
  715. /**
  716. Improved method of initiating a transaction. Used together with CompleteTrans().
  717. Advantages include:
  718. a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
  719. Only the outermost block is treated as a transaction.<br>
  720. b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
  721. c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
  722. are disabled, making it backward compatible.
  723. */
  724. function StartTrans($errfn = 'ADODB_TransMonitor')
  725. {
  726. if ($this->transOff > 0) {
  727. $this->transOff += 1;
  728. return;
  729. }
  730. $this->_oldRaiseFn = $this->raiseErrorFn;
  731. $this->raiseErrorFn = $errfn;
  732. $this->_transOK = true;
  733. if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
  734. $this->BeginTrans();
  735. $this->transOff = 1;
  736. }
  737. /**
  738. Used together with StartTrans() to end a transaction. Monitors connection
  739. for sql errors, and will commit or rollback as appropriate.
  740. @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
  741. and if set to false force rollback even if no SQL error detected.
  742. @returns true on commit, false on rollback.
  743. */
  744. function CompleteTrans($autoComplete = true)
  745. {
  746. if ($this->transOff > 1) {
  747. $this->transOff -= 1;
  748. return true;
  749. }
  750. $this->raiseErrorFn = $this->_oldRaiseFn;
  751. $this->transOff = 0;
  752. if ($this->_transOK && $autoComplete) {
  753. if (!$this->CommitTrans()) {
  754. $this->_transOK = false;
  755. if ($this->debug) ADOConnection::outp("Smart Commit failed");
  756. } else
  757. if ($this->debug) ADOConnection::outp("Smart Commit occurred");
  758. } else {
  759. $this->_transOK = false;
  760. $this->RollbackTrans();
  761. if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
  762. }
  763. return $this->_transOK;
  764. }
  765. /*
  766. At the end of a StartTrans/CompleteTrans block, perform a rollback.
  767. */
  768. function FailTrans()
  769. {
  770. if ($this->debug)
  771. if ($this->transOff == 0) {
  772. ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
  773. } else {
  774. ADOConnection::outp("FailTrans was called");
  775. adodb_backtrace();
  776. }
  777. $this->_transOK = false;
  778. }
  779. /**
  780. Check if transaction has failed, only for Smart Transactions.
  781. */
  782. function HasFailedTrans()
  783. {
  784. if ($this->transOff > 0) return $this->_transOK == false;
  785. return false;
  786. }
  787. /**
  788. * Execute SQL
  789. *
  790. * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
  791. * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
  792. * @return RecordSet or false
  793. */
  794. function Execute($sql,$inputarr=false)
  795. {
  796. if ($this->fnExecute) {
  797. $fn = $this->fnExecute;
  798. $ret = $fn($this,$sql,$inputarr);
  799. if (isset($ret)) return $ret;
  800. }
  801. if ($inputarr) {
  802. if (!is_array($inputarr)) $inputarr = array($inputarr);
  803. $element0 = reset($inputarr);
  804. # is_object check because oci8 descriptors can be passed in
  805. $array_2d = is_array($element0) && !is_object(reset($element0));
  806. //remove extra memory copy of input -mikefedyk
  807. unset($element0);
  808. if (!is_array($sql) && !$this->_bindInputArray) {
  809. $sqlarr = explode('?',$sql);
  810. if (!$array_2d) $inputarr = array($inputarr);
  811. foreach($inputarr as $arr) {
  812. $sql = ''; $i = 0;
  813. //Use each() instead of foreach to reduce memory usage -mikefedyk
  814. while(list(, $v) = each($arr)) {
  815. $sql .= $sqlarr[$i];
  816. // from Ron Baldwin <ron.baldwin#sourceprose.com>
  817. // Only quote string types
  818. $typ = gettype($v);
  819. if ($typ == 'string')
  820. //New memory copy of input created here -mikefedyk
  821. $sql .= $this->qstr($v);
  822. else if ($typ == 'double')
  823. $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
  824. else if ($typ == 'boolean')
  825. $sql .= $v ? $this->true : $this->false;
  826. else if ($typ == 'object') {
  827. if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString());
  828. else $sql .= $this->qstr((string) $v);
  829. } else if ($v === null)
  830. $sql .= 'NULL';
  831. else
  832. $sql .= $v;
  833. $i += 1;
  834. }
  835. if (isset($sqlarr[$i])) {
  836. $sql .= $sqlarr[$i];
  837. if ($i+1 != sizeof($sqlarr)) $this->outp_throw( "Input Array does not match ?: ".htmlspecialchars($sql),'Execute');
  838. } else if ($i != sizeof($sqlarr))
  839. $this->outp_throw( "Input array does not match ?: ".htmlspecialchars($sql),'Execute');
  840. $ret = $this->_Execute($sql);
  841. if (!$ret) return $ret;
  842. }
  843. } else {
  844. if ($array_2d) {
  845. if (is_string($sql))
  846. $stmt = $this->Prepare($sql);
  847. else
  848. $stmt = $sql;
  849. foreach($inputarr as $arr) {
  850. $ret = $this->_Execute($stmt,$arr);
  851. if (!$ret) return $ret;
  852. }
  853. } else {
  854. $ret = $this->_Execute($sql,$inputarr);
  855. }
  856. }
  857. } else {
  858. $ret = $this->_Execute($sql,false);
  859. }
  860. return $ret;
  861. }
  862. function _Execute($sql,$inputarr=false)
  863. {
  864. if ($this->debug) {
  865. global $ADODB_INCLUDED_LIB;
  866. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  867. $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
  868. } else {
  869. $this->_queryID = @$this->_query($sql,$inputarr);
  870. }
  871. /************************
  872. // OK, query executed
  873. *************************/
  874. if ($this->_queryID === false) { // error handling if query fails
  875. if ($this->debug == 99) adodb_backtrace(true,5);
  876. $fn = $this->raiseErrorFn;
  877. if ($fn) {
  878. $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
  879. }
  880. $false = false;
  881. return $false;
  882. }
  883. if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
  884. $rsclass = $this->rsPrefix.'empty';
  885. $rs = (class_exists($rsclass)) ? new $rsclass(): new ADORecordSet_empty();
  886. return $rs;
  887. }
  888. // return real recordset from select statement
  889. $rsclass = $this->rsPrefix.$this->databaseType;
  890. $rs = new $rsclass($this->_queryID,$this->fetchMode);
  891. $rs->connection = $this; // Pablo suggestion
  892. $rs->Init();
  893. if (is_array($sql)) $rs->sql = $sql[0];
  894. else $rs->sql = $sql;
  895. if ($rs->_numOfRows <= 0) {
  896. global $ADODB_COUNTRECS;
  897. if ($ADODB_COUNTRECS) {
  898. if (!$rs->EOF) {
  899. $rs = $this->_rs2rs($rs,-1,-1,!is_array($sql));
  900. $rs->_queryID = $this->_queryID;
  901. } else
  902. $rs->_numOfRows = 0;
  903. }
  904. }
  905. return $rs;
  906. }
  907. function CreateSequence($seqname='adodbseq',$startID=1)
  908. {
  909. if (empty($this->_genSeqSQL)) return false;
  910. return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  911. }
  912. function DropSequence($seqname='adodbseq')
  913. {
  914. if (empty($this->_dropSeqSQL)) return false;
  915. return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
  916. }
  917. /**
  918. * Generates a sequence id and stores it in $this->genID;
  919. * GenID is only available if $this->hasGenID = true;
  920. *
  921. * @param seqname name of sequence to use
  922. * @param startID if sequence does not exist, start at this ID
  923. * @return 0 if not supported, otherwise a sequence id
  924. */
  925. function GenID($seqname='adodbseq',$startID=1)
  926. {
  927. if (!$this->hasGenID) {
  928. return 0; // formerly returns false pre 1.60
  929. }
  930. $getnext = sprintf($this->_genIDSQL,$seqname);
  931. $holdtransOK = $this->_transOK;
  932. $save_handler = $this->raiseErrorFn;
  933. $this->raiseErrorFn = '';
  934. @($rs = $this->Execute($getnext));
  935. $this->raiseErrorFn = $save_handler;
  936. if (!$rs) {
  937. $this->_transOK = $holdtransOK; //if the status was ok before reset
  938. $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  939. $rs = $this->Execute($getnext);
  940. }
  941. if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
  942. else $this->genID = 0; // false
  943. if ($rs) $rs->Close();
  944. return $this->genID;
  945. }
  946. /**
  947. * @param $table string name of the table, not needed by all databases (eg. mysql), default ''
  948. * @param $column string name of the column, not needed by all databases (eg. mysql), default ''
  949. * @return the last inserted ID. Not all databases support this.
  950. */
  951. function Insert_ID($table='',$column='')
  952. {
  953. if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
  954. if ($this->hasInsertID) return $this->_insertid($table,$column);
  955. if ($this->debug) {
  956. ADOConnection::outp( '<p>Insert_ID error</p>');
  957. adodb_backtrace();
  958. }
  959. return false;
  960. }
  961. /**
  962. * Portable Insert ID. Pablo Roca <pabloroca#mvps.org>
  963. *
  964. * @return the last inserted ID. All databases support this. But aware possible
  965. * problems in multiuser environments. Heavy test this before deploying.
  966. */
  967. function PO_Insert_ID($table="", $id="")
  968. {
  969. if ($this->hasInsertID){
  970. return $this->Insert_ID($table,$id);
  971. } else {
  972. return $this->GetOne("SELECT MAX($id) FROM $table");
  973. }
  974. }
  975. /**
  976. * @return # rows affected by UPDATE/DELETE
  977. */
  978. function Affected_Rows()
  979. {
  980. if ($this->hasAffectedRows) {
  981. if ($this->fnExecute === 'adodb_log_sql') {
  982. if ($this->_logsql && $this->_affected !== false) return $this->_affected;
  983. }
  984. $val = $this->_affectedrows();
  985. return ($val < 0) ? false : $val;
  986. }
  987. if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
  988. return false;
  989. }
  990. /**
  991. * @return the last error message
  992. */
  993. function ErrorMsg()
  994. {
  995. if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
  996. else return '';
  997. }
  998. /**
  999. * @return the last error number. Normally 0 means no error.
  1000. */
  1001. function ErrorNo()
  1002. {
  1003. return ($this->_errorMsg) ? -1 : 0;
  1004. }
  1005. function MetaError($err=false)
  1006. {
  1007. include_once(ADODB_DIR."/adodb-error.inc.php");
  1008. if ($err === false) $err = $this->ErrorNo();
  1009. return adodb_error($this->dataProvider,$this->databaseType,$err);
  1010. }
  1011. function MetaErrorMsg($errno)
  1012. {
  1013. include_once(ADODB_DIR."/adodb-error.inc.php");
  1014. return adodb_errormsg($errno);
  1015. }
  1016. /**
  1017. * @returns an array with the primary key columns in it.
  1018. */
  1019. function MetaPrimaryKeys($table, $owner=false)
  1020. {
  1021. // owner not used in base class - see oci8
  1022. $p = array();
  1023. $objs = $this->MetaColumns($table);
  1024. if ($objs) {
  1025. foreach($objs as $v) {
  1026. if (!empty($v->primary_key))
  1027. $p[] = $v->name;
  1028. }
  1029. }
  1030. if (sizeof($p)) return $p;
  1031. if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
  1032. return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
  1033. return false;
  1034. }
  1035. /**
  1036. * @returns assoc array where keys are tables, and values are foreign keys
  1037. */
  1038. function MetaForeignKeys($table, $owner=false, $upper=false)
  1039. {
  1040. return false;
  1041. }
  1042. /**
  1043. * Choose a database to connect to. Many databases do not support this.
  1044. *
  1045. * @param dbName is the name of the database to select
  1046. * @return true or false
  1047. */
  1048. function SelectDB($dbName)
  1049. {return false;}
  1050. /**
  1051. * Will select, getting rows from $offset (1-based), for $nrows.
  1052. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  1053. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  1054. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  1055. * eg.
  1056. * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
  1057. * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
  1058. *
  1059. * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
  1060. * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
  1061. *
  1062. * @param sql
  1063. * @param [offset] is the row to start calculations from (1-based)
  1064. * @param [nrows] is the number of rows to get
  1065. * @param [inputarr] array of bind variables
  1066. * @param [secs2cache] is a private parameter only used by jlim
  1067. * @return the recordset ($rs->databaseType == 'array')
  1068. */
  1069. function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
  1070. {
  1071. if ($this->hasTop && $nrows > 0) {
  1072. // suggested by Reinhard Balling. Access requires top after distinct
  1073. // Informix requires first before distinct - F Riosa
  1074. $ismssql = (strpos($this->databaseType,'mssql') !== false);
  1075. if ($ismssql) $isaccess = false;
  1076. else $isaccess = (strpos($this->databaseType,'access') !== false);
  1077. if ($offset <= 0) {
  1078. // access includes ties in result
  1079. if ($isaccess) {
  1080. $sql = preg_replace(
  1081. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  1082. if ($secs2cache != 0) {
  1083. $ret = $this->CacheExecute($secs2cache, $sql,$inputarr);
  1084. } else {
  1085. $ret = $this->Execute($sql,$inputarr);
  1086. }
  1087. return $ret; // PHP5 fix
  1088. } else if ($ismssql){
  1089. $sql = preg_replace(
  1090. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  1091. } else {
  1092. $sql = preg_replace(
  1093. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  1094. }
  1095. } else {
  1096. $nn = $nrows + $offset;
  1097. if ($isaccess || $ismssql) {
  1098. $sql = preg_replace(
  1099. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  1100. } else {
  1101. $sql = preg_replace(
  1102. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  1103. }
  1104. }
  1105. }
  1106. // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
  1107. // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
  1108. global $ADODB_COUNTRECS;
  1109. $savec = $ADODB_COUNTRECS;
  1110. $ADODB_COUNTRECS = false;
  1111. if ($secs2cache != 0) $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
  1112. else $rs = $this->Execute($sql,$inputarr);
  1113. $ADODB_COUNTRECS = $savec;
  1114. if ($rs && !$rs->EOF) {
  1115. $rs = $this->_rs2rs($rs,$nrows,$offset);
  1116. }
  1117. //print_r($rs);
  1118. return $rs;
  1119. }
  1120. /**
  1121. * Create serializable recordset. Breaks rs link to connection.
  1122. *
  1123. * @param rs the recordset to serialize
  1124. */
  1125. function SerializableRS(&$rs)
  1126. {
  1127. $rs2 = $this->_rs2rs($rs);
  1128. $ignore = false;
  1129. $rs2->connection = $ignore;
  1130. return $rs2;
  1131. }
  1132. /**
  1133. * Convert database recordset to an array recordset
  1134. * input recordset's cursor should be at beginning, and
  1135. * old $rs will be closed.
  1136. *
  1137. * @param rs the recordset to copy
  1138. * @param [nrows] number of rows to retrieve (optional)
  1139. * @param [offset] offset by number of rows (optional)
  1140. * @return the new recordset
  1141. */
  1142. function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
  1143. {
  1144. if (! $rs) {
  1145. $false = false;
  1146. return $false;
  1147. }
  1148. $dbtype = $rs->databaseType;
  1149. if (!$dbtype) {
  1150. $rs = $rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
  1151. return $rs;
  1152. }
  1153. if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
  1154. $rs->MoveFirst();
  1155. $rs = $rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
  1156. return $rs;
  1157. }
  1158. $flds = array();
  1159. for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
  1160. $flds[] = $rs->FetchField($i);
  1161. }
  1162. $arr = $rs->GetArrayLimit($nrows,$offset);
  1163. //print_r($arr);
  1164. if ($close) $rs->Close();
  1165. $arrayClass = $this->arrayClass;
  1166. $rs2 = new $arrayClass();
  1167. $rs2->connection = $this;
  1168. $rs2->sql = $rs->sql;
  1169. $rs2->dataProvider = $this->dataProvider;
  1170. $rs2->InitArrayFields($arr,$flds);
  1171. $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
  1172. return $rs2;
  1173. }
  1174. /*
  1175. * Return all rows. Compat with PEAR DB
  1176. */
  1177. function GetAll($sql, $inputarr=false)
  1178. {
  1179. $arr = $this->GetArray($sql,$inputarr);
  1180. return $arr;
  1181. }
  1182. function GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
  1183. {
  1184. $rs = $this->Execute($sql, $inputarr);
  1185. if (!$rs) {
  1186. $false = false;
  1187. return $false;
  1188. }
  1189. $arr = $rs->GetAssoc($force_array,$first2cols);
  1190. return $arr;
  1191. }
  1192. function CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
  1193. {
  1194. if (!is_numeric($secs2cache)) {
  1195. $first2cols = $force_array;
  1196. $force_array = $inputarr;
  1197. }
  1198. $rs = $this->CacheExecute($secs2cache, $sql, $inputarr);
  1199. if (!$rs) {
  1200. $false = false;
  1201. return $false;
  1202. }
  1203. $arr = $rs->GetAssoc($force_array,$first2cols);
  1204. return $arr;
  1205. }
  1206. /**
  1207. * Return first element of first row of sql statement. Recordset is disposed
  1208. * for you.
  1209. *
  1210. * @param sql SQL statement
  1211. * @param [inputarr] input bind array
  1212. */
  1213. function GetOne($sql,$inputarr=false)
  1214. {
  1215. global $ADODB_COUNTRECS,$ADODB_GETONE_EOF;
  1216. $crecs = $ADODB_COUNTRECS;
  1217. $ADODB_COUNTRECS = false;
  1218. $ret = false;
  1219. $rs = $this->Execute($sql,$inputarr);
  1220. if ($rs) {
  1221. if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
  1222. else $ret = reset($rs->fields);
  1223. $rs->Close();
  1224. }
  1225. $ADODB_COUNTRECS = $crecs;
  1226. return $ret;
  1227. }
  1228. // $where should include 'WHERE fld=value'
  1229. function GetMedian($table, $field,$where = '')
  1230. {
  1231. $total = $this->GetOne("select count(*) from $table $where");
  1232. if (!$total) return false;
  1233. $midrow = (integer) ($total/2);
  1234. $rs = $this->SelectLimit("select $field from $table $where order by 1",1,$midrow);
  1235. if ($rs && !$rs->EOF) return reset($rs->fields);
  1236. return false;
  1237. }
  1238. function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
  1239. {
  1240. global $ADODB_GETONE_EOF;
  1241. $ret = false;
  1242. $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
  1243. if ($rs) {
  1244. if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
  1245. else $ret = reset($rs->fields);
  1246. $rs->Close();
  1247. }
  1248. return $ret;
  1249. }
  1250. function GetCol($sql, $inputarr = false, $trim = false)
  1251. {
  1252. $rs = $this->Execute($sql, $inputarr);
  1253. if ($rs) {
  1254. $rv = array();
  1255. if ($trim) {
  1256. while (!$rs->EOF) {
  1257. $rv[] = trim(reset($rs->fields));
  1258. $rs->MoveNext();
  1259. }
  1260. } else {
  1261. while (!$rs->EOF) {
  1262. $rv[] = reset($rs->fields);
  1263. $rs->MoveNext();
  1264. }
  1265. }
  1266. $rs->Close();
  1267. } else
  1268. $rv = false;
  1269. return $rv;
  1270. }
  1271. function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
  1272. {
  1273. $rs = $this->CacheExecute($secs, $sql, $inputarr);
  1274. if ($rs) {
  1275. $rv = array();
  1276. if ($trim) {
  1277. while (!$rs->EOF) {
  1278. $rv[] = trim(reset($rs->fields));
  1279. $rs->MoveNext();
  1280. }
  1281. } else {
  1282. while (!$rs->EOF) {
  1283. $rv[] = reset($rs->fields);
  1284. $rs->MoveNext();
  1285. }
  1286. }
  1287. $rs->Close();
  1288. } else
  1289. $rv = false;
  1290. return $rv;
  1291. }
  1292. function Transpose(&$rs,$addfieldnames=true)
  1293. {
  1294. $rs2 = $this->_rs2rs($rs);
  1295. $false = false;
  1296. if (!$rs2) return $false;
  1297. $rs2->_transpose($addfieldnames);
  1298. return $rs2;
  1299. }
  1300. /*
  1301. Calculate the offset of a date for a particular database and generate
  1302. appropriate SQL. Useful for calculating future/past dates and storing
  1303. in a database.
  1304. If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
  1305. */
  1306. function OffsetDate($dayFraction,$date=false)
  1307. {
  1308. if (!$date) $date = $this->sysDate;
  1309. return '('.$date.'+'.$dayFraction.')';
  1310. }
  1311. /**
  1312. *
  1313. * @param sql SQL statement
  1314. * @param [inputarr] input bind array
  1315. */
  1316. function GetArray($sql,$inputarr=false)
  1317. {
  1318. global $ADODB_COUNTRECS;
  1319. $savec = $ADODB_COUNTRECS;
  1320. $ADODB_COUNTRECS = false;
  1321. $rs = $this->Execute($sql,$inputarr);
  1322. $ADODB_COUNTRECS = $savec;
  1323. if (!$rs)
  1324. if (defined('ADODB_PEAR')) {
  1325. $cls = ADODB_PEAR_Error();
  1326. return $cls;
  1327. } else {
  1328. $false = false;
  1329. return $false;
  1330. }
  1331. $arr = $rs->GetArray();
  1332. $rs->Close();
  1333. return $arr;
  1334. }
  1335. function CacheGetAll($secs2cache,$sql=false,$inputarr=false)
  1336. {
  1337. $arr = $this->CacheGetArray($secs2cache,$sql,$inputarr);
  1338. return $arr;
  1339. }
  1340. function CacheGetArray($secs2cache,$sql=false,$inputarr=false)
  1341. {
  1342. global $ADODB_COUNTRECS;
  1343. $savec = $ADODB_COUNTRECS;
  1344. $ADODB_COUNTRECS = false;
  1345. $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
  1346. $ADODB_COUNTRECS = $savec;
  1347. if (!$rs)
  1348. if (defined('ADODB_PEAR')) {
  1349. $cls = ADODB_PEAR_Error();
  1350. return $cls;
  1351. } else {
  1352. $false = false;
  1353. return $false;
  1354. }
  1355. $arr = $rs->GetArray();
  1356. $rs->Close();
  1357. return $arr;
  1358. }
  1359. function GetRandRow($sql, $arr= false)
  1360. {
  1361. $rezarr = $this->GetAll($sql, $arr);
  1362. $sz = sizeof($rezarr);
  1363. return $rezarr[abs(rand()) % $sz];
  1364. }
  1365. /**
  1366. * Return one row of sql statement. Recordset is disposed for you.
  1367. *
  1368. * @param sql SQL statement
  1369. * @param [inputarr] input bind array
  1370. */
  1371. function GetRow($sql,$inputarr=false)
  1372. {
  1373. global $ADODB_COUNTRECS;
  1374. $crecs = $ADODB_COUNTRECS;
  1375. $ADODB_COUNTRECS = false;
  1376. $rs = $this->Execute($sql,$inputarr);
  1377. $ADODB_COUNTRECS = $crecs;
  1378. if ($rs) {
  1379. if (!$rs->EOF) $arr = $rs->fields;
  1380. else $arr = array();
  1381. $rs->Close();
  1382. return $arr;
  1383. }
  1384. $false = false;
  1385. return $false;
  1386. }
  1387. function CacheGetRow($secs2cache,$sql=false,$inputarr=false)
  1388. {
  1389. $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
  1390. if ($rs) {
  1391. if (!$rs->EOF) $arr = $rs->fields;
  1392. else $arr = array();
  1393. $rs->Close();
  1394. return $arr;
  1395. }
  1396. $false = false;
  1397. return $false;
  1398. }
  1399. /**
  1400. * Insert or replace a single record. Note: this is not the same as MySQL's replace.
  1401. * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
  1402. * Also note that no table locking is done currently, so it is possible that the
  1403. * record be inserted twice by two programs...
  1404. *
  1405. * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
  1406. *
  1407. * $table table name
  1408. * $fieldArray associative array of data (you must quote strings yourself).
  1409. * $keyCol the primary key field name or if compound key, array of field names
  1410. * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
  1411. * but does not work with dates nor SQL functions.
  1412. * has_autoinc the primary key is an auto-inc field, so skip in insert.
  1413. *
  1414. * Currently blob replace not supported
  1415. *
  1416. * returns 0 = fail, 1 = update, 2 = insert
  1417. */
  1418. function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
  1419. {
  1420. global $ADODB_INCLUDED_LIB;
  1421. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1422. return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
  1423. }
  1424. /**
  1425. * Will select, getting rows from $offset (1-based), for $nrows.
  1426. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  1427. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  1428. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  1429. * eg.
  1430. * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
  1431. * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
  1432. *
  1433. * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP…

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