PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/selfeky/xclusivescardwebsite
PHP | 4481 lines | 2733 code | 566 blank | 1182 comment | 619 complexity | 942ab99cd514aea7d34294964a3d4f00 MD5 | raw file

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

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

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