PageRenderTime 49ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/concrete/libraries/3rdparty/adodb/adodb.inc.php

https://bitbucket.org/seanom/concrete5
PHP | 4399 lines | 2682 code | 558 blank | 1159 comment | 606 complexity | 7cc3fa0631134ecc47f3bc5c5e205c65 MD5 | raw file

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

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