/05_Desarrollo/lib/adodb/adodb.inc.php

https://bitbucket.org/SerafinAkatsuki/consultorio · PHP · 4258 lines · 2780 code · 486 blank · 992 comment · 549 complexity · a2e3ae768a4ef22887ffdecf17d46a34 MD5 · raw file

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