PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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 LIMIT or TOP clause already set
  1430. *
  1431. * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
  1432. * @param sql
  1433. * @param [offset] is the row to start calculations from (1-based)
  1434. * @param [nrows] is the number of rows to get
  1435. * @param [inputarr] array of bind variables
  1436. * @return the recordset ($rs->databaseType == 'array')
  1437. */
  1438. function CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
  1439. {
  1440. if (!is_numeric($secs2cache)) {
  1441. if ($sql === false) $sql = -1;
  1442. if ($offset == -1) $offset = false;
  1443. // sql, nrows, offset,inputarr
  1444. $rs = $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
  1445. } else {
  1446. if ($sql === false) $this->outp_throw("Warning: \$sql missing from CacheSelectLimit()",'CacheSelectLimit');
  1447. $rs = $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
  1448. }
  1449. return $rs;
  1450. }
  1451. /**
  1452. * Flush cached recordsets that match a particular $sql statement.
  1453. * If $sql == false, then we purge all files in the cache.
  1454. */
  1455. /**
  1456. * Flush cached recordsets that match a particular $sql statement.
  1457. * If $sql == false, then we purge all files in the cache.
  1458. */
  1459. function CacheFlush($sql=false,$inputarr=false)
  1460. {
  1461. global $ADODB_CACHE_DIR, $ADODB_CACHE;
  1462. if (empty($ADODB_CACHE)) return false;
  1463. if (!$sql) {
  1464. $ADODB_CACHE->flushall($this->debug);
  1465. return;
  1466. }
  1467. $f = $this->_gencachename($sql.serialize($inputarr),false);
  1468. return $ADODB_CACHE->flushcache($f, $this->debug);
  1469. }
  1470. /**
  1471. * Private function to generate filename for caching.
  1472. * Filename is generated based on:
  1473. *
  1474. * - sql statement
  1475. * - database type (oci8, ibase, ifx, etc)
  1476. * - database name
  1477. * - userid
  1478. * - setFetchMode (adodb 4.23)
  1479. *
  1480. * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
  1481. * Assuming that we can have 50,000 files per directory with good performance,
  1482. * then we can scale to 12.8 million unique cached recordsets. Wow!
  1483. */
  1484. function _gencachename($sql,$createdir)
  1485. {
  1486. global $ADODB_CACHE, $ADODB_CACHE_DIR;
  1487. if ($this->fetchMode === false) {
  1488. global $ADODB_FETCH_MODE;
  1489. $mode = $ADODB_FETCH_MODE;
  1490. } else {
  1491. $mode = $this->fetchMode;
  1492. }
  1493. $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
  1494. if (!$ADODB_CACHE->createdir) return $m;
  1495. if (!$createdir) $dir = $ADODB_CACHE->getdirname($m);
  1496. else $dir = $ADODB_CACHE->createdir($m, $this->debug);
  1497. return $dir.'/adodb_'.$m.'.cache';
  1498. }
  1499. /**
  1500. * Execute SQL, caching recordsets.
  1501. *
  1502. * @param [secs2cache] seconds to cache data, set to 0 to force query.
  1503. * This is an optional parameter.
  1504. * @param sql SQL statement to execute
  1505. * @param [inputarr] holds the input data to bind to
  1506. * @return RecordSet or false
  1507. */
  1508. function CacheExecute($secs2cache,$sql=false,$inputarr=false)
  1509. {
  1510. global $ADODB_CACHE;
  1511. if (empty($ADODB_CACHE)) $this->_CreateCache();
  1512. if (!is_numeric($secs2cache)) {
  1513. $inputarr = $sql;
  1514. $sql = $secs2cache;
  1515. $secs2cache = $this->cacheSecs;
  1516. }
  1517. if (is_array($sql)) {
  1518. $sqlparam = $sql;
  1519. $sql = $sql[0];
  1520. } else
  1521. $sqlparam = $sql;
  1522. $md5file = $this->_gencachename($sql.serialize($inputarr),true);
  1523. $err = '';
  1524. if ($secs2cache > 0){
  1525. $rs = $ADODB_CACHE->readcache($md5file,$err,$secs2cache,$this->arrayClass);
  1526. $this->numCacheHits += 1;
  1527. } else {
  1528. $err='Timeout 1';
  1529. $rs = false;
  1530. $this->numCacheMisses += 1;
  1531. }
  1532. if (!$rs) {
  1533. // no cached rs found
  1534. if ($this->debug) {
  1535. if (get_magic_quotes_runtime() && !$this->memCache) {
  1536. ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
  1537. }
  1538. if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
  1539. }
  1540. $rs = $this->Execute($sqlparam,$inputarr);
  1541. if ($rs) {
  1542. $eof = $rs->EOF;
  1543. $rs = $this->_rs2rs($rs); // read entire recordset into memory immediately
  1544. $rs->timeCreated = time(); // used by caching
  1545. $txt = _rs2serialize($rs,false,$sql); // serialize
  1546. $ok = $ADODB_CACHE->writecache($md5file,$txt,$this->debug, $secs2cache);
  1547. if (!$ok) {
  1548. if ($ok === false) {
  1549. $em = 'Cache write error';
  1550. $en = -32000;
  1551. if ($fn = $this->raiseErrorFn) {
  1552. $fn($this->databaseType,'CacheExecute', $en, $em, $md5file,$sql,$this);
  1553. }
  1554. } else {
  1555. $em = 'Cache file locked warning';
  1556. $en = -32001;
  1557. // do not call error handling for just a warning
  1558. }
  1559. if ($this->debug) ADOConnection::outp( " ".$em);
  1560. }
  1561. if ($rs->EOF && !$eof) {
  1562. $rs->MoveFirst();
  1563. //$rs = csv2rs($md5file,$err);
  1564. $rs->connection = $this; // Pablo suggestion
  1565. }
  1566. } else if (!$this->memCache)
  1567. $ADODB_CACHE->flushcache($md5file);
  1568. } else {
  1569. $this->_errorMsg = '';
  1570. $this->_errorCode = 0;
  1571. if ($this->fnCacheExecute) {
  1572. $fn = $this->fnCacheExecute;
  1573. $fn($this, $secs2cache, $sql, $inputarr);
  1574. }
  1575. // ok, set cached object found
  1576. $rs->connection = $this; // Pablo suggestion
  1577. if ($this->debug){
  1578. if ($this->debug == 99) adodb_backtrace();
  1579. $inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
  1580. $ttl = $rs->timeCreated + $secs2cache - time();
  1581. $s = is_array($sql) ? $sql[0] : $sql;
  1582. if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
  1583. ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
  1584. }
  1585. }
  1586. return $rs;
  1587. }
  1588. /*
  1589. Similar to PEAR DB's autoExecute(), except that
  1590. $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
  1591. If $mode == 'UPDATE', then $where is compulsory as a safety measure.
  1592. $forceUpdate means that even if the data has not changed, perform update.
  1593. */
  1594. function AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false)
  1595. {
  1596. $false = false;
  1597. $sql = 'SELECT * FROM '.$table;
  1598. if ($where!==FALSE) $sql .= ' WHERE '.$where;
  1599. else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
  1600. $this->outp_throw('AutoExecute: Illegal mode=UPDATE with empty WHERE clause','AutoExecute');
  1601. return $false;
  1602. }
  1603. $rs = $this->SelectLimit($sql,1);
  1604. if (!$rs) return $false; // table does not exist
  1605. $rs->tableName = $table;
  1606. $rs->sql = $sql;
  1607. switch((string) $mode) {
  1608. case 'UPDATE':
  1609. case '2':
  1610. $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
  1611. break;
  1612. case 'INSERT':
  1613. case '1':
  1614. $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
  1615. break;
  1616. default:
  1617. $this->outp_throw("AutoExecute: Unknown mode=$mode",'AutoExecute');
  1618. return $false;
  1619. }
  1620. $ret = false;
  1621. if ($sql) $ret = $this->Execute($sql);
  1622. if ($ret) $ret = true;
  1623. return $ret;
  1624. }
  1625. /**
  1626. * Generates an Update Query based on an existing recordset.
  1627. * $arrFields is an associative array of fields with the value
  1628. * that should be assigned.
  1629. *
  1630. * Note: This function should only be used on a recordset
  1631. * that is run against a single table and sql should only
  1632. * be a simple select stmt with no groupby/orderby/limit
  1633. *
  1634. * "Jonathan Younger" <jyounger@unilab.com>
  1635. */
  1636. function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
  1637. {
  1638. global $ADODB_INCLUDED_LIB;
  1639. //********************************************************//
  1640. //This is here to maintain compatibility
  1641. //with older adodb versions. Sets force type to force nulls if $forcenulls is set.
  1642. if (!isset($force)) {
  1643. global $ADODB_FORCE_TYPE;
  1644. $force = $ADODB_FORCE_TYPE;
  1645. }
  1646. //********************************************************//
  1647. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1648. return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
  1649. }
  1650. /**
  1651. * Generates an Insert Query based on an existing recordset.
  1652. * $arrFields is an associative array of fields with the value
  1653. * that should be assigned.
  1654. *
  1655. * Note: This function should only be used on a recordset
  1656. * that is run against a single table.
  1657. */
  1658. function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
  1659. {
  1660. global $ADODB_INCLUDED_LIB;
  1661. if (!isset($force)) {
  1662. global $ADODB_FORCE_TYPE;
  1663. $force = $ADODB_FORCE_TYPE;
  1664. }
  1665. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1666. return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
  1667. }
  1668. /**
  1669. * Update a blob column, given a where clause. There are more sophisticated
  1670. * blob handling functions that we could have implemented, but all require
  1671. * a very complex API. Instead we have chosen something that is extremely
  1672. * simple to understand and use.
  1673. *
  1674. * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
  1675. *
  1676. * Usage to update a $blobvalue which has a primary key blob_id=1 into a
  1677. * field blobtable.blobcolumn:
  1678. *
  1679. * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
  1680. *
  1681. * Insert example:
  1682. *
  1683. * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1684. * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
  1685. */
  1686. function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  1687. {
  1688. return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
  1689. }
  1690. /**
  1691. * Usage:
  1692. * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
  1693. *
  1694. * $blobtype supports 'BLOB' and 'CLOB'
  1695. *
  1696. * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1697. * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
  1698. */
  1699. function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
  1700. {
  1701. $fd = fopen($path,'rb');
  1702. if ($fd === false) return false;
  1703. $val = fread($fd,filesize($path));
  1704. fclose($fd);
  1705. return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
  1706. }
  1707. function BlobDecode($blob)
  1708. {
  1709. return $blob;
  1710. }
  1711. function BlobEncode($blob)
  1712. {
  1713. return $blob;
  1714. }
  1715. function SetCharSet($charset)
  1716. {
  1717. return false;
  1718. }
  1719. function IfNull( $field, $ifNull )
  1720. {
  1721. return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
  1722. }
  1723. function LogSQL($enable=true)
  1724. {
  1725. include_once(ADODB_DIR.'/adodb-perf.inc.php');
  1726. if ($enable) $this->fnExecute = 'adodb_log_sql';
  1727. else $this->fnExecute = false;
  1728. $old = $this->_logsql;
  1729. $this->_logsql = $enable;
  1730. if ($enable && !$old) $this->_affected = false;
  1731. return $old;
  1732. }
  1733. function GetCharSet()
  1734. {
  1735. return false;
  1736. }
  1737. /**
  1738. * Usage:
  1739. * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
  1740. *
  1741. * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
  1742. * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
  1743. */
  1744. function UpdateClob($table,$column,$val,$where)
  1745. {
  1746. return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
  1747. }
  1748. // not the fastest implementation - quick and dirty - jlim
  1749. // for best performance, use the actual $rs->MetaType().
  1750. function MetaType($t,$len=-1,$fieldobj=false)
  1751. {
  1752. if (empty($this->_metars)) {
  1753. $rsclass = $this->rsPrefix.$this->databaseType;
  1754. $this->_metars = new $rsclass(false,$this->fetchMode);
  1755. $this->_metars->connection = $this;
  1756. }
  1757. return $this->_metars->MetaType($t,$len,$fieldobj);
  1758. }
  1759. /**
  1760. * Change the SQL connection locale to a specified locale.
  1761. * This is used to get the date formats written depending on the client locale.
  1762. */
  1763. function SetDateLocale($locale = 'En')
  1764. {
  1765. $this->locale = $locale;
  1766. switch (strtoupper($locale))
  1767. {
  1768. case 'EN':
  1769. $this->fmtDate="'Y-m-d'";
  1770. $this->fmtTimeStamp = "'Y-m-d H:i:s'";
  1771. break;
  1772. case 'US':
  1773. $this->fmtDate = "'m-d-Y'";
  1774. $this->fmtTimeStamp = "'m-d-Y H:i:s'";
  1775. break;
  1776. case 'PT_BR':
  1777. case 'NL':
  1778. case 'FR':
  1779. case 'RO':
  1780. case 'IT':
  1781. $this->fmtDate="'d-m-Y'";
  1782. $this->fmtTimeStamp = "'d-m-Y H:i:s'";
  1783. break;
  1784. case 'GE':
  1785. $this->fmtDate="'d.m.Y'";
  1786. $this->fmtTimeStamp = "'d.m.Y H:i:s'";
  1787. break;
  1788. default:
  1789. $this->fmtDate="'Y-m-d'";
  1790. $this->fmtTimeStamp = "'Y-m-d H:i:s'";
  1791. break;
  1792. }
  1793. }
  1794. /**
  1795. * GetActiveRecordsClass Performs an 'ALL' query
  1796. *
  1797. * @param mixed $class This string represents the class of the current active record
  1798. * @param mixed $table Table used by the active record object
  1799. * @param mixed $whereOrderBy Where, order, by clauses
  1800. * @param mixed $bindarr
  1801. * @param mixed $primkeyArr
  1802. * @param array $extra Query extras: limit, offset...
  1803. * @param mixed $relations Associative array: table's foreign name, "hasMany", "belongsTo"
  1804. * @access public
  1805. * @return void
  1806. */
  1807. function GetActiveRecordsClass(
  1808. $class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false,
  1809. $extra=array(),
  1810. $relations=array())
  1811. {
  1812. global $_ADODB_ACTIVE_DBS;
  1813. ## reduce overhead of adodb.inc.php -- moved to adodb-active-record.inc.php
  1814. ## if adodb-active-recordx is loaded -- should be no issue as they will probably use Find()
  1815. if (!isset($_ADODB_ACTIVE_DBS))include_once(ADODB_DIR.'/adodb-active-record.inc.php');
  1816. return adodb_GetActiveRecordsClass($this, $class, $table, $whereOrderBy, $bindarr, $primkeyArr, $extra, $relations);
  1817. }
  1818. function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
  1819. {
  1820. $arr = $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
  1821. return $arr;
  1822. }
  1823. /**
  1824. * Close Connection
  1825. */
  1826. function Close()
  1827. {
  1828. $rez = $this->_close();
  1829. $this->_connectionID = false;
  1830. return $rez;
  1831. }
  1832. /**
  1833. * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
  1834. *
  1835. * @return true if succeeded or false if database does not support transactions
  1836. */
  1837. function BeginTrans()
  1838. {
  1839. if ($this->debug) ADOConnection::outp("BeginTrans: Transactions not supported for this driver");
  1840. return false;
  1841. }
  1842. /* set transaction mode */
  1843. function SetTransactionMode( $transaction_mode )
  1844. {
  1845. $transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider);
  1846. $this->_transmode = $transaction_mode;
  1847. }
  1848. /*
  1849. http://msdn2.microsoft.com/en-US/ms173763.aspx
  1850. http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html
  1851. http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html
  1852. http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm
  1853. */
  1854. function MetaTransaction($mode,$db)
  1855. {
  1856. $mode = strtoupper($mode);
  1857. $mode = str_replace('ISOLATION LEVEL ','',$mode);
  1858. switch($mode) {
  1859. case 'READ UNCOMMITTED':
  1860. switch($db) {
  1861. case 'oci8':
  1862. case 'oracle':
  1863. return 'ISOLATION LEVEL READ COMMITTED';
  1864. default:
  1865. return 'ISOLATION LEVEL READ UNCOMMITTED';
  1866. }
  1867. break;
  1868. case 'READ COMMITTED':
  1869. return 'ISOLATION LEVEL READ COMMITTED';
  1870. break;
  1871. case 'REPEATABLE READ':
  1872. switch($db) {
  1873. case 'oci8':
  1874. case 'oracle':
  1875. return 'ISOLATION LEVEL SERIALIZABLE';
  1876. default:
  1877. return 'ISOLATION LEVEL REPEATABLE READ';
  1878. }
  1879. break;
  1880. case 'SERIALIZABLE':
  1881. return 'ISOLATION LEVEL SERIALIZABLE';
  1882. break;
  1883. default:
  1884. return $mode;
  1885. }
  1886. }
  1887. /**
  1888. * If database does not support transactions, always return true as data always commited
  1889. *
  1890. * @param $ok set to false to rollback transaction, true to commit
  1891. *
  1892. * @return true/false.
  1893. */
  1894. function CommitTrans($ok=true)
  1895. { return true;}
  1896. /**
  1897. * If database does not support transactions, rollbacks always fail, so return false
  1898. *
  1899. * @return true/false.
  1900. */
  1901. function RollbackTrans()
  1902. { return false;}
  1903. /**
  1904. * return the databases that the driver can connect to.
  1905. * Some databases will return an empty array.
  1906. *
  1907. * @return an array of database names.
  1908. */
  1909. function MetaDatabases()
  1910. {
  1911. global $ADODB_FETCH_MODE;
  1912. if ($this->metaDatabasesSQL) {
  1913. $save = $ADODB_FETCH_MODE;
  1914. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1915. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1916. $arr = $this->GetCol($this->metaDatabasesSQL);
  1917. if (isset($savem)) $this->SetFetchMode($savem);
  1918. $ADODB_FETCH_MODE = $save;
  1919. return $arr;
  1920. }
  1921. return false;
  1922. }
  1923. /**
  1924. * @param ttype can either be 'VIEW' or 'TABLE' or false.
  1925. * If false, both views and tables are returned.
  1926. * "VIEW" returns only views
  1927. * "TABLE" returns only tables
  1928. * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
  1929. * @param mask is the input mask - only supported by oci8 and postgresql
  1930. *
  1931. * @return array of tables for current database.
  1932. */
  1933. function MetaTables($ttype=false,$showSchema=false,$mask=false)
  1934. {
  1935. global $ADODB_FETCH_MODE;
  1936. $false = false;
  1937. if ($mask) {
  1938. return $false;
  1939. }
  1940. if ($this->metaTablesSQL) {
  1941. $save = $ADODB_FETCH_MODE;
  1942. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1943. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1944. $rs = $this->Execute($this->metaTablesSQL);
  1945. if (isset($savem)) $this->SetFetchMode($savem);
  1946. $ADODB_FETCH_MODE = $save;
  1947. if ($rs === false) return $false;
  1948. $arr = $rs->GetArray();
  1949. $arr2 = array();
  1950. if ($hast = ($ttype && isset($arr[0][1]))) {
  1951. $showt = strncmp($ttype,'T',1);
  1952. }
  1953. for ($i=0; $i < sizeof($arr); $i++) {
  1954. if ($hast) {
  1955. if ($showt == 0) {
  1956. if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
  1957. } else {
  1958. if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
  1959. }
  1960. } else
  1961. $arr2[] = trim($arr[$i][0]);
  1962. }
  1963. $rs->Close();
  1964. return $arr2;
  1965. }
  1966. return $false;
  1967. }
  1968. function _findschema(&$table,&$schema)
  1969. {
  1970. if (!$schema && ($at = strpos($table,'.')) !== false) {
  1971. $schema = substr($table,0,$at);
  1972. $table = substr($table,$at+1);
  1973. }
  1974. }
  1975. /**
  1976. * List columns in a database as an array of ADOFieldObjects.
  1977. * See top of file for definition of object.
  1978. *
  1979. * @param $table table name to query
  1980. * @param $normalize makes table name case-insensitive (required by some databases)
  1981. * @schema is optional database schema to use - not supported by all databases.
  1982. *
  1983. * @return array of ADOFieldObjects for current table.
  1984. */
  1985. function MetaColumns($table,$normalize=true)
  1986. {
  1987. global $ADODB_FETCH_MODE;
  1988. $false = false;
  1989. if (!empty($this->metaColumnsSQL)) {
  1990. $schema = false;
  1991. $this->_findschema($table,$schema);
  1992. $save = $ADODB_FETCH_MODE;
  1993. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1994. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1995. $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table));
  1996. if (isset($savem)) $this->SetFetchMode($savem);
  1997. $ADODB_FETCH_MODE = $save;
  1998. if ($rs === false || $rs->EOF) return $false;
  1999. $retarr = array();
  2000. while (!$rs->EOF) { //print_r($rs->fields);
  2001. $fld = new ADOFieldObject();
  2002. $fld->name = $rs->fields[0];
  2003. $fld->type = $rs->fields[1];
  2004. if (isset($rs->fields[3]) && $rs->fields[3]) {
  2005. if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
  2006. $fld->scale = $rs->fields[4];
  2007. if ($fld->scale>0) $fld->max_length += 1;
  2008. } else
  2009. $fld->max_length = $rs->fields[2];
  2010. if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
  2011. else $retarr[strtoupper($fld->name)] = $fld;
  2012. $rs->MoveNext();
  2013. }
  2014. $rs->Close();
  2015. return $retarr;
  2016. }
  2017. return $false;
  2018. }
  2019. /**
  2020. * List indexes on a table as an array.
  2021. * @param table table name to query
  2022. * @param primary true to only show primary keys. Not actually used for most databases
  2023. *
  2024. * @return array of indexes on current table. Each element represents an index, and is itself an associative array.
  2025. Array (
  2026. [name_of_index] => Array
  2027. (
  2028. [unique] => true or false
  2029. [columns] => Array
  2030. (
  2031. [0] => firstname
  2032. [1] => lastname
  2033. )
  2034. )
  2035. */
  2036. function MetaIndexes($table, $primary = false, $owner = false)
  2037. {
  2038. $false = false;
  2039. return $false;
  2040. }
  2041. /**
  2042. * List columns names in a table as an array.
  2043. * @param table table name to query
  2044. *
  2045. * @return array of column names for current table.
  2046. */
  2047. function MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */)
  2048. {
  2049. $objarr = $this->MetaColumns($table);
  2050. if (!is_array($objarr)) {
  2051. $false = false;
  2052. return $false;
  2053. }
  2054. $arr = array();
  2055. if ($numIndexes) {
  2056. $i = 0;
  2057. if ($useattnum) {
  2058. foreach($objarr as $v)
  2059. $arr[$v->attnum] = $v->name;
  2060. } else
  2061. foreach($objarr as $v) $arr[$i++] = $v->name;
  2062. } else
  2063. foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
  2064. return $arr;
  2065. }
  2066. /**
  2067. * Different SQL databases used different methods to combine strings together.
  2068. * This function provides a wrapper.
  2069. *
  2070. * param s variable number of string parameters
  2071. *
  2072. * Usage: $db->Concat($str1,$str2);
  2073. *
  2074. * @return concatenated string
  2075. */
  2076. function Concat()
  2077. {
  2078. $arr = func_get_args();
  2079. return implode($this->concat_operator, $arr);
  2080. }
  2081. /**
  2082. * Converts a date "d" to a string that the database can understand.
  2083. *
  2084. * @param d a date in Unix date time format.
  2085. *
  2086. * @return date string in database date format
  2087. */
  2088. function DBDate($d, $isfld=false)
  2089. {
  2090. if (empty($d) && $d !== 0) return 'null';
  2091. if ($isfld) return $d;
  2092. if (is_object($d)) return $d->format($this->fmtDate);
  2093. if (is_string($d) && !is_numeric($d)) {
  2094. if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
  2095. if ($this->isoDates) return "'$d'";
  2096. $d = ADOConnection::UnixDate($d);
  2097. }
  2098. return adodb_date($this->fmtDate,$d);
  2099. }
  2100. function BindDate($d)
  2101. {
  2102. $d = $this->DBDate($d);
  2103. if (strncmp($d,"'",1)) return $d;
  2104. return substr($d,1,strlen($d)-2);
  2105. }
  2106. function BindTimeStamp($d)
  2107. {
  2108. $d = $this->DBTimeStamp($d);
  2109. if (strncmp($d,"'",1)) return $d;
  2110. return substr($d,1,strlen($d)-2);
  2111. }
  2112. /**
  2113. * Converts a timestamp "ts" to a string that the database can understand.
  2114. *
  2115. * @param ts a timestamp in Unix date time format.
  2116. *
  2117. * @return timestamp string in database timestamp format
  2118. */
  2119. function DBTimeStamp($ts,$isfld=false)
  2120. {
  2121. if (empty($ts) && $ts !== 0) return 'null';
  2122. if ($isfld) return $ts;
  2123. if (is_object($ts)) return $ts->format($this->fmtTimeStamp);
  2124. # strlen(14) allows YYYYMMDDHHMMSS format
  2125. if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
  2126. return adodb_date($this->fmtTimeStamp,$ts);
  2127. if ($ts === 'null') return $ts;
  2128. if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
  2129. $ts = ADOConnection::UnixTimeStamp($ts);
  2130. return adodb_date($this->fmtTimeStamp,$ts);
  2131. }
  2132. /**
  2133. * Also in ADORecordSet.
  2134. * @param $v is a date string in YYYY-MM-DD format
  2135. *
  2136. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2137. */
  2138. static function UnixDate($v)
  2139. {
  2140. if (is_object($v)) {
  2141. // odbtp support
  2142. //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
  2143. return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
  2144. }
  2145. if (is_numeric($v) && strlen($v) !== 8) return $v;
  2146. if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
  2147. ($v), $rr)) return false;
  2148. if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
  2149. // h-m-s-MM-DD-YY
  2150. return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  2151. }
  2152. /**
  2153. * Also in ADORecordSet.
  2154. * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  2155. *
  2156. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2157. */
  2158. static function UnixTimeStamp($v)
  2159. {
  2160. if (is_object($v)) {
  2161. // odbtp support
  2162. //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
  2163. return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
  2164. }
  2165. if (!preg_match(
  2166. "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
  2167. ($v), $rr)) return false;
  2168. if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
  2169. // h-m-s-MM-DD-YY
  2170. if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  2171. return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
  2172. }
  2173. /**
  2174. * Also in ADORecordSet.
  2175. *
  2176. * Format database date based on user defined format.
  2177. *
  2178. * @param v is the character date in YYYY-MM-DD format, returned by database
  2179. * @param fmt is the format to apply to it, using date()
  2180. *
  2181. * @return a date formated as user desires
  2182. */
  2183. function UserDate($v,$fmt='Y-m-d',$gmt=false)
  2184. {
  2185. $tt = $this->UnixDate($v);
  2186. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2187. if (($tt === false || $tt == -1) && $v != false) return $v;
  2188. else if ($tt == 0) return $this->emptyDate;
  2189. else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  2190. }
  2191. return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  2192. }
  2193. /**
  2194. *
  2195. * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
  2196. * @param fmt is the format to apply to it, using date()
  2197. *
  2198. * @return a timestamp formated as user desires
  2199. */
  2200. function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)
  2201. {
  2202. if (!isset($v)) return $this->emptyTimeStamp;
  2203. # strlen(14) allows YYYYMMDDHHMMSS format
  2204. if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
  2205. $tt = $this->UnixTimeStamp($v);
  2206. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2207. if (($tt === false || $tt == -1) && $v != false) return $v;
  2208. if ($tt == 0) return $this->emptyTimeStamp;
  2209. return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  2210. }
  2211. function escape($s,$magic_quotes=false)
  2212. {
  2213. return $this->addq($s,$magic_quotes);
  2214. }
  2215. /**
  2216. * Quotes a string, without prefixing nor appending quotes.
  2217. */
  2218. function addq($s,$magic_quotes=false)
  2219. {
  2220. if (!$magic_quotes) {
  2221. if ($this->replaceQuote[0] == '\\'){
  2222. // only since php 4.0.5
  2223. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  2224. //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  2225. }
  2226. return str_replace("'",$this->replaceQuote,$s);
  2227. }
  2228. // undo magic quotes for "
  2229. $s = str_replace('\\"','"',$s);
  2230. if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything
  2231. return $s;
  2232. else {// change \' to '' for sybase/mssql
  2233. $s = str_replace('\\\\','\\',$s);
  2234. return str_replace("\\'",$this->replaceQuote,$s);
  2235. }
  2236. }
  2237. /**
  2238. * Correctly quotes a string so that all strings are escaped. We prefix and append
  2239. * to the string single-quotes.
  2240. * An example is $db->qstr("Don't bother",magic_quotes_runtime());
  2241. *
  2242. * @param s the string to quote
  2243. * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
  2244. * This undoes the stupidity of magic quotes for GPC.
  2245. *
  2246. * @return quoted string to be sent back to database
  2247. */
  2248. function qstr($s,$magic_quotes=false)
  2249. {
  2250. if (!$magic_quotes) {
  2251. if ($this->replaceQuote[0] == '\\'){
  2252. // only since php 4.0.5
  2253. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  2254. //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  2255. }
  2256. return "'".str_replace("'",$this->replaceQuote,$s)."'";
  2257. }
  2258. // undo magic quotes for "
  2259. $s = str_replace('\\"','"',$s);
  2260. if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything
  2261. return "'$s'";
  2262. else {// change \' to '' for sybase/mssql
  2263. $s = str_replace('\\\\','\\',$s);
  2264. return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
  2265. }
  2266. }
  2267. /**
  2268. * Will select the supplied $page number from a recordset, given that it is paginated in pages of
  2269. * $nrows rows per page. It also saves two boolean values saying if the given page is the first
  2270. * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination.
  2271. *
  2272. * See readme.htm#ex8 for an example of usage.
  2273. *
  2274. * @param sql
  2275. * @param nrows is the number of rows per page to get
  2276. * @param page is the page number to get (1-based)
  2277. * @param [inputarr] array of bind variables
  2278. * @param [secs2cache] is a private parameter only used by jlim
  2279. * @return the recordset ($rs->databaseType == 'array')
  2280. *
  2281. * NOTE: phpLens uses a different algorithm and does not use PageExecute().
  2282. *
  2283. */
  2284. function PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
  2285. {
  2286. global $ADODB_INCLUDED_LIB;
  2287. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  2288. if ($this->pageExecuteCountRows) $rs = _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  2289. else $rs = _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  2290. return $rs;
  2291. }
  2292. /**
  2293. * Will select the supplied $page number from a recordset, given that it is paginated in pages of
  2294. * $nrows rows per page. It also saves two boolean values saying if the given page is the first
  2295. * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination.
  2296. *
  2297. * @param secs2cache seconds to cache data, set to 0 to force query
  2298. * @param sql
  2299. * @param nrows is the number of rows per page to get
  2300. * @param page is the page number to get (1-based)
  2301. * @param [inputarr] array of bind variables
  2302. * @return the recordset ($rs->databaseType == 'array')
  2303. */
  2304. function CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
  2305. {
  2306. /*switch($this->dataProvider) {
  2307. case 'postgres':
  2308. case 'mysql':
  2309. break;
  2310. default: $secs2cache = 0; break;
  2311. }*/
  2312. $rs = $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
  2313. return $rs;
  2314. }
  2315. } // end class ADOConnection
  2316. //==============================================================================================
  2317. // CLASS ADOFetchObj
  2318. //==============================================================================================
  2319. /**
  2320. * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
  2321. */
  2322. class ADOFetchObj {
  2323. };
  2324. //==============================================================================================
  2325. // CLASS ADORecordSet_empty
  2326. //==============================================================================================
  2327. class ADODB_Iterator_empty implements Iterator {
  2328. private $rs;
  2329. function __construct($rs)
  2330. {
  2331. $this->rs = $rs;
  2332. }
  2333. function rewind()
  2334. {
  2335. }
  2336. function valid()
  2337. {
  2338. return !$this->rs->EOF;
  2339. }
  2340. function key()
  2341. {
  2342. return false;
  2343. }
  2344. function current()
  2345. {
  2346. return false;
  2347. }
  2348. function next()
  2349. {
  2350. }
  2351. function __call($func, $params)
  2352. {
  2353. return call_user_func_array(array($this->rs, $func), $params);
  2354. }
  2355. function hasMore()
  2356. {
  2357. return false;
  2358. }
  2359. }
  2360. /**
  2361. * Lightweight recordset when there are no records to be returned
  2362. */
  2363. class ADORecordSet_empty implements IteratorAggregate
  2364. {
  2365. var $dataProvider = 'empty';
  2366. var $databaseType = false;
  2367. var $EOF = true;
  2368. var $_numOfRows = 0;
  2369. var $fields = false;
  2370. var $connection = false;
  2371. function RowCount() {return 0;}
  2372. function RecordCount() {return 0;}
  2373. function PO_RecordCount(){return 0;}
  2374. function Close(){return true;}
  2375. function FetchRow() {return false;}
  2376. function FieldCount(){ return 0;}
  2377. function Init() {}
  2378. function getIterator() {return new ADODB_Iterator_empty($this);}
  2379. }
  2380. //==============================================================================================
  2381. // DATE AND TIME FUNCTIONS
  2382. //==============================================================================================
  2383. if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php');
  2384. //==============================================================================================
  2385. // CLASS ADORecordSet
  2386. //==============================================================================================
  2387. class ADODB_Iterator implements Iterator {
  2388. private $rs;
  2389. function __construct($rs)
  2390. {
  2391. $this->rs = $rs;
  2392. }
  2393. function rewind()
  2394. {
  2395. $this->rs->MoveFirst();
  2396. }
  2397. function valid()
  2398. {
  2399. return !$this->rs->EOF;
  2400. }
  2401. function key()
  2402. {
  2403. return $this->rs->_currentRow;
  2404. }
  2405. function current()
  2406. {
  2407. return $this->rs->fields;
  2408. }
  2409. function next()
  2410. {
  2411. $this->rs->MoveNext();
  2412. }
  2413. function __call($func, $params)
  2414. {
  2415. return call_user_func_array(array($this->rs, $func), $params);
  2416. }
  2417. function hasMore()
  2418. {
  2419. return !$this->rs->EOF;
  2420. }
  2421. }
  2422. /**
  2423. * RecordSet class that represents the dataset returned by the database.
  2424. * To keep memory overhead low, this class holds only the current row in memory.
  2425. * No prefetching of data is done, so the RecordCount() can return -1 ( which
  2426. * means recordcount not known).
  2427. */
  2428. class ADORecordSet implements IteratorAggregate {
  2429. /*
  2430. * public variables
  2431. */
  2432. var $dataProvider = "native";
  2433. var $fields = false; /// holds the current row data
  2434. var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
  2435. /// in other words, we use a text area for editing.
  2436. var $canSeek = false; /// indicates that seek is supported
  2437. var $sql; /// sql text
  2438. var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
  2439. var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
  2440. var $emptyDate = '&nbsp;'; /// what to display when $time==0
  2441. var $debug = false;
  2442. var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
  2443. var $bind = false; /// used by Fields() to hold array - should be private?
  2444. var $fetchMode; /// default fetch mode
  2445. var $connection = false; /// the parent connection
  2446. /*
  2447. * private variables
  2448. */
  2449. var $_numOfRows = -1; /** number of rows, or -1 */
  2450. var $_numOfFields = -1; /** number of fields in recordset */
  2451. var $_queryID = -1; /** This variable keeps the result link identifier. */
  2452. var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
  2453. var $_closed = false; /** has recordset been closed */
  2454. var $_inited = false; /** Init() should only be called once */
  2455. var $_obj; /** Used by FetchObj */
  2456. var $_names; /** Used by FetchObj */
  2457. var $_currentPage = -1; /** Added by Iv�n Oliva to implement recordset pagination */
  2458. var $_atFirstPage = false; /** Added by Iv�n Oliva to implement recordset pagination */
  2459. var $_atLastPage = false; /** Added by Iv�n Oliva to implement recordset pagination */
  2460. var $_lastPageNo = -1;
  2461. var $_maxRecordCount = 0;
  2462. var $datetime = false;
  2463. /**
  2464. * Constructor
  2465. *
  2466. * @param queryID this is the queryID returned by ADOConnection->_query()
  2467. *
  2468. */
  2469. function ADORecordSet($queryID)
  2470. {
  2471. $this->_queryID = $queryID;
  2472. }
  2473. function getIterator()
  2474. {
  2475. return new ADODB_Iterator($this);
  2476. }
  2477. /* this is experimental - i don't really know what to return... */
  2478. function __toString()
  2479. {
  2480. include_once(ADODB_DIR.'/toexport.inc.php');
  2481. return _adodb_export($this,',',',',false,true);
  2482. }
  2483. function Init()
  2484. {
  2485. if ($this->_inited) return;
  2486. $this->_inited = true;
  2487. if ($this->_queryID) @$this->_initrs();
  2488. else {
  2489. $this->_numOfRows = 0;
  2490. $this->_numOfFields = 0;
  2491. }
  2492. if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
  2493. $this->_currentRow = 0;
  2494. if ($this->EOF = ($this->_fetch() === false)) {
  2495. $this->_numOfRows = 0; // _numOfRows could be -1
  2496. }
  2497. } else {
  2498. $this->EOF = true;
  2499. }
  2500. }
  2501. /**
  2502. * Generate a SELECT tag string from a recordset, and return the string.
  2503. * If the recordset has 2 cols, we treat the 1st col as the containing
  2504. * the text to display to the user, and 2nd col as the return value. Default
  2505. * strings are compared with the FIRST column.
  2506. *
  2507. * @param name name of SELECT tag
  2508. * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
  2509. * @param [blank1stItem] true to leave the 1st item in list empty
  2510. * @param [multiple] true for listbox, false for popup
  2511. * @param [size] #rows to show for listbox. not used by popup
  2512. * @param [selectAttr] additional attributes to defined for SELECT tag.
  2513. * useful for holding javascript onChange='...' handlers.
  2514. & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
  2515. * column 0 (1st col) if this is true. This is not documented.
  2516. *
  2517. * @return HTML
  2518. *
  2519. * changes by glen.davies@cce.ac.nz to support multiple hilited items
  2520. */
  2521. function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
  2522. $size=0, $selectAttr='',$compareFields0=true)
  2523. {
  2524. global $ADODB_INCLUDED_LIB;
  2525. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  2526. return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
  2527. $size, $selectAttr,$compareFields0);
  2528. }
  2529. /**
  2530. * Generate a SELECT tag string from a recordset, and return the string.
  2531. * If the recordset has 2 cols, we treat the 1st col as the containing
  2532. * the text to display to the user, and 2nd col as the return value. Default
  2533. * strings are compared with the SECOND column.
  2534. *
  2535. */
  2536. function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
  2537. {
  2538. return $this->GetMenu($name,$defstr,$blank1stItem,$multiple,
  2539. $size, $selectAttr,false);
  2540. }
  2541. /*
  2542. Grouped Menu
  2543. */
  2544. function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false,
  2545. $size=0, $selectAttr='')
  2546. {
  2547. global $ADODB_INCLUDED_LIB;
  2548. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  2549. return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple,
  2550. $size, $selectAttr,false);
  2551. }
  2552. /**
  2553. * return recordset as a 2-dimensional array.
  2554. *
  2555. * @param [nRows] is the number of rows to return. -1 means every row.
  2556. *
  2557. * @return an array indexed by the rows (0-based) from the recordset
  2558. */
  2559. function GetArray($nRows = -1)
  2560. {
  2561. global $ADODB_EXTENSION; if ($ADODB_EXTENSION) {
  2562. $results = adodb_getall($this,$nRows);
  2563. return $results;
  2564. }
  2565. $results = array();
  2566. $cnt = 0;
  2567. while (!$this->EOF && $nRows != $cnt) {
  2568. $results[] = $this->fields;
  2569. $this->MoveNext();
  2570. $cnt++;
  2571. }
  2572. return $results;
  2573. }
  2574. function GetAll($nRows = -1)
  2575. {
  2576. $arr = $this->GetArray($nRows);
  2577. return $arr;
  2578. }
  2579. /*
  2580. * Some databases allow multiple recordsets to be returned. This function
  2581. * will return true if there is a next recordset, or false if no more.
  2582. */
  2583. function NextRecordSet()
  2584. {
  2585. return false;
  2586. }
  2587. /**
  2588. * return recordset as a 2-dimensional array.
  2589. * Helper function for ADOConnection->SelectLimit()
  2590. *
  2591. * @param offset is the row to start calculations from (1-based)
  2592. * @param [nrows] is the number of rows to return
  2593. *
  2594. * @return an array indexed by the rows (0-based) from the recordset
  2595. */
  2596. function GetArrayLimit($nrows,$offset=-1)
  2597. {
  2598. if ($offset <= 0) {
  2599. $arr = $this->GetArray($nrows);
  2600. return $arr;
  2601. }
  2602. $this->Move($offset);
  2603. $results = array();
  2604. $cnt = 0;
  2605. while (!$this->EOF && $nrows != $cnt) {
  2606. $results[$cnt++] = $this->fields;
  2607. $this->MoveNext();
  2608. }
  2609. return $results;
  2610. }
  2611. /**
  2612. * Synonym for GetArray() for compatibility with ADO.
  2613. *
  2614. * @param [nRows] is the number of rows to return. -1 means every row.
  2615. *
  2616. * @return an array indexed by the rows (0-based) from the recordset
  2617. */
  2618. function GetRows($nRows = -1)
  2619. {
  2620. $arr = $this->GetArray($nRows);
  2621. return $arr;
  2622. }
  2623. /**
  2624. * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
  2625. * The first column is treated as the key and is not included in the array.
  2626. * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
  2627. * $force_array == true.
  2628. *
  2629. * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
  2630. * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
  2631. * read the source.
  2632. *
  2633. * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
  2634. * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
  2635. *
  2636. * @return an associative array indexed by the first column of the array,
  2637. * or false if the data has less than 2 cols.
  2638. */
  2639. function GetAssoc($force_array = false, $first2cols = false)
  2640. {
  2641. global $ADODB_EXTENSION;
  2642. $cols = $this->_numOfFields;
  2643. if ($cols < 2) {
  2644. $false = false;
  2645. return $false;
  2646. }
  2647. $numIndex = isset($this->fields[0]);
  2648. $results = array();
  2649. if (!$first2cols && ($cols > 2 || $force_array)) {
  2650. if ($ADODB_EXTENSION) {
  2651. if ($numIndex) {
  2652. while (!$this->EOF) {
  2653. $results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2654. adodb_movenext($this);
  2655. }
  2656. } else {
  2657. while (!$this->EOF) {
  2658. // Fix for array_slice re-numbering numeric associative keys
  2659. $keys = array_slice(array_keys($this->fields), 1);
  2660. $sliced_array = array();
  2661. foreach($keys as $key) {
  2662. $sliced_array[$key] = $this->fields[$key];
  2663. }
  2664. $results[trim(reset($this->fields))] = $sliced_array;
  2665. adodb_movenext($this);
  2666. }
  2667. }
  2668. } else {
  2669. if ($numIndex) {
  2670. while (!$this->EOF) {
  2671. $results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2672. $this->MoveNext();
  2673. }
  2674. } else {
  2675. while (!$this->EOF) {
  2676. // Fix for array_slice re-numbering numeric associative keys
  2677. $keys = array_slice(array_keys($this->fields), 1);
  2678. $sliced_array = array();
  2679. foreach($keys as $key) {
  2680. $sliced_array[$key] = $this->fields[$key];
  2681. }
  2682. $results[trim(reset($this->fields))] = $sliced_array;
  2683. $this->MoveNext();
  2684. }
  2685. }
  2686. }
  2687. } else {
  2688. if ($ADODB_EXTENSION) {
  2689. // return scalar values
  2690. if ($numIndex) {
  2691. while (!$this->EOF) {
  2692. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2693. $results[trim(($this->fields[0]))] = $this->fields[1];
  2694. adodb_movenext($this);
  2695. }
  2696. } else {
  2697. while (!$this->EOF) {
  2698. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2699. $v1 = trim(reset($this->fields));
  2700. $v2 = ''.next($this->fields);
  2701. $results[$v1] = $v2;
  2702. adodb_movenext($this);
  2703. }
  2704. }
  2705. } else {
  2706. if ($numIndex) {
  2707. while (!$this->EOF) {
  2708. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2709. $results[trim(($this->fields[0]))] = $this->fields[1];
  2710. $this->MoveNext();
  2711. }
  2712. } else {
  2713. while (!$this->EOF) {
  2714. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2715. $v1 = trim(reset($this->fields));
  2716. $v2 = ''.next($this->fields);
  2717. $results[$v1] = $v2;
  2718. $this->MoveNext();
  2719. }
  2720. }
  2721. }
  2722. }
  2723. $ref = $results; # workaround accelerator incompat with PHP 4.4 :(
  2724. return $ref;
  2725. }
  2726. /**
  2727. *
  2728. * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
  2729. * @param fmt is the format to apply to it, using date()
  2730. *
  2731. * @return a timestamp formated as user desires
  2732. */
  2733. function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
  2734. {
  2735. if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
  2736. $tt = $this->UnixTimeStamp($v);
  2737. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2738. if (($tt === false || $tt == -1) && $v != false) return $v;
  2739. if ($tt === 0) return $this->emptyTimeStamp;
  2740. return adodb_date($fmt,$tt);
  2741. }
  2742. /**
  2743. * @param v is the character date in YYYY-MM-DD format, returned by database
  2744. * @param fmt is the format to apply to it, using date()
  2745. *
  2746. * @return a date formated as user desires
  2747. */
  2748. function UserDate($v,$fmt='Y-m-d')
  2749. {
  2750. $tt = $this->UnixDate($v);
  2751. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2752. if (($tt === false || $tt == -1) && $v != false) return $v;
  2753. else if ($tt == 0) return $this->emptyDate;
  2754. else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  2755. }
  2756. return adodb_date($fmt,$tt);
  2757. }
  2758. /**
  2759. * @param $v is a date string in YYYY-MM-DD format
  2760. *
  2761. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2762. */
  2763. static function UnixDate($v)
  2764. {
  2765. return ADOConnection::UnixDate($v);
  2766. }
  2767. /**
  2768. * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  2769. *
  2770. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2771. */
  2772. static function UnixTimeStamp($v)
  2773. {
  2774. return ADOConnection::UnixTimeStamp($v);
  2775. }
  2776. /**
  2777. * PEAR DB Compat - do not use internally
  2778. */
  2779. function Free()
  2780. {
  2781. return $this->Close();
  2782. }
  2783. /**
  2784. * PEAR DB compat, number of rows
  2785. */
  2786. function NumRows()
  2787. {
  2788. return $this->_numOfRows;
  2789. }
  2790. /**
  2791. * PEAR DB compat, number of cols
  2792. */
  2793. function NumCols()
  2794. {
  2795. return $this->_numOfFields;
  2796. }
  2797. /**
  2798. * Fetch a row, returning false if no more rows.
  2799. * This is PEAR DB compat mode.
  2800. *
  2801. * @return false or array containing the current record
  2802. */
  2803. function FetchRow()
  2804. {
  2805. if ($this->EOF) {
  2806. $false = false;
  2807. return $false;
  2808. }
  2809. $arr = $this->fields;
  2810. $this->_currentRow++;
  2811. if (!$this->_fetch()) $this->EOF = true;
  2812. return $arr;
  2813. }
  2814. /**
  2815. * Fetch a row, returning PEAR_Error if no more rows.
  2816. * This is PEAR DB compat mode.
  2817. *
  2818. * @return DB_OK or error object
  2819. */
  2820. function FetchInto(&$arr)
  2821. {
  2822. if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
  2823. $arr = $this->fields;
  2824. $this->MoveNext();
  2825. return 1; // DB_OK
  2826. }
  2827. /**
  2828. * Move to the first row in the recordset. Many databases do NOT support this.
  2829. *
  2830. * @return true or false
  2831. */
  2832. function MoveFirst()
  2833. {
  2834. if ($this->_currentRow == 0) return true;
  2835. return $this->Move(0);
  2836. }
  2837. /**
  2838. * Move to the last row in the recordset.
  2839. *
  2840. * @return true or false
  2841. */
  2842. function MoveLast()
  2843. {
  2844. if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
  2845. if ($this->EOF) return false;
  2846. while (!$this->EOF) {
  2847. $f = $this->fields;
  2848. $this->MoveNext();
  2849. }
  2850. $this->fields = $f;
  2851. $this->EOF = false;
  2852. return true;
  2853. }
  2854. /**
  2855. * Move to next record in the recordset.
  2856. *
  2857. * @return true if there still rows available, or false if there are no more rows (EOF).
  2858. */
  2859. function MoveNext()
  2860. {
  2861. if (!$this->EOF) {
  2862. $this->_currentRow++;
  2863. if ($this->_fetch()) return true;
  2864. }
  2865. $this->EOF = true;
  2866. /* -- tested error handling when scrolling cursor -- seems useless.
  2867. $conn = $this->connection;
  2868. if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
  2869. $fn = $conn->raiseErrorFn;
  2870. $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
  2871. }
  2872. */
  2873. return false;
  2874. }
  2875. /**
  2876. * Random access to a specific row in the recordset. Some databases do not support
  2877. * access to previous rows in the databases (no scrolling backwards).
  2878. *
  2879. * @param rowNumber is the row to move to (0-based)
  2880. *
  2881. * @return true if there still rows available, or false if there are no more rows (EOF).
  2882. */
  2883. function Move($rowNumber = 0)
  2884. {
  2885. $this->EOF = false;
  2886. if ($rowNumber == $this->_currentRow) return true;
  2887. if ($rowNumber >= $this->_numOfRows)
  2888. if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
  2889. if ($this->canSeek) {
  2890. if ($this->_seek($rowNumber)) {
  2891. $this->_currentRow = $rowNumber;
  2892. if ($this->_fetch()) {
  2893. return true;
  2894. }
  2895. } else {
  2896. $this->EOF = true;
  2897. return false;
  2898. }
  2899. } else {
  2900. if ($rowNumber < $this->_currentRow) return false;
  2901. global $ADODB_EXTENSION;
  2902. if ($ADODB_EXTENSION) {
  2903. while (!$this->EOF && $this->_currentRow < $rowNumber) {
  2904. adodb_movenext($this);
  2905. }
  2906. } else {
  2907. while (! $this->EOF && $this->_currentRow < $rowNumber) {
  2908. $this->_currentRow++;
  2909. if (!$this->_fetch()) $this->EOF = true;
  2910. }
  2911. }
  2912. return !($this->EOF);
  2913. }
  2914. $this->fields = false;
  2915. $this->EOF = true;
  2916. return false;
  2917. }
  2918. /**
  2919. * Get the value of a field in the current row by column name.
  2920. * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
  2921. *
  2922. * @param colname is the field to access
  2923. *
  2924. * @return the value of $colname column
  2925. */
  2926. function Fields($colname)
  2927. {
  2928. return $this->fields[$colname];
  2929. }
  2930. function GetAssocKeys($upper=true)
  2931. {
  2932. $this->bind = array();
  2933. for ($i=0; $i < $this->_numOfFields; $i++) {
  2934. $o = $this->FetchField($i);
  2935. if ($upper === 2) $this->bind[$o->name] = $i;
  2936. else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
  2937. }
  2938. }
  2939. /**
  2940. * Use associative array to get fields array for databases that do not support
  2941. * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it
  2942. *
  2943. * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
  2944. * before you execute your SQL statement, and access $rs->fields['col'] directly.
  2945. *
  2946. * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
  2947. */
  2948. function GetRowAssoc($upper=1)
  2949. {
  2950. $record = array();
  2951. // if (!$this->fields) return $record;
  2952. if (!$this->bind) {
  2953. $this->GetAssocKeys($upper);
  2954. }
  2955. foreach($this->bind as $k => $v) {
  2956. $record[$k] = $this->fields[$v];
  2957. }
  2958. return $record;
  2959. }
  2960. /**
  2961. * Clean up recordset
  2962. *
  2963. * @return true or false
  2964. */
  2965. function Close()
  2966. {
  2967. // free connection object - this seems to globally free the object
  2968. // and not merely the reference, so don't do this...
  2969. // $this->connection = false;
  2970. if (!$this->_closed) {
  2971. $this->_closed = true;
  2972. return $this->_close();
  2973. } else
  2974. return true;
  2975. }
  2976. /**
  2977. * synonyms RecordCount and RowCount
  2978. *
  2979. * @return the number of rows or -1 if this is not supported
  2980. */
  2981. function RecordCount() {return $this->_numOfRows;}
  2982. /*
  2983. * If we are using PageExecute(), this will return the maximum possible rows
  2984. * that can be returned when paging a recordset.
  2985. */
  2986. function MaxRecordCount()
  2987. {
  2988. return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
  2989. }
  2990. /**
  2991. * synonyms RecordCount and RowCount
  2992. *
  2993. * @return the number of rows or -1 if this is not supported
  2994. */
  2995. function RowCount() {return $this->_numOfRows;}
  2996. /**
  2997. * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
  2998. *
  2999. * @return the number of records from a previous SELECT. All databases support this.
  3000. *
  3001. * But aware possible problems in multiuser environments. For better speed the table
  3002. * must be indexed by the condition. Heavy test this before deploying.
  3003. */
  3004. function PO_RecordCount($table="", $condition="") {
  3005. $lnumrows = $this->_numOfRows;
  3006. // the database doesn't support native recordcount, so we do a workaround
  3007. if ($lnumrows == -1 && $this->connection) {
  3008. IF ($table) {
  3009. if ($condition) $condition = " WHERE " . $condition;
  3010. $resultrows = $this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
  3011. if ($resultrows) $lnumrows = reset($resultrows->fields);
  3012. }
  3013. }
  3014. return $lnumrows;
  3015. }
  3016. /**
  3017. * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  3018. */
  3019. function CurrentRow() {return $this->_currentRow;}
  3020. /**
  3021. * synonym for CurrentRow -- for ADO compat
  3022. *
  3023. * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  3024. */
  3025. function AbsolutePosition() {return $this->_currentRow;}
  3026. /**
  3027. * @return the number of columns in the recordset. Some databases will set this to 0
  3028. * if no records are returned, others will return the number of columns in the query.
  3029. */
  3030. function FieldCount() {return $this->_numOfFields;}
  3031. /**
  3032. * Get the ADOFieldObject of a specific column.
  3033. *
  3034. * @param fieldoffset is the column position to access(0-based).
  3035. *
  3036. * @return the ADOFieldObject for that column, or false.
  3037. */
  3038. function FetchField($fieldoffset = -1)
  3039. {
  3040. // must be defined by child class
  3041. $false = false;
  3042. return $false;
  3043. }
  3044. /**
  3045. * Get the ADOFieldObjects of all columns in an array.
  3046. *
  3047. */
  3048. function FieldTypesArray()
  3049. {
  3050. $arr = array();
  3051. for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
  3052. $arr[] = $this->FetchField($i);
  3053. return $arr;
  3054. }
  3055. /**
  3056. * Return the fields array of the current row as an object for convenience.
  3057. * The default case is lowercase field names.
  3058. *
  3059. * @return the object with the properties set to the fields of the current row
  3060. */
  3061. function FetchObj()
  3062. {
  3063. $o = $this->FetchObject(false);
  3064. return $o;
  3065. }
  3066. /**
  3067. * Return the fields array of the current row as an object for convenience.
  3068. * The default case is uppercase.
  3069. *
  3070. * @param $isupper to set the object property names to uppercase
  3071. *
  3072. * @return the object with the properties set to the fields of the current row
  3073. */
  3074. function FetchObject($isupper=true)
  3075. {
  3076. if (empty($this->_obj)) {
  3077. $this->_obj = new ADOFetchObj();
  3078. $this->_names = array();
  3079. for ($i=0; $i <$this->_numOfFields; $i++) {
  3080. $f = $this->FetchField($i);
  3081. $this->_names[] = $f->name;
  3082. }
  3083. }
  3084. $i = 0;
  3085. if (PHP_VERSION >= 5) $o = clone($this->_obj);
  3086. else $o = $this->_obj;
  3087. for ($i=0; $i <$this->_numOfFields; $i++) {
  3088. $name = $this->_names[$i];
  3089. if ($isupper) $n = strtoupper($name);
  3090. else $n = $name;
  3091. $o->$n = $this->Fields($name);
  3092. }
  3093. return $o;
  3094. }
  3095. /**
  3096. * Return the fields array of the current row as an object for convenience.
  3097. * The default is lower-case field names.
  3098. *
  3099. * @return the object with the properties set to the fields of the current row,
  3100. * or false if EOF
  3101. *
  3102. * Fixed bug reported by tim@orotech.net
  3103. */
  3104. function FetchNextObj()
  3105. {
  3106. $o = $this->FetchNextObject(false);
  3107. return $o;
  3108. }
  3109. /**
  3110. * Return the fields array of the current row as an object for convenience.
  3111. * The default is upper case field names.
  3112. *
  3113. * @param $isupper to set the object property names to uppercase
  3114. *
  3115. * @return the object with the properties set to the fields of the current row,
  3116. * or false if EOF
  3117. *
  3118. * Fixed bug reported by tim@orotech.net
  3119. */
  3120. function FetchNextObject($isupper=true)
  3121. {
  3122. $o = false;
  3123. if ($this->_numOfRows != 0 && !$this->EOF) {
  3124. $o = $this->FetchObject($isupper);
  3125. $this->_currentRow++;
  3126. if ($this->_fetch()) return $o;
  3127. }
  3128. $this->EOF = true;
  3129. return $o;
  3130. }
  3131. /**
  3132. * Get the metatype of the column. This is used for formatting. This is because
  3133. * many databases use different names for the same type, so we transform the original
  3134. * type to our standardised version which uses 1 character codes:
  3135. *
  3136. * @param t is the type passed in. Normally is ADOFieldObject->type.
  3137. * @param len is the maximum length of that field. This is because we treat character
  3138. * fields bigger than a certain size as a 'B' (blob).
  3139. * @param fieldobj is the field object returned by the database driver. Can hold
  3140. * additional info (eg. primary_key for mysql).
  3141. *
  3142. * @return the general type of the data:
  3143. * C for character < 250 chars
  3144. * X for teXt (>= 250 chars)
  3145. * B for Binary
  3146. * N for numeric or floating point
  3147. * D for date
  3148. * T for timestamp
  3149. * L for logical/Boolean
  3150. * I for integer
  3151. * R for autoincrement counter/integer
  3152. *
  3153. *
  3154. */
  3155. function MetaType($t,$len=-1,$fieldobj=false)
  3156. {
  3157. if (is_object($t)) {
  3158. $fieldobj = $t;
  3159. $t = $fieldobj->type;
  3160. $len = $fieldobj->max_length;
  3161. }
  3162. // changed in 2.32 to hashing instead of switch stmt for speed...
  3163. static $typeMap = array(
  3164. 'VARCHAR' => 'C',
  3165. 'VARCHAR2' => 'C',
  3166. 'CHAR' => 'C',
  3167. 'C' => 'C',
  3168. 'STRING' => 'C',
  3169. 'NCHAR' => 'C',
  3170. 'NVARCHAR' => 'C',
  3171. 'VARYING' => 'C',
  3172. 'BPCHAR' => 'C',
  3173. 'CHARACTER' => 'C',
  3174. 'INTERVAL' => 'C', # Postgres
  3175. 'MACADDR' => 'C', # postgres
  3176. 'VAR_STRING' => 'C', # mysql
  3177. ##
  3178. 'LONGCHAR' => 'X',
  3179. 'TEXT' => 'X',
  3180. 'NTEXT' => 'X',
  3181. 'M' => 'X',
  3182. 'X' => 'X',
  3183. 'CLOB' => 'X',
  3184. 'NCLOB' => 'X',
  3185. 'LVARCHAR' => 'X',
  3186. ##
  3187. 'BLOB' => 'B',
  3188. 'IMAGE' => 'B',
  3189. 'BINARY' => 'B',
  3190. 'VARBINARY' => 'B',
  3191. 'LONGBINARY' => 'B',
  3192. 'B' => 'B',
  3193. ##
  3194. 'YEAR' => 'D', // mysql
  3195. 'DATE' => 'D',
  3196. 'D' => 'D',
  3197. ##
  3198. 'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
  3199. ##
  3200. 'SMALLDATETIME' => 'T',
  3201. 'TIME' => 'T',
  3202. 'TIMESTAMP' => 'T',
  3203. 'DATETIME' => 'T',
  3204. 'TIMESTAMPTZ' => 'T',
  3205. 'T' => 'T',
  3206. 'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
  3207. ##
  3208. 'BOOL' => 'L',
  3209. 'BOOLEAN' => 'L',
  3210. 'BIT' => 'L',
  3211. 'L' => 'L',
  3212. ##
  3213. 'COUNTER' => 'R',
  3214. 'R' => 'R',
  3215. 'SERIAL' => 'R', // ifx
  3216. 'INT IDENTITY' => 'R',
  3217. ##
  3218. 'INT' => 'I',
  3219. 'INT2' => 'I',
  3220. 'INT4' => 'I',
  3221. 'INT8' => 'I',
  3222. 'INTEGER' => 'I',
  3223. 'INTEGER UNSIGNED' => 'I',
  3224. 'SHORT' => 'I',
  3225. 'TINYINT' => 'I',
  3226. 'SMALLINT' => 'I',
  3227. 'I' => 'I',
  3228. ##
  3229. 'LONG' => 'N', // interbase is numeric, oci8 is blob
  3230. 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
  3231. 'DECIMAL' => 'N',
  3232. 'DEC' => 'N',
  3233. 'REAL' => 'N',
  3234. 'DOUBLE' => 'N',
  3235. 'DOUBLE PRECISION' => 'N',
  3236. 'SMALLFLOAT' => 'N',
  3237. 'FLOAT' => 'N',
  3238. 'NUMBER' => 'N',
  3239. 'NUM' => 'N',
  3240. 'NUMERIC' => 'N',
  3241. 'MONEY' => 'N',
  3242. ## informix 9.2
  3243. 'SQLINT' => 'I',
  3244. 'SQLSERIAL' => 'I',
  3245. 'SQLSMINT' => 'I',
  3246. 'SQLSMFLOAT' => 'N',
  3247. 'SQLFLOAT' => 'N',
  3248. 'SQLMONEY' => 'N',
  3249. 'SQLDECIMAL' => 'N',
  3250. 'SQLDATE' => 'D',
  3251. 'SQLVCHAR' => 'C',
  3252. 'SQLCHAR' => 'C',
  3253. 'SQLDTIME' => 'T',
  3254. 'SQLINTERVAL' => 'N',
  3255. 'SQLBYTES' => 'B',
  3256. 'SQLTEXT' => 'X',
  3257. ## informix 10
  3258. "SQLINT8" => 'I8',
  3259. "SQLSERIAL8" => 'I8',
  3260. "SQLNCHAR" => 'C',
  3261. "SQLNVCHAR" => 'C',
  3262. "SQLLVARCHAR" => 'X',
  3263. "SQLBOOL" => 'L'
  3264. );
  3265. $tmap = false;
  3266. $t = strtoupper($t);
  3267. $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
  3268. switch ($tmap) {
  3269. case 'C':
  3270. // is the char field is too long, return as text field...
  3271. if ($this->blobSize >= 0) {
  3272. if ($len > $this->blobSize) return 'X';
  3273. } else if ($len > 250) {
  3274. return 'X';
  3275. }
  3276. return 'C';
  3277. case 'I':
  3278. if (!empty($fieldobj->primary_key)) return 'R';
  3279. return 'I';
  3280. case false:
  3281. return 'N';
  3282. case 'B':
  3283. if (isset($fieldobj->binary))
  3284. return ($fieldobj->binary) ? 'B' : 'X';
  3285. return 'B';
  3286. case 'D':
  3287. if (!empty($this->connection) && !empty($this->connection->datetime)) return 'T';
  3288. return 'D';
  3289. default:
  3290. if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
  3291. return $tmap;
  3292. }
  3293. }
  3294. function _close() {}
  3295. /**
  3296. * set/returns the current recordset page when paginating
  3297. */
  3298. function AbsolutePage($page=-1)
  3299. {
  3300. if ($page != -1) $this->_currentPage = $page;
  3301. return $this->_currentPage;
  3302. }
  3303. /**
  3304. * set/returns the status of the atFirstPage flag when paginating
  3305. */
  3306. function AtFirstPage($status=false)
  3307. {
  3308. if ($status != false) $this->_atFirstPage = $status;
  3309. return $this->_atFirstPage;
  3310. }
  3311. function LastPageNo($page = false)
  3312. {
  3313. if ($page != false) $this->_lastPageNo = $page;
  3314. return $this->_lastPageNo;
  3315. }
  3316. /**
  3317. * set/returns the status of the atLastPage flag when paginating
  3318. */
  3319. function AtLastPage($status=false)
  3320. {
  3321. if ($status != false) $this->_atLastPage = $status;
  3322. return $this->_atLastPage;
  3323. }
  3324. } // end class ADORecordSet
  3325. //==============================================================================================
  3326. // CLASS ADORecordSet_array
  3327. //==============================================================================================
  3328. /**
  3329. * This class encapsulates the concept of a recordset created in memory
  3330. * as an array. This is useful for the creation of cached recordsets.
  3331. *
  3332. * Note that the constructor is different from the standard ADORecordSet
  3333. */
  3334. class ADORecordSet_array extends ADORecordSet
  3335. {
  3336. var $databaseType = 'array';
  3337. var $_array; // holds the 2-dimensional data array
  3338. var $_types; // the array of types of each column (C B I L M)
  3339. var $_colnames; // names of each column in array
  3340. var $_skiprow1; // skip 1st row because it holds column names
  3341. var $_fieldobjects; // holds array of field objects
  3342. var $canSeek = true;
  3343. var $affectedrows = false;
  3344. var $insertid = false;
  3345. var $sql = '';
  3346. var $compat = false;
  3347. /**
  3348. * Constructor
  3349. *
  3350. */
  3351. function ADORecordSet_array($fakeid=1)
  3352. {
  3353. global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
  3354. // fetch() on EOF does not delete $this->fields
  3355. $this->compat = !empty($ADODB_COMPAT_FETCH);
  3356. $this->ADORecordSet($fakeid); // fake queryID
  3357. $this->fetchMode = $ADODB_FETCH_MODE;
  3358. }
  3359. function _transpose($addfieldnames=true)
  3360. {
  3361. global $ADODB_INCLUDED_LIB;
  3362. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  3363. $hdr = true;
  3364. $fobjs = $addfieldnames ? $this->_fieldobjects : false;
  3365. adodb_transpose($this->_array, $newarr, $hdr, $fobjs);
  3366. //adodb_pr($newarr);
  3367. $this->_skiprow1 = false;
  3368. $this->_array = $newarr;
  3369. $this->_colnames = $hdr;
  3370. adodb_probetypes($newarr,$this->_types);
  3371. $this->_fieldobjects = array();
  3372. foreach($hdr as $k => $name) {
  3373. $f = new ADOFieldObject();
  3374. $f->name = $name;
  3375. $f->type = $this->_types[$k];
  3376. $f->max_length = -1;
  3377. $this->_fieldobjects[] = $f;
  3378. }
  3379. $this->fields = reset($this->_array);
  3380. $this->_initrs();
  3381. }
  3382. /**
  3383. * Setup the array.
  3384. *
  3385. * @param array is a 2-dimensional array holding the data.
  3386. * The first row should hold the column names
  3387. * unless paramter $colnames is used.
  3388. * @param typearr holds an array of types. These are the same types
  3389. * used in MetaTypes (C,B,L,I,N).
  3390. * @param [colnames] array of column names. If set, then the first row of
  3391. * $array should not hold the column names.
  3392. */
  3393. function InitArray($array,$typearr,$colnames=false)
  3394. {
  3395. $this->_array = $array;
  3396. $this->_types = $typearr;
  3397. if ($colnames) {
  3398. $this->_skiprow1 = false;
  3399. $this->_colnames = $colnames;
  3400. } else {
  3401. $this->_skiprow1 = true;
  3402. $this->_colnames = $array[0];
  3403. }
  3404. $this->Init();
  3405. }
  3406. /**
  3407. * Setup the Array and datatype file objects
  3408. *
  3409. * @param array is a 2-dimensional array holding the data.
  3410. * The first row should hold the column names
  3411. * unless paramter $colnames is used.
  3412. * @param fieldarr holds an array of ADOFieldObject's.
  3413. */
  3414. function InitArrayFields(&$array,&$fieldarr)
  3415. {
  3416. $this->_array = $array;
  3417. $this->_skiprow1= false;
  3418. if ($fieldarr) {
  3419. $this->_fieldobjects = $fieldarr;
  3420. }
  3421. $this->Init();
  3422. }
  3423. function GetArray($nRows=-1)
  3424. {
  3425. if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
  3426. return $this->_array;
  3427. } else {
  3428. $arr = ADORecordSet::GetArray($nRows);
  3429. return $arr;
  3430. }
  3431. }
  3432. function _initrs()
  3433. {
  3434. $this->_numOfRows = sizeof($this->_array);
  3435. if ($this->_skiprow1) $this->_numOfRows -= 1;
  3436. $this->_numOfFields =(isset($this->_fieldobjects)) ?
  3437. sizeof($this->_fieldobjects):sizeof($this->_types);
  3438. }
  3439. /* Use associative array to get fields array */
  3440. function Fields($colname)
  3441. {
  3442. $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode;
  3443. if ($mode & ADODB_FETCH_ASSOC) {
  3444. if (!isset($this->fields[$colname]) && !is_null($this->fields[$colname])) $colname = strtolower($colname);
  3445. return $this->fields[$colname];
  3446. }
  3447. if (!$this->bind) {
  3448. $this->bind = array();
  3449. for ($i=0; $i < $this->_numOfFields; $i++) {
  3450. $o = $this->FetchField($i);
  3451. $this->bind[strtoupper($o->name)] = $i;
  3452. }
  3453. }
  3454. return $this->fields[$this->bind[strtoupper($colname)]];
  3455. }
  3456. function FetchField($fieldOffset = -1)
  3457. {
  3458. if (isset($this->_fieldobjects)) {
  3459. return $this->_fieldobjects[$fieldOffset];
  3460. }
  3461. $o = new ADOFieldObject();
  3462. $o->name = $this->_colnames[$fieldOffset];
  3463. $o->type = $this->_types[$fieldOffset];
  3464. $o->max_length = -1; // length not known
  3465. return $o;
  3466. }
  3467. function _seek($row)
  3468. {
  3469. if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
  3470. $this->_currentRow = $row;
  3471. if ($this->_skiprow1) $row += 1;
  3472. $this->fields = $this->_array[$row];
  3473. return true;
  3474. }
  3475. return false;
  3476. }
  3477. function MoveNext()
  3478. {
  3479. if (!$this->EOF) {
  3480. $this->_currentRow++;
  3481. $pos = $this->_currentRow;
  3482. if ($this->_numOfRows <= $pos) {
  3483. if (!$this->compat) $this->fields = false;
  3484. } else {
  3485. if ($this->_skiprow1) $pos += 1;
  3486. $this->fields = $this->_array[$pos];
  3487. return true;
  3488. }
  3489. $this->EOF = true;
  3490. }
  3491. return false;
  3492. }
  3493. function _fetch()
  3494. {
  3495. $pos = $this->_currentRow;
  3496. if ($this->_numOfRows <= $pos) {
  3497. if (!$this->compat) $this->fields = false;
  3498. return false;
  3499. }
  3500. if ($this->_skiprow1) $pos += 1;
  3501. $this->fields = $this->_array[$pos];
  3502. return true;
  3503. }
  3504. function _close()
  3505. {
  3506. return true;
  3507. }
  3508. } // ADORecordSet_array
  3509. //==============================================================================================
  3510. // HELPER FUNCTIONS
  3511. //==============================================================================================
  3512. /**
  3513. * Synonym for ADOLoadCode. Private function. Do not use.
  3514. *
  3515. * @deprecated
  3516. */
  3517. function ADOLoadDB($dbType)
  3518. {
  3519. return ADOLoadCode($dbType);
  3520. }
  3521. /**
  3522. * Load the code for a specific database driver. Private function. Do not use.
  3523. */
  3524. function ADOLoadCode($dbType)
  3525. {
  3526. global $ADODB_LASTDB;
  3527. if (!$dbType) return false;
  3528. $db = strtolower($dbType);
  3529. switch ($db) {
  3530. case 'ado':
  3531. if (PHP_VERSION >= 5) $db = 'ado5';
  3532. $class = 'ado';
  3533. break;
  3534. case 'ifx':
  3535. case 'maxsql': $class = $db = 'mysqlt'; break;
  3536. case 'postgres':
  3537. case 'postgres8':
  3538. case 'pgsql': $class = $db = 'postgres7'; break;
  3539. default:
  3540. $class = $db; break;
  3541. }
  3542. $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
  3543. @include_once($file);
  3544. $ADODB_LASTDB = $class;
  3545. if (class_exists("ADODB_" . $class)) return $class;
  3546. //ADOConnection::outp(adodb_pr(get_declared_classes(),true));
  3547. if (!file_exists($file)) ADOConnection::outp("Missing file: $file");
  3548. else ADOConnection::outp("Syntax error in file: $file");
  3549. return false;
  3550. }
  3551. /**
  3552. * synonym for ADONewConnection for people like me who cannot remember the correct name
  3553. */
  3554. function NewADOConnection($db='')
  3555. {
  3556. $tmp = ADONewConnection($db);
  3557. return $tmp;
  3558. }
  3559. /**
  3560. * Instantiate a new Connection class for a specific database driver.
  3561. *
  3562. * @param [db] is the database Connection object to create. If undefined,
  3563. * use the last database driver that was loaded by ADOLoadCode().
  3564. *
  3565. * @return the freshly created instance of the Connection class.
  3566. */
  3567. function ADONewConnection($db='')
  3568. {
  3569. GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
  3570. if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  3571. $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
  3572. $false = false;
  3573. if (($at = strpos($db,'://')) !== FALSE) {
  3574. $origdsn = $db;
  3575. $fakedsn = 'fake'.substr($origdsn,$at);
  3576. if (($at2 = strpos($origdsn,'@/')) !== FALSE) {
  3577. // special handling of oracle, which might not have host
  3578. $fakedsn = str_replace('@/','@adodb-fakehost/',$fakedsn);
  3579. }
  3580. $dsna = @parse_url($fakedsn);
  3581. if (!$dsna) {
  3582. return $false;
  3583. }
  3584. $dsna['scheme'] = substr($origdsn,0,$at);
  3585. if ($at2 !== FALSE) {
  3586. $dsna['host'] = '';
  3587. }
  3588. if (strncmp($origdsn,'pdo',3) == 0) {
  3589. $sch = explode('_',$dsna['scheme']);
  3590. if (sizeof($sch)>1) {
  3591. $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
  3592. if ($sch[1] == 'sqlite')
  3593. $dsna['host'] = rawurlencode($sch[1].':'.rawurldecode($dsna['host']));
  3594. else
  3595. $dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host']));
  3596. $dsna['scheme'] = 'pdo';
  3597. }
  3598. }
  3599. $db = @$dsna['scheme'];
  3600. if (!$db) return $false;
  3601. $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
  3602. $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : '';
  3603. $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : '';
  3604. $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial /
  3605. if (isset($dsna['query'])) {
  3606. $opt1 = explode('&',$dsna['query']);
  3607. foreach($opt1 as $k => $v) {
  3608. $arr = explode('=',$v);
  3609. $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1;
  3610. }
  3611. } else $opt = array();
  3612. }
  3613. /*
  3614. * phptype: Database backend used in PHP (mysql, odbc etc.)
  3615. * dbsyntax: Database used with regards to SQL syntax etc.
  3616. * protocol: Communication protocol to use (tcp, unix etc.)
  3617. * hostspec: Host specification (hostname[:port])
  3618. * database: Database to use on the DBMS server
  3619. * username: User name for login
  3620. * password: Password for login
  3621. */
  3622. if (!empty($ADODB_NEWCONNECTION)) {
  3623. $obj = $ADODB_NEWCONNECTION($db);
  3624. }
  3625. if(empty($obj)) {
  3626. if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
  3627. if (empty($db)) $db = $ADODB_LASTDB;
  3628. if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
  3629. if (!$db) {
  3630. if (isset($origdsn)) $db = $origdsn;
  3631. if ($errorfn) {
  3632. // raise an error
  3633. $ignore = false;
  3634. $errorfn('ADONewConnection', 'ADONewConnection', -998,
  3635. "could not load the database driver for '$db'",
  3636. $db,false,$ignore);
  3637. } else
  3638. ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
  3639. return $false;
  3640. }
  3641. $cls = 'ADODB_'.$db;
  3642. if (!class_exists($cls)) {
  3643. adodb_backtrace();
  3644. return $false;
  3645. }
  3646. $obj = new $cls();
  3647. }
  3648. # constructor should not fail
  3649. if ($obj) {
  3650. if ($errorfn) $obj->raiseErrorFn = $errorfn;
  3651. if (isset($dsna)) {
  3652. if (isset($dsna['port'])) $obj->port = $dsna['port'];
  3653. foreach($opt as $k => $v) {
  3654. switch(strtolower($k)) {
  3655. case 'new':
  3656. $nconnect = true; $persist = true; break;
  3657. case 'persist':
  3658. case 'persistent': $persist = $v; break;
  3659. case 'debug': $obj->debug = (integer) $v; break;
  3660. #ibase
  3661. case 'role': $obj->role = $v; break;
  3662. case 'dialect': $obj->dialect = (integer) $v; break;
  3663. case 'charset': $obj->charset = $v; $obj->charSet=$v; break;
  3664. case 'buffers': $obj->buffers = $v; break;
  3665. case 'fetchmode': $obj->SetFetchMode($v); break;
  3666. #ado
  3667. case 'charpage': $obj->charPage = $v; break;
  3668. #mysql, mysqli
  3669. case 'clientflags': $obj->clientFlags = $v; break;
  3670. #mysql, mysqli, postgres
  3671. case 'port': $obj->port = $v; break;
  3672. #mysqli
  3673. case 'socket': $obj->socket = $v; break;
  3674. #oci8
  3675. case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break;
  3676. case 'cachesecs': $obj->cacheSecs = $v; break;
  3677. case 'memcache':
  3678. $varr = explode(':',$v);
  3679. $vlen = sizeof($varr);
  3680. if ($vlen == 0) break;
  3681. $obj->memCache = true;
  3682. $obj->memCacheHost = explode(',',$varr[0]);
  3683. if ($vlen == 1) break;
  3684. $obj->memCachePort = $varr[1];
  3685. if ($vlen == 2) break;
  3686. $obj->memCacheCompress = $varr[2] ? true : false;
  3687. break;
  3688. }
  3689. }
  3690. if (empty($persist))
  3691. $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3692. else if (empty($nconnect))
  3693. $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3694. else
  3695. $ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3696. if (!$ok) return $false;
  3697. }
  3698. }
  3699. return $obj;
  3700. }
  3701. // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary
  3702. function _adodb_getdriver($provider,$drivername,$perf=false)
  3703. {
  3704. switch ($provider) {
  3705. case 'odbtp': if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6);
  3706. case 'odbc' : if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5);
  3707. case 'ado' : if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4);
  3708. case 'native': break;
  3709. default:
  3710. return $provider;
  3711. }
  3712. switch($drivername) {
  3713. case 'mysqlt':
  3714. case 'mysqli':
  3715. $drivername='mysql';
  3716. break;
  3717. case 'postgres7':
  3718. case 'postgres8':
  3719. $drivername = 'postgres';
  3720. break;
  3721. case 'firebird15': $drivername = 'firebird'; break;
  3722. case 'oracle': $drivername = 'oci8'; break;
  3723. case 'access': if ($perf) $drivername = ''; break;
  3724. case 'db2' : break;
  3725. case 'sapdb' : break;
  3726. default:
  3727. $drivername = 'generic';
  3728. break;
  3729. }
  3730. return $drivername;
  3731. }
  3732. function NewPerfMonitor(&$conn)
  3733. {
  3734. $false = false;
  3735. $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
  3736. if (!$drivername || $drivername == 'generic') return $false;
  3737. include_once(ADODB_DIR.'/adodb-perf.inc.php');
  3738. @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
  3739. $class = "Perf_$drivername";
  3740. if (!class_exists($class)) return $false;
  3741. $perf = new $class($conn);
  3742. return $perf;
  3743. }
  3744. function NewDataDictionary(&$conn,$drivername=false)
  3745. {
  3746. $false = false;
  3747. if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
  3748. include_once(ADODB_DIR.'/adodb-lib.inc.php');
  3749. include_once(ADODB_DIR.'/adodb-datadict.inc.php');
  3750. $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
  3751. if (!file_exists($path)) {
  3752. ADOConnection::outp("Dictionary driver '$path' not available");
  3753. return $false;
  3754. }
  3755. include_once($path);
  3756. $class = "ADODB2_$drivername";
  3757. $dict = new $class();
  3758. $dict->dataProvider = $conn->dataProvider;
  3759. $dict->connection = $conn;
  3760. $dict->upperName = strtoupper($drivername);
  3761. $dict->quote = $conn->nameQuote;
  3762. if (!empty($conn->_connectionID))
  3763. $dict->serverInfo = $conn->ServerInfo();
  3764. return $dict;
  3765. }
  3766. /*
  3767. Perform a print_r, with pre tags for better formatting.
  3768. */
  3769. function adodb_pr($var,$as_string=false)
  3770. {
  3771. if ($as_string) ob_start();
  3772. if (isset($_SERVER['HTTP_USER_AGENT'])) {
  3773. echo " <pre>\n";print_r($var);echo "</pre>\n";
  3774. } else
  3775. print_r($var);
  3776. if ($as_string) {
  3777. $s = ob_get_contents();
  3778. ob_end_clean();
  3779. return $s;
  3780. }
  3781. }
  3782. /*
  3783. Perform a stack-crawl and pretty print it.
  3784. @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
  3785. @param levels Number of levels to display
  3786. */
  3787. function adodb_backtrace($printOrArr=true,$levels=9999,$ishtml=null)
  3788. {
  3789. global $ADODB_INCLUDED_LIB;
  3790. if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  3791. return _adodb_backtrace($printOrArr,$levels,0,$ishtml);
  3792. }
  3793. }
  3794. ?>